I'm scheduling a repeating alarm, ringing every Tuesday morning, at 08:30.
Because of Doze, I can't use AlarmManager.setRepeating
because the time of the alarm won't be precise (it needs to be, I understand the effects on battery).
So, I use this code to schedule the first alarm :
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.setFirstDayOfWeek(Calendar.WEDNESDAY); // Trick not to get a "tuesday" timestamp in the past if today is wednesday+ !
calendar.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
long scheduledTime = calendar.getTimeInMillis();
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, scheduledTime, pendingIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, scheduledTime, pendingIntent);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, scheduledTime, pendingIntent);
}
And it works flawlessly.
Problem is, I have to re-schedule the alarm when the Intent
in consumed by my BroadcastReceiver
, on Tuesday, 8:30AM.
But between Tuesday 08:30 and Tuesday 23:59, the method will give me a timestamp in the "past", which is incorrect.
Is there any method than "if the provided timestamp is in the past, add 1 week to it" to fix this issue?