views:

5619

answers:

1

Can someone please show me some sample code on how to use an AlarmManager in android.

I have been playing around with some code for a few days and it just won't work...

I need to trigger a block of code after 20 minutes from the AlarmManager being set.

Thanks.

+10  A: 

"Some sample code" is not that easy when it comes to AlarmManager.

Here is a snippet showing the setup of AlarmManager:

AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(context, OnAlarmReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0);

mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), PERIOD, pi);

In this example, I am using setRepeating(). If you want a one-shot alarm, you would just use set(). Be sure to give the time for the alarm to start in the same time base as you use in the initial parameter to set(). In my example above, I am using AlarmManager.ELAPSED_REALTIME_WAKEUP, so my time base is SystemClock.elapsedRealtime().

This snippet is from a larger sample AlarmManager example you can download from:

http://commonsware.com/AdvAndroid/

Note, though, that I will be updating that example in a few days, as a reader has pointed out a bug -- not in the AlarmManager usage itself, but in the service that does (simulated) work based on the alarm going off.

CommonsWare
Hello again. Thanks for the reply. If I purchase your book does it explain how to implement a alarm manager in full detail?
Tom
The Advanced Android book (Version 0.9) has ~9 pages covering AlarmManager, WakeLocks, and the rest of that example. That will probably expand slightly in Version 1.0 as I make the fix I mentioned in my answer above. And if you have questions regarding the book or its sample code, hop over to http://groups.google.com/group/cw-android and I'll be happy to answer them.
CommonsWare
Any android developer should have subscription to Mark's books :) At least once
DroidIn.net