Question

I have an app which is recording the position of the user continuously. The location updates are to be very frequent to get an exact mapping of the route the user has taken. To keep the application recording the geo points when the phone falls asleep I use a wake lock which is released when the user stops the recording or in onDestroy().

I now realize I am not removing the location listener from the location manager. This leads to the battery draining if the user forgets to press the "stop recording route" button before leacing the application. My initial thought was to remove it in onPause() but then I'm afraid onPause() might get called when the screen turns off although I have a wake lock (but not screen on).

My questions in this matter are: When should I remove the location listener from the location manager? Should I release the listener i onDestroy()? Or perhaps I do not need a wake lock at all as long as I am listening to the location manager? How should this be handled if so?

I've seen this discussed in other places like here: Android - When using LocationManager.requestLocationUpdates, do I need a WakeLock?

But there doesn't seem to be an absolute answer.

Was it helpful?

Solution

You didn't mention how frequently you want to acquire locations which is relevant for the soluiton.

Acquisition frequency

If you want to acquire locations with a frequency bigger then 1 per 5 minutes, I suggest to leave the the listener registered. GPS devices as supposed to enter a energy save mode between acquisitions.

If the frequency is smaller that that, than you can consider removing the lister after you get the location and register it again using a timer task or the Alarmmanager, depending on your application design.

WakeLock

I've never tried it myself, but my expectation is that Android will enter sleep mode after some time of no user interaction, if no one request it to stay awake. It should be no different even if you register a listener.

Appliaction architecture

onPause() and onStop() are called when some other activity covers partially or totally you activity screen. So this are not suitable places to unregister the listener, if you want to keep continuous recording. Also, if the user leaves your application the recording will stop.

I suggest that you use a service to recorde the locations, if you have short period between acquisitions, or use the AlarmManager to schedule less frequent acqisitions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top