Is it possible to set an Android notification or a date and time to trigger later when the application is not running?
From what I’ve read, it seems like code like this needs the application to run in a thread until the notification is triggered. I need the notification to fire at a later date and time so that the user sees the notification like any other notification, then click on it and open an activity that passes some data so the app knows what to do.
How do I get this notification to trigger after a few days when the app isn’t running all the time?
Do I use wait to do this?
long millis = 60000;
myNotification.wait(millis);
Here is my code and it fires immediately
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(getActivity())
.setSmallIcon(R.drawable.star)
.setContentTitle("How was " + me.getString("EventTitle") + "?")
.setContentText("Click here to leave your review");
Intent resultIntent = new Intent(getActivity(), SetupActivity.class);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
getActivity(),
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
int mNotificationId = me.getInt("EventID");
Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
(NotificationManager) getActivity().getSystemService(getActivity(). NOTIFICATION_SERVICE);
Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());
Solution
As A-C writes, use AlarmManager
to schedule a PendingIntent
to be called at the time you want. You might use RTC_WAKEUP
alarm, meaning “Time based on System.currentTimeMillis(),
just like Calendar
uses” and “Let’s wake up and take the device out of sleep mode.” With broadcast PendingIntent
, your Notification code can go into the onReceive()
method if you don’t need to do any disk or network I/O to get the information used for the Notification
itself.
Note that in Android 4.4, the rules of AlarmManager
have changed a bit. You need to use setExact
() on Android 4.4+ and set()
on earlier Android versions.