Tuesday, July 12, 2011

AlarmManager and NotificationManager sample code

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

publicclass AlarmReceiver extends BroadcastReceiver {
@Override
publicvoid 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);
}
}

@Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the current time as the default values for the picker final Calendar c = Calendar.getInstance(); int hour = c.get(Calendar.HOUR_OF_DAY); int minute = c.get(Calendar.MINUTE);

// Create a new instance of TimePickerDialog and return it return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity())); }

public void onTimeSet(TimePicker view, int hourOfDay, int minute) { // Do something with the time chosen by the user