位置通过android中的服务获取后台

时间:2017-09-21 09:58:41

标签: android

如何在Android中通过GPS系统服务获取用户位置?我当前代码中的错误是什么?

  

我在我的项目中尝试了这个代码,但第一次只有我得到位置。一世   尝试在关闭应用程序时连续获取当前位置。   但我无法持续获得位置。

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.content.ContextCompat;
import android.util.Log;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Jana on 9/19/2017.
 */

public class LocationUpdaterService extends Service
{
    public static final int TWO_MINUTES = 1000; // 120 seconds
    public static Boolean isRunning = false;

    public LocationManager mLocationManager;
    public LocationUpdaterListener mLocationListener;
    public Location previousBestLocation = null;


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    private Timer mTimer;
    @Override
    public void onCreate() {
        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        mLocationListener = new LocationUpdaterListener();
        mTimer = new Timer();
        mTimer.schedule(timerTask, 2000, 10 * 1000);
      /*  Handler mHandler = new Handler();
        mHandler.postDelayed(mHandlerTask, TWO_MINUTES);*/

        super.onCreate();
    }



    TimerTask timerTask = new TimerTask() {

        @Override
        public void run() {
            Log.e("Log", "Running");
            mHandler.postDelayed(mHandlerTask, TWO_MINUTES);


        }
    };
    Handler mHandler = new Handler();
    Runnable mHandlerTask = new Runnable(){
        @Override
        public void run() {
            if (!isRunning) {
                startListening();
            }
           // mHandler.postDelayed(mHandlerTask, TWO_MINUTES);
        }
    };

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mHandlerTask.run();
        return START_STICKY;
    }

   /* @Override
    public void onDestroy() {
        stopListening();
        mHandler.removeCallbacks(mHandlerTask);
        super.onDestroy();
    }*/

    private void startListening() {
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            if (mLocationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER))
                mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mLocationListener);

            if (mLocationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER))
                mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
        }
        isRunning = true;
    }

    private void stopListening() {
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            mLocationManager.removeUpdates(mLocationListener);
        }
        isRunning = false;
    }

    public class LocationUpdaterListener implements LocationListener
    {
        @Override
        public void onLocationChanged(Location location) {

            Log.e("testing","location changed = "+location);
            if (isBetterLocation(location, previousBestLocation)) {
                previousBestLocation = location;
                try {
                    // Script to post location data to server..
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
                finally {
                    stopListening();
                }
            }
        }

        @Override
        public void onProviderDisabled(String provider) {
            stopListening();
        }

        @Override
        public void onProviderEnabled(String provider) { }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) { }
    }

    protected boolean isBetterLocation(Location location, Location currentBestLocation) {
        if (currentBestLocation == null) {
            // A new location is always better than no location
            return true;
        }

        // Check whether the new location fix is newer or older
        long timeDelta = location.getTime() - currentBestLocation.getTime();
        boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
        boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
        boolean isNewer = timeDelta > 0;

        // If it's been more than two minutes since the current location, use the new location
        // because the user has likely moved
        if (isSignificantlyNewer) {
            return true;
            // If the new location is more than two minutes older, it must be worse
        } else if (isSignificantlyOlder) {
            return false;
        }

        // Check whether the new location fix is more or less accurate
        int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
        boolean isLessAccurate = accuracyDelta > 0;
        boolean isMoreAccurate = accuracyDelta < 0;
        boolean isSignificantlyLessAccurate = accuracyDelta > 200;

        // Check if the old and new location are from the same provider
        boolean isFromSameProvider = isSameProvider(location.getProvider(), currentBestLocation.getProvider());

        // Determine location quality using a combination of timeliness and accuracy
        if (isMoreAccurate) {
            return true;
        } else if (isNewer && !isLessAccurate) {
            return true;
        } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
            return true;
        }
        return false;
    }

    /** Checks whether two providers are the same */
    private boolean isSameProvider(String provider1, String provider2) {
        if (provider1 == null) {
            return provider2 == null;
        }
        return provider1.equals(provider2);
    }
}

任何人都可以帮助解决这个问题。 提前致谢

1 个答案:

答案 0 :(得分:0)

我在应用程序关闭时获得了在后台获取位置的解决方案。

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;
import android.widget.Toast;

import com.github.kayvannj.permission_utils.Func2;
import com.github.kayvannj.permission_utils.PermissionUtil;

import butterknife.Bind;
import butterknife.ButterKnife;
import jana.g2evolution.transitoak.R;

public class Activity_DriverTracking extends AppCompatActivity implements ILocationConstants {

    //protected static final String TAG = Activity_DriverTracking.class.getSimpleName();




    /**
     * Receiver listening to Location updates and updating UI in activity
     */
    private LocationReceiver locationReceiver;

    /**
     * Permission util with callback mechanism to avoid boilerplate code
     * <p/>
     * https://github.com/kayvannj/PermissionUtil
     */
    private PermissionUtil.PermissionRequestObject mBothPermissionRequest;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity__driver_tracking);



        locationReceiver = new LocationReceiver();


    }


    private void startLocationService() {

        Intent serviceIntent = new Intent(this, LocationService.class);
        startService(serviceIntent);

    }

    @Override
    protected void onStart() {
        super.onStart();

        LocalBroadcastManager.getInstance(this).registerReceiver(locationReceiver, new IntentFilter(LOACTION_ACTION));


        /**
         * Runtime permissions are required on Android M and above to access User's location
         */
        if (AppUtils.hasM() && !(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)) {

            askPermissions();

        } else {

            startLocationService();

        }

    }

    /**
     * Ask user for permissions to access GPS location on Android M
     */
    public void askPermissions() {
        mBothPermissionRequest =
                PermissionUtil.with(this).request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION).onResult(
                        new Func2() {
                            @Override
                            protected void call(int requestCode, String[] permissions, int[] grantResults) {

                                if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {

                                    startLocationService();

                                } else {

                                    //Toast.makeText(Activity_DriverTracking.this, R.string.permission_denied, Toast.LENGTH_LONG).show();
                                }
                            }

                        }).ask(PERMISSION_ACCESS_LOCATION_CODE);

    }


    @Override
    protected void onStop() {
        super.onStop();

        LocalBroadcastManager.getInstance(this).unregisterReceiver(locationReceiver);
    }

    private class LocationReceiver extends BroadcastReceiver {


        @Override
        public void onReceive(Context context, Intent intent) {


            if (null != intent && intent.getAction().equals(LOACTION_ACTION)) {

                String locationData = intent.getStringExtra(LOCATION_MESSAGE);

               // tvLocationData.setText(locationData);
            }

        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        if (null != mBothPermissionRequest) {
            mBothPermissionRequest.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


}

应用偏好

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;

import java.util.Map;
import java.util.Set;

/**
 * @author Nayanesh Gupte
 */
public class AppPreferences {

    private SharedPreferences mPreferences;

    /**
     * Constructor to initialize SharedPreferences object with default preferences.
     *
     * @param context Represents current state of the application/object.
     */
    public AppPreferences(Context context) {
        mPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    }

    /**
     * Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and
     * modify its values.
     *
     * @param context Represents current state of the application/object
     * @param name    Desired preferences file name.
     * @param mode    Operating mode like MODE_PRIVATE,MODE_WORLD_READABLE,etc.
     */
    public AppPreferences(Context context, String name, int mode) {
        mPreferences = context.getSharedPreferences(name, mode);
    }

    /**
     * Sets the default values from an XML preference file
     *
     * @param context   The context of the shared preferences.
     * @param resId     The resource ID of the preference XML file.
     * @param readAgain Whether to re-read the default values.
     * @throws Exception if context is null or unable to set default values.
     */

    public void setDefaultValues(Context context, int resId, boolean readAgain) {
        PreferenceManager.setDefaultValues(context, resId, readAgain);
    }

    /**
     * Set a String value in the preferences.
     *
     * @param key   The name of the preference to modify.
     * @param value The new value for the preference.
     * @throws Exception if key or value is null.
     */
    public void putString(String key, String value) {
        try {
            Editor prefEdit = mPreferences.edit();
            prefEdit.putString(key, value);
            prefEdit.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Retrieve a String value from the preferences.
     *
     * @param key The name of the preference to retrieve.
     * @return Returns the preference value if it exists, or defValue.
     * @throws ClassCastException if there is a preference with this name that is not a String.
     */
    public String getString(String key, String defValue) throws ClassCastException {
        return mPreferences.getString(key, defValue);
    }

    /**
     * Set a Integer value in the preferences.
     *
     * @param key   The name of the preference to modify.
     * @param value The new value for the preference.
     * @throws Exception if key or value is null.
     */
    public void putInt(String key, int value) {
        try {
            Editor prefEdit = mPreferences.edit();
            prefEdit.putInt(key, value);
            prefEdit.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Retrieve a Integer value from the preferences.
     *
     * @param key The name of the preference to retrieve.
     * @return Returns the preference value if it exists, or defValue.
     * @throws ClassCastException if there is a preference with this name that is not a int.
     */
    public int getInt(String key, int defValue) throws ClassCastException {
        return mPreferences.getInt(key, defValue);
    }

    /**
     * Set a Long value in the preferences.
     *
     * @param key   The name of the preference to modify.
     * @param value The new value for the preference.
     * @throws Exception if key or value is null.
     */
    public void putLong(String key, long value) {
        try {
            Editor prefEdit = mPreferences.edit();
            prefEdit.putLong(key, value);
            prefEdit.commit();
        } catch (Exception e) {

            e.printStackTrace();

        }
    }

    /**
     * Retrieve a Long value from the preferences.
     *
     * @param key The name of the preference to retrieve.
     * @return Returns the preference value if it exists, or defValue.
     * @throws ClassCastException if there is a preference with this name that is not a long.
     */
    public long getLong(String key, long defValue) throws ClassCastException {
        return mPreferences.getLong(key, defValue);
    }

    /**
     * Set a Boolean value in the preferences.
     *
     * @param key   The name of the preference to modify.
     * @param value The new value for the preference.
     * @throws Exception if key or value is null.
     */
    public void putBoolean(String key, Boolean value) {
        try {
            Editor prefEdit = mPreferences.edit();
            prefEdit.putBoolean(key, value);
            prefEdit.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Retrieve a Boolean value from the preferences.
     *
     * @param key The name of the preference to retrieve.
     * @return Returns the preference value if it exists, or defValue.
     * @throws ClassCastException if there is a preference with this name that is not a boolean.
     */
    public boolean getBoolean(String key, boolean defValue) throws ClassCastException {
        return mPreferences.getBoolean(key, defValue);
    }

    /**
     * Set a Float value in the preferences.
     *
     * @param key   The name of the preference to modify.
     * @param value The new value for the preference.
     * @throws Exception if key or value is null.
     */
    public void putFloat(String key, float value) {
        try {
            Editor prefEdit = mPreferences.edit();
            prefEdit.putFloat(key, value);
            prefEdit.apply();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Retrieve a Float value from the preferences.
     *
     * @param key The name of the preference to retrieve.
     * @return Returns the preference value if it exists, or defValue.
     * @throws ClassCastException if there is a preference with this name that is not a float.
     */
    public float getFloat(String key, float defValue) throws ClassCastException {
        return mPreferences.getFloat(key, defValue);
    }

    /**
     * Retrieve all values from the preferences.
     *
     * @return Map<String,?> containing all values from Preferences.
     * @throws NullPointerException if no data in preferences.
     */
    public Map<String, ?> getAll() throws NullPointerException {
        return mPreferences.getAll();
    }

    /**
     * Checks whether the preferences contains a preference.
     *
     * @param key The name of the preference to check.
     * @return true if the preference exists in the preferences, otherwise. false.
     * @throws Exception if key is null.
     */
    public Boolean contains(String key) {
        return mPreferences.contains(key);
    }

    /**
     * Method to remove all values from preferences.
     *
     * @throws Exception if <code>mPreferences</code> is null.
     */
    public void clearPreferences() {
        try {
            Editor prefEdit = mPreferences.edit();
            prefEdit.clear();
            prefEdit.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Method to remove key
     *
     * @param key The name of the preference to remove.
     * @throws Exception if key is null.
     */
    public void removeKey(String key) {
        try {
            Editor prefEdit = mPreferences.edit();
            prefEdit.remove(key);
            prefEdit.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Set a {@code Set<String>} in the preferences.
     *
     * @param key The name of the preference to modify.
     * @param set The new value for the preference.
     * @throws Exception if key or value is null.
     */
    public void putStringSet(String key, Set<String> set) {
        try {
            Editor prefEdit = mPreferences.edit();
            prefEdit.putStringSet(key, set);
            prefEdit.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * Retrieve a {@code Set<String>} from the preferences.
     *
     * @param key the name of the preference to retrieve.
     * @param set the default value for the preference.
     * @return Returns the preference value if it exists, or defValue.
     */
    public Set<String> getStringSet(String key, Set<String> set) {
        return mPreferences.getStringSet(key, set);
    }

}

AppUtils

import android.os.Build;

/**
 * @author Nayanesh Gupte
 */
public class AppUtils {

    /**
     * @return true If device has Android Marshmallow or above version
     */
    public static boolean hasM() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
    }
}

ILocationConstants

/**
 * @author Nayanesh Gupte
 */
public interface ILocationConstants {


    /**
     * The desired interval for location updates. Inexact. Updates may be more or less frequent.
     */
    long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;

    /**
     * If accuracy is lesser than 100m , discard it
     */
    int ACCURACY_THRESHOLD = 100;

    /**
     * The fastest rate for active location updates. Exact. Updates will never be more frequent
     * than this value.
     */
    long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;


    /**
     * Broadcast Receiver Action to update location
     */
    String LOACTION_ACTION = "com.technosavy.showmedistance.LOCATION_ACTION";

    /**
     * Message key for data with in the broadcast
     */
    String LOCATION_MESSAGE = "com.technosavy.showmedistance.LOCATION_DATA";


    /***
     * Request code while asking for permissions
     */
    int PERMISSION_ACCESS_LOCATION_CODE = 99;


}

IPreferenceConstants

/**
 * @author Nayanesh Gupte
 */
public interface IPreferenceConstants {

    String PREF_DISTANCE = "distance";

}

用于在后台获取位置的LocationService

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import jana.g2evolution.transitoak.Json.End_Urls;
import jana.g2evolution.transitoak.R;

/**
 * @author Nayanesh Gupte
 */
public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, ILocationConstants, IPreferenceConstants {


    private static final String TAG = LocationService.class.getSimpleName();

    /**
     * Provides the entry point to Google Play services.
     */
    protected GoogleApiClient mGoogleApiClient;

    /**
     * Stores parameters for requests to the FusedLocationProviderApi.
     */
    protected LocationRequest mLocationRequest;

    /**
     * Represents a geographical location.
     */
    protected Location mCurrentLocation;


    private String mLatitudeLabel;
    private String mLongitudeLabel;
    private String mLastUpdateTimeLabel;
    private String mDistance;

    String Result;
    String strlatitude, strlongitude;

    /**
     * Time when the location was updated represented as a String.
     */
    protected String mLastUpdateTime;

    private Location oldLocation;

    private Location newLocation;


    private AppPreferences appPreferences;
    String strloginid, strloginname, strlogintype;
    /**
     * Total distance covered
     */
    private float distance;


    @Override
    public void onCreate() {
        super.onCreate();


        SharedPreferences prefuserdata = getSharedPreferences("registerUser", 0);
        strloginid = prefuserdata.getString("loginid", "");
        strloginname = prefuserdata.getString("username", "");
        strlogintype = prefuserdata.getString("usertype", "");



        appPreferences = new AppPreferences(this);

        oldLocation = new Location("Point A");
        newLocation = new Location("Point B");

     /*   mLatitudeLabel = getString(R.string.latitude_label);
        mLongitudeLabel = getString(R.string.longitude_label);
        mLastUpdateTimeLabel = getString(R.string.last_update_time_label);
        mDistance = getString(R.string.distance);*/

        mLastUpdateTime = "";

        distance = appPreferences.getFloat(PREF_DISTANCE, 0);

        Log.d(TAG, "onCreate Distance: " + distance);


    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {


        buildGoogleApiClient();

        mGoogleApiClient.connect();

        if (mGoogleApiClient.isConnected()) {
            startLocationUpdates();
        }

        return START_STICKY;

    }


    /**
     * Builds a GoogleApiClient. Uses the {@code #addApi} method to request the
     * LocationServices API.
     */
    protected synchronized void buildGoogleApiClient() {

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        createLocationRequest();
    }


    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();

        mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);

        mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);

        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }


    /**
     * Requests location updates from the FusedLocationApi.
     */
    protected void startLocationUpdates() {

        try {

            LocationServices.FusedLocationApi.requestLocationUpdates(
                    mGoogleApiClient, mLocationRequest, this);

        } catch (SecurityException ex) {


        }
    }


    /**
     * Updates the latitude, the longitude, and the last location time in the UI.
     */
    private void updateUI() {

        if (null != mCurrentLocation) {

            Log.e("testing","latitude in service = "+mCurrentLocation.getLatitude());
            Log.e("testing","longitude in service = "+mCurrentLocation.getLongitude());

                    strlatitude =  String.valueOf(mCurrentLocation.getLatitude());
                    strlongitude = String.valueOf(mCurrentLocation.getLongitude());
            Toast.makeText(this, mCurrentLocation.getLatitude()+" , "+mCurrentLocation.getLongitude(), Toast.LENGTH_SHORT).show();

            StringBuilder sbLocationData = new StringBuilder();
            sbLocationData.append(mLatitudeLabel)
                    .append(" ")
                    .append(mCurrentLocation.getLatitude())
                    .append("\n")
                    .append(mLongitudeLabel)
                    .append(" ")
                    .append(mCurrentLocation.getLongitude())
                    .append("\n")
                    .append(mLastUpdateTimeLabel)
                    .append(" ")
                    .append(mLastUpdateTime)
                    .append("\n")
                    .append(mDistance)
                    .append(" ")
                    .append(getUpdatedDistance())
                    .append(" meters");


            /*
             * update preference with latest value of distance
             */
            appPreferences.putFloat(PREF_DISTANCE, distance);

            Log.d(TAG, "Location Data:\n" + sbLocationData.toString());

            sendLocationBroadcast(sbLocationData.toString());
        } else {

           // Toast.makeText(this, R.string.unable_to_find_location, Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * Send broadcast using LocalBroadcastManager to update UI in activity
     *
     * @param sbLocationData
     */
    private void sendLocationBroadcast(String sbLocationData) {

        Intent locationIntent = new Intent();
        locationIntent.setAction(LOACTION_ACTION);
        locationIntent.putExtra(LOCATION_MESSAGE, sbLocationData);

        LocalBroadcastManager.getInstance(this).sendBroadcast(locationIntent);

    }

    /**
     * Removes location updates from the FusedLocationApi.
     */
    protected void stopLocationUpdates() {

        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }


   /* @Override
    public void onDestroy() {

        appPreferences.putFloat(PREF_DISTANCE, distance);

        stopLocationUpdates();

        mGoogleApiClient.disconnect();

        Log.d(TAG, "onDestroy Distance " + distance);


        super.onDestroy();
    }*/


    /**
     * Runs when a GoogleApiClient object successfully connects.
     */
    @Override
    public void onConnected(Bundle connectionHint) throws SecurityException {
        Log.i(TAG, "Connected to GoogleApiClient");


        if (mCurrentLocation == null) {
            mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
            updateUI();
        }

        startLocationUpdates();

    }

    /**
     * Callback that fires when the location changes.
     */
    @Override
    public void onLocationChanged(Location location) {
        mCurrentLocation = location;
        mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
        updateUI();

    }

    @Override
    public void onConnectionSuspended(int cause) {

        mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {

        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
    }


    private float getUpdatedDistance() {

        /**
         * There is 68% chance that user is with in 100m from this location.
         * So neglect location updates with poor accuracy
         */


        if (mCurrentLocation.getAccuracy() > ACCURACY_THRESHOLD) {

            return distance;
        }


        if (oldLocation.getLatitude() == 0 && oldLocation.getLongitude() == 0) {

            oldLocation.setLatitude(mCurrentLocation.getLatitude());
            oldLocation.setLongitude(mCurrentLocation.getLongitude());

            newLocation.setLatitude(mCurrentLocation.getLatitude());
            newLocation.setLongitude(mCurrentLocation.getLongitude());

            return distance;
        } else {

            oldLocation.setLatitude(newLocation.getLatitude());
            oldLocation.setLongitude(newLocation.getLongitude());

            newLocation.setLatitude(mCurrentLocation.getLatitude());
            newLocation.setLongitude(mCurrentLocation.getLongitude());

        }


        /**
         * Calculate distance between last two geo locations
         */
        distance += newLocation.distanceTo(oldLocation);

        return distance;
    }


    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }




}