This is not a complete tutorial on how to use AlarmManager and NotificationManager, but a simple sample.
The scenario is I want to have an alarm set to certain time. When it goes off, it show notification icon on status bar. When click on the notification, it will start an activity.
1. Create the BroadcastReceiver
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
NotificationManager mNM;
mNM = (NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
// Set the icon, scrolling text and timestamp
Notification notification = new Notification(R.drawable.icon, "Test Alarm",
System.currentTimeMillis());
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, TestActivity.class), 0);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(context, context.getText(R.string.alarm_service_label), "This is a Test Alarm", contentIntent);
// Send the notification.
// We use a layout id because it is a unique number. We use it later to cancel.
mNM.notify(R.string.alarm_service_label, notification);
}
}
2. Add Receiver to Manifest.xml
<receiver android:process=":remote" android:name="AlarmReceiver"></receiver>
3. Set the alarm
public class AlarmService {
private Context context;
private PendingIntent mAlarmSender;
public AlarmService(Context context) {
this.context = context;
mAlarmSender = PendingIntent.getBroadcast(context, 0, new Intent(context, AlarmReceiver.class), 0);
}
public void startAlarm(){
//Set the alarm to 10 seconds from now
Calendar c = Calendar.getInstance();
c.add(Calendar.SECOND, 10);
long firstTime = c.getTimeInMillis();
// Schedule the alarm!
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, firstTime, mAlarmSender);
}
}