views:

428

answers:

2

I'm noticing a strange thing with Alarms on Android - they don't always wake up the device at the correct intervals. For example, if I set an alarm to start a service every 5 minutes (using RTC_WAKEUP, or similar), everything works fine until the device goes to sleep - after that, the alarm may not fire for minutes, or close to an hour. It usually does fire eventually - and it always fires if I wake the device by pressing Menu. Using repeating alarms (vs. re-setting them each time) has the same effect.

So my question is, are alarms guaranteed to fire at proper intervals when the device is asleep? I understand that I shouldn't expect millisecond or second precision, but tens of minutes?

+7  A: 

I've never programmed on Android but I was kinda bored so I googled around and found this, which seems to be very related: http://groups.google.com/group/android-developers/browse%5Fthread/thread/f0303a539de3a74a (you'll need to sign in to your google account in order to read it)

I had another look at the AlarmManager documentation and I noticed that it only talks about using alarms to broadcast events, not start services. I changed things around to use a BroadcastReceiver instead that acquires the lock in its onReceive() and stored the lock reference as a static member of another class, following the example of the AlarmClock application: http://android.git.kernel.org/?p=platform/packages/apps/AlarmClock.gi...

That seems to have worked. I guess what was happening was that my service starting alarms were being fired, but the device was sometimes going back to sleep before I could acquire the wake lock. Apparently the only guarantee that is made when an alarm is received is that the onReceive will run to completion.

I just thought I'd post this in case anyone is ever searching for the same problem.

Andreas Bonini
That's a perfect answer; thanks!
Melllvar
+3  A: 

You should also look at: http://developer.android.com/reference/android/app/AlarmManager.html

Also, when the device is asleep, your program has already had OnPause() called, so only services are running at that point. Meaning that unless your Broadcast Receiver is set to have a wake lock -- the way it suggests in the docs -- the original service call is not going to maintain the device's awake status.

UEC
Thanks for an excellent pointer.
Melllvar