views:

129

answers:

1

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

+3  A: 

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.

pableu
Thanks, a very helpful answer. It seems the tutorial I started on from a book left these important parts out.Should I still have enableMyLocation within onCreate(), yet also within onResume() so it works the first time you launch the app? Or does it run onResume anyway? or do I call onResume from onCreate?
Daniel Bowden
It runs onResume anyways, also when the app if freshly started. Look at the image a bit further down in my first link above. I have that printed out and pinned next to my TFT ;-)
pableu