Proper handling LocationManager.requestLocationUpdates in background

363 views Asked by At

I'm creating app which must gets location of user through GPS while app is in background and I'm doing it using LocationManager but i started wonder which method will be safer.

1) Start listenening for any location changes in services, and removeUpdates in onDestroy() - but from what I read, if service'll be killed then onDestroy() can not be triggered.

2) Create some kind of GPSManager class and in Application class removeUpdates at onDestroy() (or maybe at onTrimMemory() ). GPSManager would be looks something like that: public class GPSManager {

Context mContext;

LocationManager mLocationManager;

public GPSManager(Context context){
}

public void startGPSService(){
}

public void stopGPSService(){
}

LocationListener listener = new LocationListener() {
    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }
};

}

3) Any other method, better that I mentioned, which i doesn't know.

Thanks in advance

2

There are 2 answers

0
Gabe Sechan On BEST ANSWER

If your service is killed, either onDestroy will be called or the entire process is going to be killed- in which case you don't need to worry about it, the OS will remove you from the list of apps to notify. So you're good with #1.

The second is a bad idea. THere's no reason to remove GPS updates in onTrimMemory, it doesn't use a lot of RAM. And you want to bind turning on and off updates to the Context that is using it, not to the application- otherwise you'll keep them on longer than needed.

2
Akhil On

Using LocationManager is quite old now, you should use simpler and effective way using Google Play services Location API's

You should check out this, there is sample code also available here..