Search code examples
javaandroidfusedlocationproviderclient

How to stop properly FusedLocationProviderClient?


I use FusedLocationProviderClient within a Service.
I would like to "stop" it in a right way.

Is it good to use following code?

 @Override
    public void onDestroy() {
        super.onDestroy();
        // Stop Looper of FusedLocationProviderClient  
        if (locationClient != null) {
            locationClient = null;
        }
    }

And the rest code

FusedLocationProviderClient locationClient;


protected void startLocationUpdates() {


        // Create the location request to start receiving updates
        mLocationRequest = new LocationRequest();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);

        // Create LocationSettingsRequest object using location request
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
        builder.addLocationRequest(mLocationRequest);
        LocationSettingsRequest locationSettingsRequest = builder.build();

        // Check whether location settings are satisfied
        // https://developers.google.com/android/reference/com/google/android/gms/location/SettingsClient
        SettingsClient settingsClient = LocationServices.getSettingsClient(this);
        settingsClient.checkLocationSettings(locationSettingsRequest);

        // new Google API SDK v11 uses getFusedLocationProviderClient(this)
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }

        locationClient = getFusedLocationProviderClient(this);getFusedLocationProviderClient(this).requestLocationUpdates(mLocationRequest, new LocationCallback() {
                    @Override
                    public void onLocationResult(LocationResult locationResult) {
                        // do work here
                        onLocationChanged(locationResult.getLastLocation());
                    }
                }, Looper.myLooper());
    }

Solution

  • just call removeLocationUpdates in onDestroy

    for requestLocationUpdates, it says:

    This call will keep the Google Play services connection active, so make sure to call removeLocationUpdates(LocationCallback) when you no longer need it, otherwise you lose the benefits of the automatic connection management.