Disclaimer: My app already working without any Wake Locks for 1+ year and all is well for most devices.
I’m tracking GPS and it works like this:
- AlarmReceiver starts Service every 5/10/15 minutes (as user wishes)
- Service subscribes for Location updates and waits MAX 1 minute for good GPS.
- Wrap up, send data to server and shut down service.
Due to bad connections and bad locations – whole thing take up to 2-3 minutes sometimes. And it works. No matter if phone is sleeping or not.
Now I’m reading about WakeLock and it doesn’t make sense to me. How come my stuff is working? Is that coincidence?
A combination of things, including a dollop of luck. 🙂
First, as Joel noted, the device wakes up briefly courtesy of your alarm, but the OS is only guaranteed to hold a
WakeLockfor the duration ofonReceive()of aBroadcastReceiver.It is possible that, at least on some versions of Android, requesting GPS updates causes the OS to acquire its own
WakeLock. This is undocumented behavior AFAIK, and I have never relied upon it personally. If it does, though, and you are doing the rest of your work (“Wrap up, send data to server and shut down service”) before removing location updates, that would explain the behavior.There are still potential gaps in your approach (e.g., if you delegate to a
Serviceto do the work and are not holding aWakeLockas part of passing control to that service). Statistically speaking, it may fail occasionally but work a lot of the time.Personally, I recommend using a
WakeLock, in case the undocumented behavior changes. That’s what I do inLocationPoller.