Using AlarmManager to Schedule Activities on Android

Looking for a new mobile advertising platform? Check out my blog post on the new solution I am using (or sign-up if you don’t want to read the post)

 

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>).

 

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:

41 Comments

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">