Android Example : Alarm Manager Complete Working

AlarmManager as the name itself suggests is used to schedule time based operations outside the lifecycle of your application. With the help of AlarmManager you can schedule your application to run at any scheduled time in future. Once the scheduled time arrives the target application starts running even if the device is asleep.

Photo_1521975251900

Step -1 : Create a AlarmManager

AlarmManager can be easily accessed anywhere in your application with the help of Context object as shown below


AlarmManager alarmManager= (AlarmManager) context.getSystemService(ALARM_SERVICE);

Step 2 :  Create Broadcast Receiver

BroadcastReceiver is what will be triggered when the Alarm goes off at the scheduled time. You can read more about BroadcastReceiver  here  .

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        Toast.makeText(context,"Alarm Triggered",Toast.LENGTH_SHORT).show();

    }
}

 

Step 3 : Create a PendingIntent

Creating a PendingIntent is the most important part of scheduling an Alarm using AlarmManager. In fact this is what defines the operation which will be executed once the Alarm is triggered.

What is Pending Intent ?

PendingIntent is an object which wraps another intent object. We pass the pending intent to the AlarmManager which  basically gives AlarmManager the permission to trigger the wrapped intent as if it is being triggered from your own app(Even if your application is killed)

Following is how a pending intent is created


public static final int REQUEST_CODE=101;

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

PendingIntent.getBroadcast(this,REQUEST_CODE,intent,PendingIntent.FLAG_UPDATE_CURRENT);
/*
1st Param : Context
2nd Param : Integer request code
3rd Param : Wrapped Intent
4th Intent: Flag
*/

 

  • Always keep a note of the request code used while creating a pending intent. Request code is a unique identifier of that pending intent and can be used to get reference to that PendingIntent anywhere inside the application.
  • One more important factor while creating a pending intent is the flag passed in as the 4th parameter. Flags define the behavior of a PendingIntent and in turn the behavior of that Alarm.1. FLAG_CANCEL_CURRENT
    Flag indicating that if the described PendingIntent already exists, the current one should be canceled before generating a new one.

    2. FLAG_IMMUTABLE

    Flag indicating that the created PendingIntent should be immutable.

    3. FLAG_NO_CREATE

    Flag indicating that if the described PendingIntent does not already exist, then simply return null instead of creating it.

    4.FLAG_ONE_SHOT

    Flag indicating that this PendingIntent can be used only once.

    5. FLAG_UPDATE_CURRENT

    Flag indicating that if the described PendingIntent already exists, then keep it but replace its extra data with what is in this new Intent.

    Not choosing a proper flag could result in multiple duplicate alarms scheduled around the same time

Step 3: Choosing the Alarm Types

One of the first steps while creating an Alarm is choosing its type. This will define its behavior. There are basically two types of clocks to schedule time based alarms using AlarmManager. First is Elapsed Real Time- which uses the “time since system boot” for reference, second is Real time clock which uses UTC (wall clock) . Both also have their wake up version which defines whether the system should wake up the device when the alarm is triggered.

Here is the list of types:

  • ELAPSED_REALTIME—Fires the pending intent based on the amount of time since the device was booted, but doesn’t wake up the device. The elapsed time includes any time during which the device was asleep.
  • ELAPSED_REALTIME_WAKEUP—Wakes up the device and fires the pending intent after a specified length of time has elapsed since device boot.
  • RTC—Fires the pending intent at the specified time as per Wall Clock but does not wake up the device.
  • RTC_WAKEUP—Wakes up the device to fire the pending intent at the specified time as per Wall Clock.

 

Waking up the device refers to turning the device screen on if the device is in sleep mode

 

Final Step : Setting the Alarm

AlarmManager provides with number of methods which can be used based on how precise you want the alarm to be. Some of the most commonly used methods are

  • setInexactRepeating
    This schedules a repeating alarm which is inexact in its trigger time i.e. if you schedule the alarm to trigger at 8:00am it might not trigger exactly at the same time. These alarms are very power efficient as they adjust delivery times to fire multiple alarms simultaneously. This alarm will be repeated after a scheduled time

AlarmManager alarmManager= (AlarmManager) getSystemService(ALARM_SERVICE);

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

PendingIntent pendingIntent=PendingIntent.getBroadcast(this,REQUEST_CODE,intent,PendingIntent.FLAG_UPDATE_CURRENT);

/*
Alarm will be triggered approximately after one hour and will be repeated every hour after that
*/
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,System.currentTimeMillis()+AlarmManager.INTERVAL_HOUR,AlarmManager.INTERVAL_HOUR,pendingIntent);

/*
1st Param : Type of the Alarm

2nd Param  : Time in milliseconds when the alarm will be triggered first

3rd Param : Interval after which alarm will be repeated . You can only use any one of the AlarmManager constants

4th Param :Pending Intent

*/

  • setRepeating
    This is same as setInExactRepeating except for the fact that the alarm is triggered exactly at the scheduled time. Android suggests us to use this only when it is necessary as this puts unnecessary burden on the system since it wont be able adjust delivery time to bundle multiple alarms together. Like setInExactRepeating this alarm will repeat itself after a scheduled time

AlarmManager alarmManager= (AlarmManager) getSystemService(ALARM_SERVICE);

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

PendingIntent pendingIntent=PendingIntent.getBroadcast(this,REQUEST_CODE,intent,PendingIntent.FLAG_UPDATE_CURRENT);

Calendar calendar=Calendar.getInstance();

calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY,8);
calendar.set(Calendar.MINUTE,30);

/*
Alarm will be triggered exactly at 8:30 every day
*/
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);

/*
1st Param : Type of the Alarm

2nd Parm  : Time in milliseconds when the alarm will be triggered first

3rd Param : Interval after which alarm will be repeated .

4th Param : Pending Intent

Note that we have changed the type to RTC_WAKEUP as we are using Wall clock time

*/

  • set
    This will schedule a one time alarm which will be triggered approximately at the scheduled time. OS is allowed to adjust delivery time for these alarms. This alarm will be triggered only once.

AlarmManager alarmManager= (AlarmManager) getSystemService(ALARM_SERVICE);

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

PendingIntent pendingIntent=PendingIntent.getBroadcast(this,REQUEST_CODE,intent,PendingIntent.FLAG_UPDATE_CURRENT);
//This alarm will trigger once approximately after 1 hour and
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,System.currentTimeMillis()+AlarmManager.INTERVAL_HOUR,pendingIntent);

  • setExact
    This is same as set(context,timeMillis,pendingIntent) except for the fact that OS is not allowed to adjust the delivery time for these type of alarms. This shouldn’t be used unless there is a strong demand for alarm to be triggered at a precise time
AlarmManager alarmManager= (AlarmManager) getSystemService(ALARM_SERVICE);

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

PendingIntent pendingIntent=PendingIntent.getBroadcast(this,REQUEST_CODE,intent,PendingIntent.FLAG_UPDATE_CURRENT);

Calendar calendar=Calendar.getInstance();

calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY,5);
calendar.set(Calendar.MINUTE,30);

/*
Alarm will be triggered once exactly at 5:30
*/
alarmManager.setExact(AlarmManager.RTC,calendar.getTimeInMillis(),pendingIntent);

/*
1st Param : Type of the Alarm

2nd Param  : Time in milliseconds when the alarm will be triggered first

3rd Param :Pending Intent

Note that we have changed the type to RTC as we are using Wall clock time. Also device wont wake up
when the alarm is triggered

*/

 

Canceling the Alarm:

Canceling a scheduled alarm is much simpler than creating one. You just need to cancel with the same PendingIntent as shown below


alarmManager.cancel(pendingIntent);

You don’t even need  access to the same PendingIntent object for cancelling. You can create a new pending intent with the same request code and FLAG_NO_CREATE and it will return the same PendingIntent object


/*
With FLAG_NO_CREATE it will return null if the PendingIntent doesnt already exist. If it already exists it returns
reference to the existing PendingIntent
*/
PendingIntent pendingIntent=PendingIntent.getBroadcast(this,REQUEST_CODE,intent,PendingIntent.FLAG_NO_CREATE);

if (pendingIntent!=null)
alarmManager.cancel(pendingIntent);

 

Conclusion:

I hope by now you are pretty clear of how the AlarmManager works and how can it be used. If this article helped please like and feel free to comment any of your questions.

5 thoughts on “Android Example : Alarm Manager Complete Working

  1. Mor August 12, 2019 / 10:50 pm

    This is awesome, didn’t expect to find that quality of information 😉

    Like

  2. GGy September 4, 2019 / 12:11 pm

    And what about “AndroidManifest.xml”???

    Like

  3. Dannie Njango December 26, 2019 / 10:30 am

    Hey There. I discovered your blog using msn. This is an extremely well written article. I’ll make sure to bookmark it and come back to learn extra of your helpful info. Thanks for the post. I will definitely comeback.|

    Like

  4. Daniel April 18, 2020 / 12:00 am

    Hi , seems a good introduction to alarms in android thanks , but recentlly i can get the alarm work with this line of code in my android manifest (Android 9)

    Like

Leave a comment