tags:

views:

79

answers:

1

Hi,

My application uses GPS updates while it is running and I would like that to stop when the user back out of the app as I assume it will continue wasting a lot of battery power. I've tried intercepting the back button press but it doesn't seem to work. I'm not sure if this is because it's not executing the code or I'm using the wrong command. Any help would be appreciated.

public boolean OnKeyDown(int keyCode, KeyEvent event){
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0){
    lm.removeUpdates(this);
        return true;    
    }
    return super.onKeyDown(keyCode, event);
}
+3  A: 

Just call removeUpdates() in onPause() or onStop(), probably the latter.

CommonsWare
Works perfectly, many thanks.
t.vb.w
Nope, the former, onStop() is not guaranteed to be called :).
MrSnowflake
I'm using onPause() and it works brilliantly anytime I navigate away from the main activity. I suppose onStop() will only be called when you back out of the main activity?
t.vb.w
`onPause()` is called when the activity no longer has the foreground. `onStop()` is called (after `onPause()`) when the activity is no longer visible. With respect to MrSnowflake's comment, the only time `onStop()` will never be called is if the process is being terminated (e.g., emergency RAM reclamation), at which point it is up to the OS to make sure GPS turns off, AFAICT.
CommonsWare
Yes if the system needs to kill your process before onStop(), the resources that process is holding must of course also be released by the system. There are, however, some things you can do where your process is not holding the resource so it getting killed will not clean it up -- basically anything involving a PendingIntent or otherwise having a way to launch your activity via an Intent in the future. For example, a status bar icon, or requestLocationUpdates() with a PendingIntent. The purpose of these is, of course, to allow them to continue operating even if your process is gone.
hackbod