3

Im trying to retrieve the user's location once, then disconnect() from location services to avoid battery use. The problem is, even after i disconnect i see the location arrow icon in the status area - also the callback onDisconnected() never gets called, even after calling disconnect on the client.

This is what im doing:

In onResume() i connect:

mLocationClient = new LocationClient(this, this, this);
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(LOCATION_UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(1);
mLocationClient.connect();

In onConnected() i try getting lastlocation, if its NOT null, ill get it and disconnect from location services. If it is null, i start listening for updates:

if (mLocationClient.getLastLocation() != null) {
        userLocation = mLocationClient.getLastLocation();
        stopLocationServices();
        // do something which requires location
} else {
        mLocationClient.requestLocationUpdates(mLocationRequest, this);
}

In onLocationChanged

userLocation = mLocationClient.getLastLocation();
stopLocationServices();
// do something which requires location

My stopLocationServices() function looks like this:

private void stopLocationServices() {
    if (mLocationClient != null) {
        try {
            mLocationClient.removeLocationUpdates(this);
            mLocationClient.disconnect();
        } catch (Exception e) {}
    }
    mLocationClient = null;
}

thanks for any help.

Parampal Pooni
  • 2,958
  • 8
  • 34
  • 40

2 Answers2

0

If getLastLocation() doesn't return null and stopLocationServices() is called sequentially, you would then be trying to removeLocationUpdates() on mLocationClient without requesting them in the first place which may be throwing an exception and maybe the reason onDisconnected() is never called.

canopi
  • 107
  • 1
  • 5
  • I separated the two lines `mLocationClient.removeLocationUpdates(this);` and `mLocationClient.disconnect();` into different try catch statements; it still didnt work. – Parampal Pooni Jun 24 '14 at 22:29
0

If you are still having issues with this..

I think you are setting the location client to null before it had a chance to disconnect.

Try putting this mLocationClient = null; into the onDisconnected method (remove from stopLocationServices()).

public void onDisconnected() {

mLocationClient = null;

}
hutchonoid
  • 32,982
  • 15
  • 99
  • 104