Home > Android API > Android Basics – Alarm Service

Android Basics – Alarm Service

February 3rd, 2009

Today we will see Alarm Service provided by Android. Android provide AlarmManager class. The class provides access to the android Alarm Service. AlarmManager provide the methods to set the alarms. Alarm can be one time or repeating. When the alarms goes off (alarm time occurs) a pending intent will be broadcasted that can invoke a BroadCastReceiver (intent receiver) or Service or Activity.

Let’s see how to set alarms. The Alarm Manger instance for the Alarm service can be obtained as follows:

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

There are 4 types of alarms the AlarmManager has defined constants for each type as RTC, RTC_WAKEUP, ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP.

While setting an alarm, a pending intent has to be defined. The pending intent is called when alarm goes off.
One time alarms:
One time alarm can be set using AlarmManager set() method. Here is how it can be done:

Intent intent = new Intent(this, OnetimeAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, intent, 0);

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), sender);
Toast.makeText(this, "Alarm set", Toast.LENGTH_LONG).show();

The pending intent is created for a Broadcast Receiver, the receiver is just notifying the user using Toast. The alarm is set to 10 secs from current time. Here is the code for the intent receiver:

public class OnetimeAlarmReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm worked.", Toast.LENGTH_LONG).show();
}
}

Repeating alarm:
Setting a repeating alarm is similar to setting one time alarm. The repeating alarm can be set using setRepeating() method of AlarmManager. Here is the code:

Intent intent = new Intent(this, RepeatingAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, intent, 0);

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), 10 * 1000, pendingIntent);
Toast.makeText(this, "Alarm set", Toast.LENGTH_LONG).show();

There is only one parameter extra in case of repeating alarm. The repeating alarm takes interval after which the alarm should be repeated. In this case the alarm is repeating itself after 10 secs.

The code of the RepeatingAlarmReceiver is:

public class RepeatingAlarmReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Repeating Alarm worked.", Toast.LENGTH_LONG).show();
}
}

The repeating alarms have to be cancelled to stop them. AlarmManager provide a cancel() method that requires the same intent class with which the intent is created. This is how you can cancel the alarm.

alarmManager.cancel(pendingIntent);

Note the pendingIntent object does not need to be same object. The intent fields like action, class, category etc should be same while creating the alarm. The intent is used to identify the alarm to cancel it.

E.g. Alarm Clock:
You can create a wake up alarm with the help of android Alarm service and notification service. The ring tone and the vibration pattern can be put in the intent of extras that can be retrieved by the Broadcast receiver. The code will be as follows:

Intent intent = new Intent(this, RepeatingAlarmReceiver.class);

intent.putExtra("Ringtone", Uri.parse("file:///sdcard/audiofile.mp3"));
intent.putExtra("vibrationPatern", new long[] { 200, 300 });
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), (24 * 60 * 60 * 1000), pendingIntent);

The alarm is set as daily (will repeat after 24 hours). The broadcast receiver can show a notification with the help of the notification service.

NotificationManager manger = (NotificationManager)     context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon, "Wake up alarm", System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);
notification.setLatestEventInfo(context, "Context Title", "Context text", contentIntent);
notification.flags = Notification.FLAG_INSISTENT;

notification.sound = (Uri) intent.getParcelableExtra("Ringtone");
notification.vibrate = (long[]) intent.getExtras().get("vibrationPatern");

// The PendingIntent to launch our activity if the user selects this notification
manger.notify(NOTIFICATION_ID, notification);

You can set appropriate values for contentIntent as your need. You can also pass an array of boolean for each day like Sunday, Monday etc. The intent receiver will match the current day with the alarm days and show the alarm notification accordingly.

Android API , , , ,

  1. April 2nd, 2009 at 19:09 | #1

    Thanks for this tutorial! Android tuts are scarce and mostly outdated.

    I’m trying to construct an OnListItemClick that opens a simple Alert Dialog with the positive button setting a “one time alarm”. Here’s what I have:

    [code]
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

    AlertDialog.Builder SetReminder = new AlertDialog.Builder(this);
    //*this* is the Activity because it needs the Context.
    SetReminder.setIcon(R.drawable.ic_dialog_menu_generic);
    SetReminder.setTitle("Set Reminder?");
    SetReminder.setMessage("Would you like to set a reminder?");
    AlertDialog ad = SetReminder.create();
    ad.requestWindowFeature(Window.FEATURE_LEFT_ICON);
    SetReminder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
    Intent intent = new Intent(this, OnetimeAlarmReceiver.class);
    PendingIntent sender = PendingIntent.getBroadcast(context, REQUEST_CODE, intent, 0);

    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), sender);

    Toast.makeText(this, "Alarm Set", Toast.LENGTH_LONG).show();
    }

    });
    SetReminder.setNegativeButton("No", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
    Toast.makeText(getBaseContext(), "Reminder Not Set", Toast.LENGTH_SHORT).show();
    }
    });
    SetReminder.show();
    }

    public class OnetimeAlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
    Toast.makeText(context, "Alarm Worked", Toast.LENGTH_LONG).show();
    }
    }
    [/code]

    Any help, hints or links would be greatly appreciated.

    Thanks in advance,
    Paul

  2. April 2nd, 2009 at 22:56 | #2

    Could someone also tell me what intent filters or modifications one must make to the manifest.xml to get the “Alarm Clock” example working?

    Thanks

  3. April 7th, 2009 at 01:03 | #3

    Okay so I got the alarm/notification working based on your example (thanks), albeit, not from the AlertDialog. I’m no longer interested in my above request.

    Instead, I was wondering if its possible to have an AlertDialog built and displayed in a BroadcastReciever. I’d like a dialog to show at the same time as the notification.

    Any advice, help?

  4. April 7th, 2009 at 09:25 | #4

    Thought I’d pay it forward:

    To use standard sound, vibration, and flashing green led light notifications replace:

    notification.flags = Notification.FLAG_INSISTENT;

    notification.sound = (Uri) intent.getParcelableExtra(”Ringtone”);
    notification.vibrate = (long[]) intent.getExtras().get(”vibrationPatern”);

    with:

    notification.flags = Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_SHOW_LIGHTS;
    notification.ledARGB = Color.GREEN;
    notification.ledOnMS = 1000;
    notification.ledOffMS = 500;
    notification.defaults = Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE;

    - Paul

  5. chris
    June 24th, 2009 at 17:44 | #5

    Well done,

    just one question: how can i get the notification.sound to just play once?

  6. Sam
    February 3rd, 2010 at 17:39 | #6

    Nice tutorial, but how can i set the alarm to go off at a certain time. I have some times stored in a database and would like the alarm to go off at these times.

  7. Amanda
    February 13th, 2010 at 18:16 | #7

    @Sam
    I would love to get that to work too!

  8. Sam
    February 24th, 2010 at 10:13 | #8

    Hmm i couldnt get the database to work. So i just set the times manually now using Calendar and then setting the day,hour,time ect.

  9. cyberjar09
    March 17th, 2010 at 05:03 | #9

    Sam :
    Nice tutorial, but how can i set the alarm to go off at a certain time. I have some times stored in a database and would like the alarm to go off at these times.

    I’m looking for a solution to the same problem… I want some of my alarms during the day to only ring once and go off instead of the alarm sound looping over and over again. Please help.

    Thanks.

  10. cyberjar09
    March 17th, 2010 at 05:05 | #10

    Sorry I quoted the wrong comment. Meant to quote comment no 6 by Sam.

  11. cyberjar09
    March 17th, 2010 at 05:10 | #11

    chris :
    Well done,
    just one question: how can i get the notification.sound to just play once?

    Looking for a solution to the same problem.

  12. anusha
    April 19th, 2010 at 05:15 | #12

    how can i set more than one alarm and listout those alarms

  13. April 20th, 2010 at 02:03 | #13

    First add this code in your start.java class(Main Activity class)-

    package com.wissen.alarm;

    import android.app.Activity;
    import android.app.AlarmManager;
    import android.app.PendingIntent;
    import android.content.Intent;
    import android.os.Bundle;
    import android.widget.Toast;

    public class Alarm extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Intent intent = new Intent(this, AlarmReceiver.class);

    PendingIntent pendingIntent = PendingIntent.getBroadcast(this,001000,intent,0);

    PendingIntent pendingIntent2 = PendingIntent.getBroadcast(this,002000,intent,0);

    PendingIntent pendingIntent3 = PendingIntent.getBroadcast(this,003000,intent,0);

    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), pendingIntent);
    Toast.makeText(this, “Alarm set 1″, Toast.LENGTH_LONG).show();

    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), pendingIntent2);
    Toast.makeText(this, “Alarm set 2″, Toast.LENGTH_LONG).show();

    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), pendingIntent3);
    Toast.makeText(this, “Alarm set 3″, Toast.LENGTH_LONG).show();
    }
    }

    after this make sure that ,the BroadcastReceiver( AlarmReceiver) must be defined in the manifest.xml inside the application tag like this

    to notify the multiple Alarms, your AlarmReceiver should be like this-

    package com.wissen.alarm;

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.widget.Toast;

    public class AlarmReceiver extends BroadcastReceiver {

    static int count=1;
    @Override
    public void onReceive(Context context, Intent intent) {
    Toast.makeText(context, “Alarm worked -”+count, Toast.LENGTH_LONG).show();
    count++;
    }
    }

  14. anusha
    April 20th, 2010 at 03:34 | #14

    Thank you very much for the help

  15. Archana
    May 2nd, 2010 at 09:02 | #15

    Thanks a ton for this article!
    Its simple, straight-forward and the best that i have read so far on Alarm!
    You have made it so easy and understandable!

  16. juan lee
    May 19th, 2010 at 15:17 | #16

    I am new to android so please bear with me.
    1. After you set the alarm and kill the alarm clock( using taskiller) the alarm never goes off. why? I thought this was the idea behind intent and broadcast receivers. Also, can android kill the alarm because it require resources? is this possible?

    3. I am currently writing a program handles the statues of the phone( rining, idle, in use, etc)
    Again, if my program is killed by android memory management system, then It wouldn’t work.
    can someone explain to me how can i make sure my program would run when there is incoming call even after android has killed it?

    thank you

  17. Kevin
    May 19th, 2010 at 18:11 | #17

    Does something need to be specified in the manifest.xml file for this to work? I’m trying everything I can think of, but I just can’t seem to get this working. Thanks

  18. May 21st, 2010 at 04:22 | #18

    hi @Kevin
    You need to make sure BroadcastReceiver( AlarmReceiver) must be defined in the manifest.xml inside the application tag like this

  19. Richy
    July 18th, 2010 at 05:59 | #19

    Same question as Kevin asked. What entries i should put in manifest.xml to make this work.
    Can somebody please tell me what should be the which i have to specify in manifest.xml

  20. Richy
    July 18th, 2010 at 06:01 | #20

    Same question as Kevin asked. What entries i should put in manifest.xml to make this work.
    Can somebody please tell me what should be the ‘intentname’ which i have to specify in manifest.xml
    While answering please remove the ‘greater than’ and ‘less than’ signs..

  21. Garry
    August 13th, 2010 at 21:44 | #21

    Trying to figure out all the android stuff – brand new to it — and having to build a simple alarm clock but can’t find *any* source code for 2.01 — can anyone point me to a simple example source code?

  22. Alioooop
    September 6th, 2010 at 17:27 | #22

    how can I get the alarm icon in the statusbar? something in the manifest right?

  23. September 8th, 2010 at 01:42 | #23

    Hi @Alioooop
    to set the alarm icon in the statusbar, add Notification on AlarmReceiver intent class, used following code to show the alarm_icon,

    //using notification manager
    NotificationManager mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

    int icon = R.drawable.alarm_icon;
    CharSequence tickerText = “Hello”;
    long when = System.currentTimeMillis();

    Notification notification = new Notification(icon, tickerText, when);

    Context context = getApplicationContext();
    CharSequence contentTitle = “My notification”;
    CharSequence contentText = “Hello World!”;
    Intent notificationIntent = new Intent(this, AlarmReceiver.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

    final int HELLO_ID = 1;

    mNotificationManager.notify(HELLO_ID, notification);

  24. Alioooop
    September 8th, 2010 at 02:23 | #24

    @mayur birari
    that notification appears on the left side right? but I want to have a on the right ide like in the real alarm app! other third party apps have that so it should go

  1. January 2nd, 2010 at 11:21 | #1
  2. March 14th, 2010 at 11:32 | #2