In my application, I want to record the phone's location at fixed interval. To do that, I have a
TimerTask to record the location on a regular basis and a
WakeLock for the recording to continue even when the phone is aslept.
My problem is that the
Wakelock doesn't prevent the app from going into the "Stop" state when it is no longer displayed in the foreground. As a consequence, my app is regularly, but apparently randomly, destroyed by the system (no crash and no call to
onDestroy), and the recording stops.
How can I keep my recording process going even if my app goes into the background?
Best How To :
In my application, I want to record the phone's location at fixed interval.
JobScheduler to get control at your fixed interval. Use
WakefulBroadcastReceiver as the recipient of the alarm event, and have it delegate the work to a
Service that gets the location. Have the service call
completeWakefulIntent() once either it gets the location or after some timeout, as it may not be possible to get the location right now.
Or, if you are using the fused location API from Play Services, try the versions of that API that take a
PendingIntent instead of a listener, and you may be able to skip the alarms.
I have a TimerTask to record the location on a regular basis
That will only work while your process is around, and it will not be around all that long.
and a WakeLock for the recording to continue even when the phone is aslept
Your users will be extremely unhappy with you for keeping the CPU on constantly and draining the battery.