Crea sito

Android: AlarmManager Tutorial

Hello to all. In this tutorial we'll talk about AlarmManager related to a very simple project (about 100 code lines).


First of all I want to explain why I wrote this tutorial:

- I used the alarm manager to have a repeating data refreshing from a db.

- I have searched a good and simple tutorial but I didn't find it.


...but...what are alarms and AlarmManager?

An AlarmManager is an entity that grants you to access to system alarm service and that allows you to schedule the code execution at a specific time, even if your application is not currently running.



Discussion about the posted project (download link at the end of the page)

Layout: As you can see in the emulator-screenshot you'll find:

- two EditText with whom you can set the delay time for the first alarm and the delay between alarms  in repeating mode

- an EditText (not editable) that visualize a counter for received alarms

- three Button: one to start a single alarm, one to start repeting alarms and one to stop alarms in repeating mode

Code: you'll find a simple and commented activity that will contains:

- a BroadcastReceiver: it receives the intent sent as alarms an send a message to an handler

- an Handler: it receives a message and if it's an alarm it refresh "Received Alarms" and shows a toast

- a PendingIntent: with whom you notify the action to AlarmManager

- an AlarmManager: you ask to it the type of alarm that you desire (one shot or repeating) or cancel an active repeating alarm


See you soon,