Using AlarmManager to Schedule Activities on Android
Sometimes, it may be necessary for your android app to complete a task sometime in the future. In order to do this, you must schedule an activity (can also be a service) to be run using Android’s AlarmManager. This post will show:
- How to set up a receiver for the scheduled event
- How to create an activity from this receiver
- Using the AlarmManager and the created classes to successfully receive and process a scheduled event
Want the code? Get the source for only $1.49 (50% off). Click the button below to buy now:
Creating a BroadcastReceiver
The first thing you will need is a receiver to receive the event. There are several key aspects to have for the receiver to work properly. First create a class that extends BroadcastReceiver and override and implement the necessary onReceive(Context context, Intent intent) method. The following is a basic example using a Toast message:
package com.justcallmebrian.alarmexample; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; import android.os.Bundle; public class AlarmReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { try { Bundle bundle = intent.getExtras(); String message = bundle.getString("alarm_message"); Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(context, "There was an error somewhere, but we still received an alarm", Toast.LENGTH_SHORT).show(); e.printStackTrace(); } } }
In the previous example, we are simply just printing out the message supplied by the String passed in under the name of alarm_message. For those who are not familiar with Toast, it is basically a short and quick message given to the user. Here you can find more information on Toast.
Besides actually creating the class to receive the event, you must also declare it within AndroidManifest.xml. The following is the line that should be added before the closing of the application tag (before </application>).
<receiver android:process=":remote" android:name="AlarmReceiver"></receiver>Basically this states that the class AlarmReceiver is available and will start a private process. Once that is done, your BroadcastReceiver is ready to go.
Setting up an Event using AlarmManager
In order to receive an event, you obviously must schedule the event. There are three ways of scheduling an event (a one time event using the set method, a repeating event using the setRepeating method and finally using the setInexactRepeating). This tutorial will cover the one time alarm using the set method. For more information regarding the other events, you can view AlarmManager. The following code snippet will get the AlarmManager and set an event to occur 5 minutes from the current time:
// get a Calendar object with current time Calendar cal = Calendar.getInstance(); // add 5 minutes to the calendar object cal.add(Calendar.MINUTE, 5); Intent intent = new Intent(ctx, AlarmReceiver.class); intent.putExtra("alarm_message", "O'Doyle Rules!"); // In reality, you would want to have a static variable for the request code instead of 192837 PendingIntent sender = PendingIntent.getBroadcast(this, 192837, intent, PendingIntent.FLAG_UPDATE_CURRENT); // Get the AlarmManager service AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
This code snippet basically obtains a new Calendar object and adds 5 minutes to it. An Intent is created with the AlarmReceiver which we created earlier. The more important piece of the code is setting the FLAG_UPDATE_CURRENT flag. Without this flag, the message being passed as an Extra will be lost and not obtained by the receiver.
With these code snippets you should be able to create and run some tasks in the BroadcastReceiver. However, sometimes you may wish to start a new activity (or service) on the alarm event. In order to do this, you would want to have the AlarmReceiver create and start the new Activity.
Starting an Activity from BroadcastReceiver
Starting an activity within a Receiver has an extra flag that is needed. We will change the previous onReceive for AlarmReceiver to get this done:
@Override public void onReceive(Context context, Intent intent) { try { Bundle bundle = intent.getExtras(); String message = bundle.getString("alarm_message"); Intent newIntent = new Intent(context, AlarmActivity.class); newIntent.putExtra("alarm_message", message); newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(newIntent); } catch (Exception e) { Toast.makeText(context, "There was an error somewhere, but we still received an alarm", Toast.LENGTH_SHORT).show(); e.printStackTrace(); } }
Now you would only have to create the new AlarmActivity as you would do any other Activity. Don’t forget to include the newly created activity in the AndroidManifest.xml file.
Want the code? Next 1000 people will get the source for only $1.49 (50% off). That’s the whole project (source, resources, xml files, etc) for only $1.49. Click the button below to buy now:
Likes the tutorial? Show it by donating and helping a great cause. All donations are made to Maryland Special Olympics:
[...] This post was mentioned on Twitter by Brian Call. Brian Call said: Tutorial on how to schedule and run tasks on Android using the AlarmManager http://bit.ly/a29ila [...]
Very handy tutorial, best on the web, thanks
Awesome. I just started working on this. Thanks for the tutorial
That is exactly what I need. Thanks a lot.
Great work.
Hi,
i’ve just started to work with android. I got this error message while trying to run your code:
The method getMessage(String) is undefined for the type Bundle
Thanks for the comment. It appears getMessage is no longer a method. You may want to use getString now.
I have updated my post to account for this.
Thanks again, and let me know if you need any additional help.
Thanks for the tutorial. Great work.
thanks a lot for such an important code snippet about intent from broadcast receiver. I was struggling hard to display an intent from broadcast receiver and finally got it working coz of your tutorial.
hey guys i m using alarm manager to run my application at specific point of time. I want to run to run my application on every weekdays ( Mon-fri ) so could u please tell me how to do this..
Hi, can you add the full code for this example?
Thanks a lot.
simple, concise, complete – thanks!!
Hi,
I am new to android and I created two classes one that has an oncreate event where I copied the code from “Setting up an Event using AlarmManager” and other class “AlarmReceiver” that has the code from AlarmReceiver.java with the onreceive event.
When I try to execute it, I get an error like this “Application has stopped unexpectedly”. Can anyone please help me up.
Need help asap.
Thanks,
Jason
It’s Great . Thnx very much. This is exactly what i need………..
very very helpful mate, and appreciated!
thank youuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
veeeeeeeeeeeeeerrrrrrrrrrrrrrryyyyyyyyyyyyyyyyyyyyyyyyyyy
mmmmmmmmmmmmmmmmmmuuuuuuuuuuuuuuuuuuuccccccccccccchhhhhhhhhhhhhhhhhhhhhhhhhhh
you tutorial is so much help full to me
hii..tutorial was very helpful… but what happens if my cellphone is switched off at the particular time when the activity had to occur…. How should i modify the code so that an error msg is displayed if the activity is not performed at the specified time….
Once again thanks a lot…Really very helpful..
Thanks for this example. It works as intended.
Hi..
hanks a lot for such an important code snippet about intent from broadcast receiver..but in my application i require to alert user for every one min..from before 5 min of ending the event. how can i achieve using alarm manager..
[...] [...]
That’s really tnhkinig out of the box. Thanks!
Perfect, really helpful tutorial about the core parts. Just what I was looking for and will try setting custom data on the intent to set multiple alarms at the same time.
[...] here is a tutorial for your viewing [...]
[...] here is a tutorial for your viewing [...]
Hey there, this was helpful. Thanks!
[...] An alarm is perfect for this. You can have your application request the system to set off the alarm every 30 minutes (either manually each time or with the setRepeating() method). This alarm will go off regardless of whether your application is running at the time or not. You will need a broadcast receiver to handle the intent it generates. There is a good tutorial on alarms here. [...]
Generally i don’t post comments but just this time:P I just want to say great job!
Thank you very much….
We’re a group of volunteers and starting a new scheme in our community. Your site provided us with valuable info to work on. You’ve done an impressive job and our entire community will be grateful to you.
Absolutely first class tutorial!
You have clarified the process so succinctly for me.
Much gratitude from me to you mate!!!
Thanks!
This is really interesting, You’re a very skilled blogger. I’ve joined your rss feed and look forward to seeking more of your great post. Also, I’ve shared your site in my social networks!
Hi! If you like article marketing as a way to spread the word…… Cheers!
… [Trackback]…
[...] There you will find more Infos: justcallmebrian.com/?p=129 [...]…
Simple and one of the best tutorial for Beginners of android… Thanks
Hi,
nice work, but I’m a bit disappointed about the “full” source code. $2.99 is rather steep for essentially the same content as but without in-line comments
((
Aph, thanks for your comments.
Just a quick note, it’s one thing to have snippets of code within a tutorial, but having the full source (including all resource files) that can be downloaded and compiled without any possible issues is always nice. Just check some of the comments below asking I put the source code up in its entirety (one of the reasons I did).
Thanks,
Brian
P.S. You should have received a partial refund.
just wanted to say thanks, it was very helpful!
FLAG_UPDATE_CURRENT flag used in the PendingIntent is not necessary to pass the extras like you mentioned. Here we’re creating a PendingIntent and handing it out to a service (AlarmManager) which is outside of our application and lives even if our app. gets terminated by the user. So, when the user tries to create another PendingIntent with the same signature (same operation, same Intent action, data, categories, and components, and same flags) an instance of the existing intent (maintained by AlarmManager) will be returned. This will contain the old extras that we had passed and not the new ones which we have now provided. In order to get the old PeningIntent but with the new extras (remember AlarmManager still maintains a copy of the old one till the alarm goes off or your phone gets re-booted) we use the flag FLAG_UPDATE_CURRENT which is more than obvious from the name of the flag.
Thnks a lot!!dis was really helpful:):)
Thanks, very helpful.
[...] Using AlarmManager to Schedule Activities on Android as a tutorial and example. Tagged: AndroidJava /* * * CONFIGURATION [...]