I have just started working on my first Android application and am going ok. I have managed to get the app to locate my current position on a map and place the blue circle there. I can see the satellite icon in the notification bar working (satellite dish with rays coming off it).
I am very new to android phones altogether but upon being done with my app I just exit it by either using the back key or the home key which works fine, however I notice the satellite icon is still working. Going back to my phone an hour later the GPS is still running. This of course sends the phone battery flat very quickly.
I assume unlike iPhone that Android apps can run in the background and this is still running. How do I get my app to stop using GPS when it is no longer on the map view?
Here is an example of what I have done so far:
//find and initialise map view
private void initMapView() {
map = (MapView) findViewById(R.id.map);
controller = map.getController();
map.setSatellite(false);
map.setBuiltInZoomControls(true);
}
//start tracking the position on the map
private void initMyLocation() {
final MyLocationOverlay overlay = new MyLocationOverlay(this, map);
overlay.enableMyLocation();
//overlay.enableCompass(); does not work in emulator
overlay.runOnFirstFix(new Runnable() {
public void run() {
//zoom in to current location
controller.setZoom(8);
controller.animateTo(overlay.getMyLocation());
}
});
map.getOverlays().add(overlay);
}
Do I need to disable something when I leave the map view? if so, how?
Cheers guys
You should probably take a look at the Activity Lifecycle. In short, your assumption is correct: Android does not just kill your App when you leave it.
You’ll have to implement the onPause() method and unregister the GPS listener. And maybe also remove the mapview, but I don’t think that matters much in terms of battery life.
Also, you should move the registration of the GPS into the onResume() method. That’s necessary in order to enable the GPS again when your App coms back into view.
The onPause(), onResume(), onCreate() (and so on) methods get called by android itself at the appropriate times.