开发者

android: running a background task using AlarmManager

I am writing an app which needs to periodically check the server for new messages and notify开发者_开发问答 the user. I have seen some examples using AlarmManager to hit a BroadcastReciever which seems like the right thing to do, but i cant seem to get it to work.

Can anyone show me a step by step tutorial for this sort of thing (repeating alarm which triggers some kind of background code that fires a Notification)?

TIA


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜