Search code examples
androidalarmmanagerandroid-alarms

How far (and why!) do Android alarms execute in the past?


I have had several frustrations with setting alarms in Android. I have tried setting repeating/non-repeating alarms and exact/inexact alarms but it does not matter, if the alarm is ever set for a time in the past, it executes as soon as it is set. I have tested this as far back as setting an alarm for 5 hours in the past and is still executes immediately.

For example:

The time is 7 AM and I set an alarm to execute at 2 AM. This is obviously meant for the next time the clock reads 2:00 AM but it does not matter, the alarm goes off at 7 AM, right after it is set.

The code below should select a random time between 1:00 AM and 3:59 AM to set/execute the alarm for the next calendar day and then the logic circles back around to set itself again after execution. The alarm will execute repeatedly, forever.

    int randomHour = new Random().nextInt((3 - 1) + 1) + 1;
    int randomMinute = new Random().nextInt((59 - 1) + 1) + 1;

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, randomHour);
    calendar.set(Calendar.MINUTE, randomMinute);
    calendar.set(Calendar.SECOND, 0);
    calendar.add(Calendar.DAY_OF_MONTH, 1);

    alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

Questions:

  1. At what point does Android stop executing alarms in the past?

  2. Is there any way to stop this?


Solution

  • "This is obviously meant for the next time" Does not work for computers, they will do exactly what you tell them to do.

    calendar.getTimeInMillis() returns the number of milliseconds since January 1, 1970 at 00:00:00 GMT. You need to specify not just the time but also the date that you want the alarm to go off. Instead you are always calling calendar.add(Calendar.DAY_OF_MONTH, 1); (the first day of the current month)