Android AlarmManager - Androhub

AlarmManager

Android AlarmManager

Daily we used to set Alarms in our phone to wake up in morning or for some meetings, etc. I used to set lot of alarms for morning but unfortunately i used to wake up late only. 😛  So today we are going to learn about Alarms. Alarms (based on the AlarmManager class) give you a way to perform time-based operations outside the lifetime of your application. For example, you could use an alarm to initiate a long-running operation, such as starting a service once a day to download a weather forecast. You can schedule your application to run at a specific time in the future. It works whether your phone is running or not.

AlarmManager is having different characteristics mentioned below:

  • AlarmManager runs outside the lifetime of your application. Once an alarm is scheduled, it will invoke even when your application is not running or in sleep mode.
  • An scheduled alarm will execute unless it is stopped explicitly by calling cancel() method, or until device reboots.
  • All scheduled alarms will be stopped when device reboots. This means, you need to re-schedule them explicitly when device boot completes.
  • AlarmManger fires an Intent at given intervals. This can be used along with broadcast receivers to start a service to perform network operations.
  • AlarmManager is different form java Timer and TimerTask.

Android supports two clock types for alarm service; Elapsed real time and real time clock (RTC). Elapsed real time uses the time since device last booted. Real time clock (RTC) uses UTC time for alarm service clock. RTC is most commonly used for setting alarm service in android. The following example, using RTC to schedule alarm.

Prerequisite:

  1. Radio Button.
  2. Notification Manager.
  3. Services.
  4. Broadcast Receiver.

Example

In this tutorial, we will learn how to use AlarmManager that runs after a specific time provided by user.

VIDEO DEMO

1. Create a new project in Android Studio by navigating to File ⇒ New ⇒ New Project and fill required details. By default my activity is MainActivity.java.

2. Open res ⇒ values ⇒ strings.xml and add below string values. These are some strings that we are going to use in our project.

3. Open your activity_main.xml layout and place the below code to it. The layout contains some RadioButton, Edit Text and Button.

4. Now create Broadcast Receiver java class naming AlarmReceiver.java which will invoke by AlarmManger. Here you can do your task like I am running AlarmSound by starting a service and also displaying a Notification.

Alarm Triggered
Alarm Triggered

5. Let us have a look into MainActivity.java file. In this class, we have defined two simple methods triggerAlarmManager(int alarmTriggerTime) and stopAlarmManager().

  • Retrieve PendingIntent : These two lines of use to get the PendingIntent of AlarmReceiver broadcast receiver.

  • Trigger AlarmManager :triggerAlarmManager(int alarmTriggerTime) method use to set the AlarmManager at particular time that we pass in parameter.

Set AlarmManager
Set AlarmManager

  • Stop AlarmManager :stopAlarmManager() method use to stop any running alarm. As I am playing sound and displaying notification as well so i am stopping the sound and cancelling the notification respectively.

Final Source Code

6. As we started sound service in AlarmReceiver.java class, so now create a AlarmSoundService.java class extending with Service. This class will use to play the alarm sound in onCreate() and stop the sound in onDestroy() when user stops the Alarm.

You can download the Alarm Sound mp3 file from this link. Its a good website for Alarm Sounds.

7. Also we are displaying Notification when Alarm starts so lets create new java class naming AlarmNotificationService.java and extend it with IntentService. This class used to show notification.

Alarm Notification
Alarm Notification

8. Also don’t forget to declare BroadCastReceiver, Service and IntentService in Manifest file and as we are showing notification with WAKE_LOCK so use the android.permission.WAKE_LOCK permission. Your AndroidManifest.xml will look like as below.

9. Finally all done, now you can also make apps with AlarmManager.

Thanks. :)

 

37 Comments

Crsitofer
Tuesday, June 27th, 2017

What Android OS version are you using? because I added a reminder for one of my app, it is working well in Pre Nougat versión but in Nougat version the dayInterval is not working!

Dr. Droid
Tuesday, June 27th, 2017

Hi Cristofer,

I am using Marshmallow OS Version for testing. I have not tested in Nougat OS Devices.

Thanks.

Vijay
Thursday, August 17th, 2017

How to trigger the alarm for every 5 seconds. I want to hit my server every 5 secs. Can you give me sample for that?

Dr. Droid
Friday, August 18th, 2017

Hi Vijay,

Please see the article by clicking below link:
https://www.androhub.com/android-image-slider-using-viewpager/

In this article I am using TIMER inside MainActivity.java to slide the images after 3 sec. So you can also use that TIMER code to hit your server after 5 sec by changing the value.

Thanks

vikas joshi
Sunday, September 24th, 2017

can you tell me
how to can pick image compressed to gallery
like whats up profile set gallery

Dr. Droid
Monday, September 25th, 2017

Hi Vikas Joshi,

For picking image from gallery see this article : https://www.androhub.com/select-and-share-multiple-images/

To compress image visit this link : https://stackoverflow.com/questions/18545246/how-to-compress-image-size

Thanks

INDRAKANTH
Thursday, November 9th, 2017

Hi,
I slightly modified this code to do a periodic task by broadcasting the alarm receiver class for every 30 mins from alarm notifier service class.
Butt after 3-4 intervals it stopped showing notifications. May I know the reason for that

Dr. Droid
Thursday, November 9th, 2017

Hi Indrakanth,

Can you please share your changes so that i can see what is creating the issue.

Thanks

INDRAKANTH
Friday, November 10th, 2017

I have downloaded your sample and modified AlarmReceiver and AlarmNotificationService only to implement periodic notification.
Below are my changes.
AlarmReceiver.java:
In Onreceive() i commented out the alarmSoundService to get only notification.

Toast.makeText(context, “ALARM!! ALARM!!”, Toast.LENGTH_SHORT).show();
//Stop sound service to play sound for alarm
//context.startService(new Intent(context, AlarmSoundService.class));
//This will send a notification message and show notification in notification tray
ComponentName comp = new ComponentName(context.getPackageName(),
AlarmNotificationService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));

Changes in AlarmNotificationService: I wrote the code to broadcast the alarmReceiver for every 30mins.
public void onHandleIntent(Intent intent) {
Calendar cal = Calendar.getInstance();
Intent alarmIntent = new Intent(AlarmNotificationService.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(AlarmNotificationService.this, 133, alarmIntent, 0);
cal.add(Calendar.MINUTE,30);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);//get instance of alarm manager
manager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);//set alarm manager with entered timer by converting into milliseconds
//Send notification
sendNotification(“Wake Up! Wake Up! Alarm started!!”);
}

INDRAKANTH
Friday, November 10th, 2017

I already shared the sample
But not sure why it is not showing here even though it generated a comment number successfully

INDRAKANTH
Friday, November 10th, 2017

I have downloaded your sample and modified AlarmReceiver and AlarmNotificationService only to implement periodic notification.
Below are my changes.
AlarmReceiver.java:
In Onreceive() i commented out the alarmSoundService to get only notification.

//Stop sound service to play sound for alarm
//context.startService(new Intent(context, AlarmSoundService.class))
//This will send a notification message and show notification in notification tray
ComponentName comp = new ComponentName(context.getPackageName(),
AlarmNotificationService.class.getName())
startWakefulService(context, (intent.setComponent(comp)))

Changes in AlarmNotificationService: I wrote the code to broadcast the alarmReceiver for every 30mins.
public void onHandleIntent(Intent intent)
Calendar cal = Calendar.getInstance()
Intent alarmIntent = new Intent(AlarmNotificationService.this, AlarmReceiver.class)
pendingIntent = PendingIntent.getBroadcast(AlarmNotificationService.this, 133, alarmIntent, 0)
cal.add(Calendar.MINUTE,30)
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE)//get instance of alarm manager
manager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent)//set alarm manager with entered timer by converting into milliseconds
//Send notification
sendNotification(“Wake Up Wake Up Alarm started”)

Dr. Droid
Friday, November 10th, 2017

Hi Indrakanth,

You need to use setRepeating() method instead of set(). I am sharing some links for your reference so that you can check the code and implement it in correct way.

1. https://stackoverflow.com/questions/22189283/how-to-set-time-for-repeating-alarm-for-every-15-mints-in-android
2. https://stackoverflow.com/questions/26573341/scheduling-alarm-every-2-minutes-android

Hope it will help you.

Thanks

INDRAKANTH
Friday, November 10th, 2017

Hi
I modified the main activity.java from set to set repeating as suggested and gave the interval that we sepcify in this demo as frequency.
I commented the setlooping true as the alarm will ring and stop on its own.
Everything worked fine till 7hrs i.e for 14 intervals. After that I went to a meeting where I left the mobile idle at desk for more than 1hr. After that there are no notifications?
Not sure why?

Dr. Droid
Friday, November 10th, 2017

Hi Indrakanth,

This is strange issue.
Can you please tell me in which device you are testing the app with OS Version?

So that i can do some research for you. And you also do some research about this strange issue.

Thanks

INDRAKANTH
Friday, November 10th, 2017

I am using Xiaomi mi Redmi 3s prime mobile with android 6.0.1 with an miui version miui global 8.5.
I have been investigating this issue from past 2months. I observed this similar behavior in letv le2 mobiles too.

Dr. Droid
Friday, November 10th, 2017

Hi Indrakanth,

If possible can you test in any other device like Samsung or Moto so that we can conclude that it is working on all devices or in some devices it is creating issue.

Thanks

INDRAKANTH
Friday, November 10th, 2017

I tested similar functionality on Moto device and found that it stopped working after a day. But I will install your demo sample with my changes on the Moto device and let u know in 2 days. In mean while I would like you too continue analysis on this

INDRAKANTH
Monday, November 13th, 2017

Hi
I tested this on xperia mobile which is working on android 7.1.1 and observed that it is working fine, I believe that the problem is with non pure android version mobiles. Is there any workaround /solution to handle this issue.

Dr. Droid
Monday, November 20th, 2017

Hi Indrakanth,

I found one library which is very great for all the API levels.

https://github.com/evernote/android-job

Implement this library and it will handle everything.

Thanks

wesley
Thursday, September 6th, 2018

como faço para salvar vários alarmes?

Dr. Droid
Friday, September 7th, 2018

Hi Wesley,

Crie várias instâncias de alarme.

Thanks

Tongdee
Friday, January 18th, 2019

Hi Dr.
I am tongdee ,be a housekeeper,and want to be gardener .would you mind to discuss ” How can i take picture and up load it to internet and can see it on phone or computer”
thank.

Dr. Droid
Wednesday, January 23rd, 2019

Hi Tongdee,

Can you mail me your requirements so that I can guide you properly.

Thanks

Maico
Tuesday, February 26th, 2019

Sir good day. Thank you for your example it really helped me with my project but there’s only one thing i cannot solve, the alarm is working fine but when i try to turn off the phone/get the battery to test if the alarm will still continue after turning it on and it doesn’t and that’s my problem please help me with this Sir. Thank you

Maico
Tuesday, February 26th, 2019

Sir how the app is working fine but it wont alarm when the phone turned off, after turning on the it doesn’t alarm anymore.
Please help me Sir. Thank You so much

Dr. Droid
Tuesday, February 26th, 2019

Hi Maico,

To start the alarm again when you restart your device. You have to listen BOOT_COMPLETED broadcast to start the service again.

Check this link for help.

Thanks

Rose
Sunday, March 31st, 2019

Hello, how do i add R.raw.alarm_sound in AlarmSoundService class in android studio. Since it is giving me an error of cannot resolve symbol ‘raw’. How do i solve this?

Rose Stacy
Monday, April 1st, 2019

Hello,
how do i add notification sound from the link you provided to AlarmSoundService class. Since
mediaPlayer = MediaPlayer.create(this, R.raw.alarm_sound); when i put this code it is giving me an error on raw. saying it can not resolve this. How do i solve this?

Dr. Droid
Wednesday, April 3rd, 2019

Hi Rose,

Have you created raw directory and kept the sound file into it?

Thanks

Stacy
Tuesday, April 2nd, 2019

hello,
i have followed your code but when i press start button i get a message of alarm is set for 2 seconds, then i get null pointer exception error, that the app has stopped.

How do i solve this?

Dr. Droid
Wednesday, April 3rd, 2019

Hi Stacy,

Null pointer exception occurs when something is not initialised. So cross check your code and check which one is not initialised.

Thanks

MariannaTD
Saturday, August 3rd, 2019

Hello!! i am following your example but in the BroadcastReceiver when i use the library WakefulBroadcastReceiver doesnt work, says that doesnt have the library anymore. Is there another library that works the same as this library or something? i’ll really appreciate your response !! Thank you for your work

Dr. Droid
Monday, August 12th, 2019

Hi Marianna TD,

WakefulBroadcastReceiver has been deprecated and Android discourage to use it. You can check the replacement here: https://stackoverflow.com/questions/47217345/wakefulbroadcastreceiver-is-deprecated.

Thanks

Chirag Prajapati
Friday, January 24th, 2020

Hello, I want some help from you.

I have created reminder app and I used Work manager, Job scheduler & Firebase JobDispater but It will not exacute on exact time which I have given the job. I really don’t know that How can I manage my all reminder in app. I heard that Alarm Manager is not supported in newer version? Is it right?

Can you please tell me about How can I schedule reminders? And It must be execute on given time.

Please answer fast as possible.
Thank you.

Dr. Droid
Friday, January 24th, 2020

Hi Chirag,

Still, you can use alarm manager see this link: https://developer.android.com/training/scheduling/alarms
Only the methods have changed.

And due to the doze mode and app standby, the alarms can be delayed.

Thanks

Nikki
Sunday, October 24th, 2021

hi i noticed that the alarm manager notification is only work for android 6.0, can you help me how can i also notified it to android 8.0 and higher?

thank you

Post comment

Your email address will not be published. Required fields are marked *