The article you were looking for has been moved to this domain. If you're using a bookmark, please update it.

Posted by & filed under Development.

There aren’t a lot of good write-ups on how to use the AlarmManager, so here is an example that launches an Activity using the AlarmManager.

What’s the AlarmManager used for?

The AlarmManager is used to schedule events or services at either a set time or a set interval. It’s Android’s “version” of the cron. In this case, we’re going to set an alarm for five seconds after the app is launched.

What we’re going to build

In order to use build this simple app, we’re going to create only two classes. One will be for the Main Activity, and one will be for the Activity we want to launch with the Alarm. We will also have two simple layouts for each of the activities.

The Main Activity

In this Activity, we are setting the layout, setting an offset for five seconds from now, creating the PendingIntent and adding it to the AlarmManager. The PendingIntent.FLAG_CANCEL_CURRENT tells the AlarmManager that any other pendingIntent’s with the same id (in this case 12345) should be canceled and replaced with this one. If you want to have more than one alarm, you’ll need to change the 12345 in line 16 to make each alarm unique.

The AlarmReceiverActivity

When this Activity starts, we are ensuring it’s full-screen, playing a sound, and making sure there’s a way to stop the sound. Not too difficult…

Don’t forget to add the Activity to your AndroidManifest.xml

Layouts

In case you’re new to Android development, these are put into your res/layout folder.

alarm.xml

main.xml

Wrap-up

Run that and see how it goes! Feel free to leave any comments below!

To check out the source code for this project, you can find it on Github.

  • dmarg

    Thank you very much for this code! It was exactly what I was looking for.