I'm trying to schedule some local notifications on specific days and I'm using the AlarmManager to schedule them. Unfortunately it does not work for times in the future. Any ideas why?
This is how I compute the time when the alarm should be triggered
private long computeDelay(int day){
long currentSystemTime = System.currentTimeMillis();
Calendar scheduleTime = Calendar.getInstance();
// used to compute number of hours and mins
int currentDay = scheduleTime.get(Calendar.DAY_OF_MONTH);
scheduleTime.set(Calendar.DAY_OF_MONTH, currentDay + day);
scheduleTime.set(Calendar.HOUR, 7);
scheduleTime.set(Calendar.MINUTE, 0);
scheduleTime.set(Calendar.SECOND, 0);
scheduleTime.set(Calendar.AM_PM, Calendar.PM);
return scheduleTime.getTimeInMillis();
}
And this is how I schedule the alarms.
private void scheduleNotification(Notification notification, long time) {
Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, 1);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, notification);
notificationIntent.addCategory("android.intent.category.DEFAULT");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
}
The context is the application (i.e. getApplication()).
Many thanks!
The problem was with how I was getting the PendingIntent.
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
I was calling the alarm schedule method several times and the request code was always 0 so it was only scheduling the last alarm. I'm giving each alarm schedule a unique request code now and it seems to work fine.