Sometimes it is required to display a notification at a specific time, a task that unfortunately is not trivial on the Android system, as there is no method setTime()
or similiar for notifications. This example outlines the steps needed to schedule notifications using the AlarmManager
:
BroadcastReceiver
that listens to Intent
s broadcasted by the Android AlarmManager
.This is the place where you build your notification based on the extras provided with the Intent
:
public class NotificationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Build notification based on Intent
Notification notification = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_notification_small_icon)
.setContentTitle(intent.getStringExtra("title", ""))
.setContentText(intent.getStringExtra("text", ""))
.build();
// Show notification
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(42, notification);
}
}
Register the BroadcastReceiver
in your AndroidManifest.xml
file (otherwise the receiver won't receive any Intent
s from the AlarmManager
):
<receiver
android:name=".NotificationReceiver"
android:enabled="true" />
Schedule a notification by passing a PendingIntent
for your BroadcastReceiver
with the needed Intent
extras to the system AlarmManager
. Your BroadcastReceiver
will receive the Intent
once the given time has arrived and display the notification. The following method schedules a notification:
public static void scheduleNotification(Context context, long time, String title, String text) {
Intent intent = new Intent(context, NotificationReceiver.class);
intent.putExtra("title", title);
intent.putExtra("text", text);
PendingIntent pending = PendingIntent.getBroadcast(context, 42, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Schdedule notification
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, time, pending);
}
Please note that the 42
above needs to be unique for each scheduled notification, otherwise the PendingIntent
s will replace each other causing undesired effects!
Cancel a notification by rebuilding the associated PendingIntent
and canceling it on the system AlarmManager
. The following method cancels a notification:
public static void cancelNotification(Context context, String title, String text) {
Intent intent = new Intent(context, NotificationReceiver.class);
intent.putExtra("title", title);
intent.putExtra("text", text);
PendingIntent pending = PendingIntent.getBroadcast(context, 42, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Cancel notification
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
manager.cancel(pending);
}
Note that the 42
above needs to match the number from step 3!