Apps

Use Android's AlarmManager to schedule an event

This app development tutorial is the most basic implementation of the powerful Android AlarmManager class.

A few weeks back, I wrote a post on Android's chronometer widget. It works great for measuring elapsed time, but what if you need to schedule an event in the future? In some cases, you can get away with a simple post delayed handler, but Android's handler class doesn't guarantee accuracy, and it can be difficult to directly correlate a post handler's relative time to a deterministic calendar date time. In these cases, there is no better class to handle the job than Android's AlarmManager.

The example that follows demonstrates using the AlarmManager class in its most basic capacity. You can follow along with the step-by-step tutorial or download and import the project in its entirety.

1. Create a new Android project in Eclipse. Target Android 1.6 or higher. Rename the startup activity to Main.java and the corresponding layout to main.xml.

2. Our layout could not be simpler. In the /res/main.xml file, we create a linear layout that contains a single text view and one button.

main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:layout_gravity="center"
    android:gravity="center">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Alarm Example" />
    <Button
        android:id="@+id/the_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Set"/>
</LinearLayout>

3. In the /src file, we create an activity that implements an on click handler. We need to go ahead and declare a few class level variables. The on create override is responsible for wiring up the button to the listener and calling our private setup function.

Main.java

package com.authorwjf.wakemeup;
import android.os.Bundle;
import android.os.SystemClock;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
public class Main extends Activity implements OnClickListener{
       final static private long ONE_SECOND = 1000;
       final static private long TWENTY_SECONDS = ONE_SECOND * 20;
       PendingIntent pi;
       BroadcastReceiver br;
       AlarmManager am;
       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main);
              setup();
              findViewById(R.id.the_button).setOnClickListener(this);
       }
}

4. The private method setup initializes the class level variables, including the new broadcast receiver that will act as the callback for our alarm.

private void setup() {
      br = new BroadcastReceiver() {
             @Override
             public void onReceive(Context c, Intent i) {
                    Toast.makeText(c, "Rise and Shine!", Toast.LENGTH_LONG).show();
                    }
             };
      registerReceiver(br, new IntentFilter("com.authorwjf.wakeywakey") );
      pi = PendingIntent.getBroadcast( this, 0, new Intent("com.authorwjf.wakeywakey"),
0 );
      am = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
}

5. In the on click listener, we set the alarm. For our example, I'm setting it for 20 seconds from whatever the time happened to be when the button was clicked.

@Override
public void onClick(View v) {
       am.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 
TWENTY_SECONDS, pi );
}

6. The AlarmManager requires a bit of cleanup when the user exits the application. We can take care of this by overriding the on destroy method.

@Override
protected void onDestroy() {
       am.cancel(pi);
       unregisterReceiver(br);
       super.onDestroy();
}
Now the application is ready to build and run. Deploy it to a device, click the button, and wait 20 seconds (Figure A). Figure A

AlarmManager is a very powerful class that deserves a closer look at the official Android documentation. When combined with the PowerManager class, alarm manager even has the power to wake up the device from sleep to run your code at a future date or a repeatable interval.

About

William J Francis began programming computers at age eleven. Specializing in embedded and mobile platforms, he has more than 20 years of professional software engineering under his belt, including a four year stint in the US Army's Military Intellige...

1 comments
tigana086
tigana086

Hello Dear Wiiliam,I really like this tutorial! i'm new learner.I want know how to reset this alarm when the phone reboots.I will be more than happy you can help on that.I have already tried many ways without success.

Thank very much for your help

Editor's Picks