How To Start Notification On Custom Date&time?
I know how to start a notification X milliseconds after some click event. A code like this Timer timer = new Timer(); TimerTask timerTask = new TimerTask() {
Solution 1:
I think that the best way will be to create a service that sets the notification and then activate the service using an AlarmManager. Here is my code for doing that. That's the code for the AlarmManager:
privatevoidstartAlarm() {
AlarmManager alarmManager = (AlarmManager) this.getSystemService(this.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(int year, int month, int date, int hour, int minute, int second);
longwhen = calendar.getTimeInMillis(); // notification time
Intent intent = new Intent(this, ReminderService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0);
alarmManager.set(AlarmManager.RTC, when, pendingIntent);
}
Here is the Service:
publicclassReminderServiceextendsIntentService {
privatestaticfinalintNOTIF_ID=1;
publicReminderService(){
super("ReminderService");
}
@OverrideprotectedvoidonHandleIntent(Intent intent) {
NotificationManagernm= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
longwhen= System.currentTimeMillis(); // notification timeNotificationnotification=newNotification(R.drawable.icon, "reminder", when);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.flags |= notification.FLAG_AUTO_CANCEL;
IntentnotificationIntent=newIntent(this, YourActivity.class);
PendingIntentcontentIntent= PendingIntent.getActivity(this, 0, notificationIntent , 0);
notification.setLatestEventInfo(getApplicationContext(), "It's about time", "You should open the app now", contentIntent);
nm.notify(NOTIF_ID, notification);
}
}
Post a Comment for "How To Start Notification On Custom Date&time?"