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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With