GPS Should Stop

One error that creeps quite often in Android applications is not handling being in background gracefully. It is error that is really easy to make since your application works as it normally would. However, it does use more resources than it is needed and resources usually map to battery life.

One example of bad behavior that comes to mind is updating location non-stop. Most often application needs to update their location only when user is looking at it. Once application is in background GPS should be turned off (although there are some application that have good reason to leave it going).

Easiest way to do it is just handling all GPS "subscriptions" in onResume and onPause methods. Those methods get called each time application comes to foreground (onResume) or leaves it (onPause).

Generic solution would look something like this:

private LocationManager thisLocationManager;

@Override
public void onCreate(Bundle savedInstanceState) {
...
thisLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
}

@Override
protected void onResume() {
thisLocationManager.requestLocationUpdates("gps", 0, 0, gpsLocationListener);
super.onResume();
}

@Override
protected void onPause() {
thisLocationManager.removeUpdates(gpsLocationListener);
super.onPause();
}

private LocationListener gpsLocationListener = new LocationListener() {
...
};

P.S. Do note that this code is not optimal in any way (e.g. hard-coding "gps" as provider name). Intention is just to illustrate concept.

Leave a Reply

Your email address will not be published. Required fields are marked *