Android AlarmManager pain
Never thought I’d be experiencing issues with such a simple task as setting recurring alarms, but it seems Android’s AlarmManager makes this more difficult than it should be.
I have a need for periodic alarms in my application to refresh data from the Internet. Pretty simple, just use
The basic issue is, there is no way for an application to know if its alarms are set.
- The user force stops my application. This clears the alarms, which is correct, because the user is very clearly saying that he does not want to run my application at this time (actually, it may not be correct, he just wants to free some memory, but I will let it pass for now).
- Then he runs one of the application’s activities again, which means that the application should enable scheduled updates again.
- To accomodate this, the code in my main activity should set the alarm somewhere in its onCreate / onStart / onResume callbacks.
Since my code has no way of knowing whether the alarm has already been set, this will schedule the next update at current time plus the update interval. This means that if the update interval is long (say, an hour or two), and the user opens the application between the updates, the scheduled actions may never take place.
Using persistent data storage doesn’t help, because if the application is killed, it won’t have a chance to clear its persistent storage, so it’ll think the alarm is set whereas it’s not.
My current solution is to schedule alarms one by one, keeping track of the next scheduled time in shared preferences. The code sets the alarm only if the next scheduled time point has already passed.
This is not perfect, because in the above scenario, the updates will resume only after 2x the update interval (one to set the next alarm, another before it actually fires). It also prevents me from using
setInexactRepeating, which is a useful way to reduce battery use.
How hard was it to add AlarmManager.isSet()? Would it be abused? Well, ok, make sure applications can’t query alarms set by other packages.
If anyone has a better solution, I’d really like to hear it.
Meanwhile, I’m not the only one having difficulties with this. Here is the output of adb dumpsys alarm from my Xperia Arc. About 120 (a hundred and twenty) alarms for something called
com.google.android.gsf, and about 20 (twenty) alarms for
MyBackup Pro, most of them for same or very close time values.