android: running a background task using AlarmManager

Here is one complete example: http://android-in-practice.googlecode.com/svn/trunk/ch02/DealDroidWithService/

The pattern this example uses, and one that I’ve found that seems to work well, is to use a boot receiver to setup the AlarmManager (and of course also check to start the polling from your main Activity too, for the case when your app is installed and the system is not booted) and have the AlarmManager send an Intent for another receiver: http://android-in-practice.googlecode.com/svn/trunk/ch02/DealDroidWithService/src/com/manning/aip/dealdroid/DealBootReceiver.java

And then from the AlarmReceiver start an IntentService:
http://android-in-practice.googlecode.com/svn/trunk/ch02/DealDroidWithService/src/com/manning/aip/dealdroid/DealAlarmReceiver.java

From your IntentService then make your network call to poll for data, or whatever you need to do. IntentService automatically puts your work in a background thread, it’s very handy:
http://android-in-practice.googlecode.com/svn/trunk/ch02/DealDroidWithService/src/com/manning/aip/dealdroid/DealService.java

Check the docs for these classes too, a lot of into in there.

The caveat with this example is that it does not deal with the wake lock gap (the excellent CommonsWare code does that if you need it), but it may give you some more ideas about how to potentially address the “poll using AlarmManager and Service” stuff.

UPDATE: the code is now here: https://github.com/charlieCollins/android-in-practice

Leave a Comment