android: running a background task using AlarmManager

后端 未结 1 529
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 05:39

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 BroadcastRecieve

相关标签:
1条回答
  • 2020-11-28 06:07

    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 讨论(0)
提交回复
热议问题