tags:

views:

337

answers:

0

In an Android app I'm developing, I've got a need for LocationManager to give me location fixes. That part is all nice and good; it's working, it has been for quite some time, and all is happy there.

However, now that I've also recently added a feature that allows the location tracking part to go to the background, I also want to allow it to slow down updates in that case to conserve battery power. In effect, the way I'm trying to do this is by reissuing the requestLocationUpdates call with new parameters if my background service detects that there aren't any listeners registered anymore (it provides something to the notification bar, so I still want it getting updates). Let's call that service "Servicemajig". The way I'm doing that, in short:

private void setMode(boolean foreground) {
    // This sets whether we're in foreground or background mode.  If we're
    // not changing anything, though, don't do anything.
    if(foreground == mForeground) return;

    // Set the current mode...
    mForeground = foreground;

    // ...and switch!
    if(mForeground) {
        // Foreground mode means we go full tilt.
        Log.i(DEBUG_TAG, "Switching to foregroud mode...");
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, Servicemajig.this);
    } else {
        // Background mode means we slow down.  Like, say, 30 seconds.
        Log.i(DEBUG_TAG, "Switching to background mode...");
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 0, Servicemajig.this);
    }
}

Now, this works, for the most part. I don't get double-updates (i.e. I don't unregister first yet it still does the trick), and on my Nexus One and G1, this properly switches between background and foreground mode as need be. That is, it'll properly wait around 30 seconds (give or take) before trying to get another location fix, conserving battery power.

The problem comes when I test it on a Motorola Droid. On the Droid and on it alone, once I put it in background mode, it'll wait 30 seconds (again, give or take) between fixes, but if it DOES get at least one fix in that manner, it won't return to foreground mode later. That is, even after I've re-entered the actual app where foreground mode desired and requested, it still waits 30 seconds per fix, and I can't seem to get around this, apart from shutting down Servicemajig and restarting it. The logs show that it IS passing through that part of code, so it's at least getting that far.

So my question is, is this just a bug specific to the Droid firmware? Is there some way I can work around this? Or is this even the right way to do something like this? I'll note that it doesn't matter if I add in a removeUpdates call before the if block with the registerLocationUpdates calls.