Alarm Manager in Android

This entry is part 42 of 50 in the series Android Development Primer

AlarmManager as the name suggests is used to schedule actions in an Android system. Do not be misled by the name that it is used to schedule the alarms. It can be used to schedule alarms, notifications, broadcasts etc.

In this post I will show you how to schedule a notification from your application. We will make use of Alarm Manager through which we will send a broadcast, and a Broadcast Receiver using which we will receive the broadcast and use it to create a notification. Complete Source Code is at the bottom.

  • Set up a layout for your activity.
  • Switch to the Java file and create a global Alarm Manager object.
  • Define the object inside the onCreate() method.
    am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    
  • Create a new method setAlarm(). Write the following lines inside it.
    Intent intent = new Intent(this, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    am.cancel(pendingIntent);
    GregorianCalendar alarmtime = new GregorianCalendar();
    alarmtime.set(GregorianCalendar.HOUR_OF_DAY, 6);
    alarmtime.set(GregorianCalendar.MINUTE, 0);
    alarmtime.set(GregorianCalendar.SECOND, 0);
    alarmtime.set(GregorianCalendar.MILLISECOND, 0);
    if(alarmtime.before(new GregorianCalendar()))alarmtime.add(GregorianCalendar.DAY_OF_MONTH, 1);
    am.set(AlarmManager.RTC_WAKEUP, alarmtime.getTimeInMillis(), pendingIntent);
    
  • Call this method inside the onCreate() method.
  • Create a new Java class that extends BroadcastReceiver class. Name it AlarmReceiver.java. Note that we have already used this name in the method setAlarm() above.
  • Inside the onReceive() method write the following lines. I will explain these line in a moment.
    notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    Intent i = new Intent(context, Second.class);
    PendingIntent pi = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
    
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent pi2 = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + AlarmManager.INTERVAL_DAY, pi2);
    
    CharSequence from = "Nero";
    CharSequence message = "Test Notification";
    notification = new Notification(R.drawable.ic_launcher,"Attention",System.currentTimeMillis());
    notification.setLatestEventInfo(context, from, message, pi);
    notification.defaults|= Notification.DEFAULT_SOUND;
    notification.defaults|= Notification.DEFAULT_LIGHTS;
    notification.defaults|= Notification.DEFAULT_VIBRATE;
    notificationManager.notify(1, notification);
    return;
    
  • Add an entry in your manifest file
    <receiver android:name=".AlarmReceiver">
         <intent-filter>
            	<action android:name="android.intent.action.BOOT_COMPLETED"/>
         </intent-filter>
    </receiver>
    
  • Save it and execute it on a device or an emulator. Remember that we have scheduled a notification ar 6 am. You might need to change the date and time to see that the notification appears.

Understanding the Code

  • GregorianCalendar is a form of calendar present in the Android system. You can use Calendar too. Google it.
  • PendingIntent –¬†It should be quite enough for you to know that we are creating an Intent that has to be fulfilled. The Broadcast receiver does that.
  • RTC_WAKEUP is used so that if your device is switched off, it starts up at the scheduled time and performs the action.
  • In the AlarmReceiver we are creating another PendingIntent that creates the intent for the alarm to fire the next day exactly at the same time.
  • ALARM_SERVICE is a service of Android system that we are calling inside the Broadcast Receiver.
  • FLAG_CANCEL_CURRENT is used to cancel any outstanding Intents. This is done so that at a time only a single Intent is active.
  • notification.defaults|= Notification.DEFAULT_SOUND –¬†This provides for the Sound attributes of the notification. Same is the case with vibrate and Lights.

COMPLETE SOURCE CODE

AlarmReceiver.java

package com.nero.myfirstapp;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;

public class AlarmReceiver extends BroadcastReceiver {

	NotificationManager notificationManager;
	Notification notification;
	@Override
	public void onReceive(Context context, Intent intent) {
		notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		Intent i = new Intent(context, Second.class);
		PendingIntent pi = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
		
		AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		PendingIntent pi2 = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
		am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + AlarmManager.INTERVAL_DAY, pi2);
		
		CharSequence from = "Nero";
		CharSequence message = "Test Notification";
		notification = new Notification(R.drawable.ic_launcher,"Attention",System.currentTimeMillis());
		notification.setLatestEventInfo(context, from, message, pi);
		notification.defaults|= Notification.DEFAULT_SOUND;
		notification.defaults|= Notification.DEFAULT_LIGHTS;
		notification.defaults|= Notification.DEFAULT_VIBRATE;
		notificationManager.notify(1, notification);
		return;
	}
}
		

MainActivity.java

package com.nero.myfirstapp;

import java.util.ArrayList;
import java.util.GregorianCalendar;

import com.psyduck.myfirstapp.AlarmReceiver;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class Main extends Activity {
	AlarmManager am;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		setAlarm();
	}

	public void setAlarm(){
		Intent intent = new Intent(this, AlarmReceiver.class);
		PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
		am.cancel(pendingIntent);
		GregorianCalendar alarmtime = new GregorianCalendar();
		alarmtime.set(GregorianCalendar.HOUR_OF_DAY, 6);
		alarmtime.set(GregorianCalendar.MINUTE, 0);
		alarmtime.set(GregorianCalendar.SECOND, 0);
		alarmtime.set(GregorianCalendar.MILLISECOND, 0);
		if(alarmtime.before(new GregorianCalendar()))alarmtime.add(GregorianCalendar.DAY_OF_MONTH, 1);
		am.set(AlarmManager.RTC_WAKEUP, alarmtime.getTimeInMillis(), pendingIntent);

	}
}
Series Navigation<< Custom Data Adapters with Checked List Views – Part IINumber Picker in Android >>

Leave a Reply

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

*

* Copy This Password *

* Type Or Paste Password Here *

41,650 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>