Search code examples
androidalarmmanager

AlarmManager alarm is called immediately when trigger time is in the past


Below is the code I am using to create alarms when data is pulled from external API. If the time set is in the past, the alarm goes off as soon as it is set(2 second gap). For example if I set the alarm for 8:00 AM, 10th April at 10:00 AM on 11th April(Past time). It starts the alarm as soon as it is set.

public static final int ALARM_REQUEST_CODE = 1001;
public static AlarmManager alarmManager = (AlarmManager) EHCApplication.getInstance().getApplicationContext().getSystemService(Context.ALARM_SERVICE);
public static Intent alarmIntent = new Intent(EHCApplication.getInstance().getApplicationContext(), AlarmReceiver.class);
public static PendingIntent pendingIntent = PendingIntent.getBroadcast(EHCApplication.getInstance().getApplicationContext(), ALARM_REQUEST_CODE, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);



public static void setAlarm(Reminder rm) {
    for (ScheduledTime time : rm.getScheduledTime()) {
        Bundle bundle = new Bundle();
        bundle.putParcelable(Constants.ARGS_SELECTED_MEDICINE, medicine);
        alarmIntent.putExtras(bundle);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time.getTimeInMilliseconds(), AlarmManager.INTERVAL_DAY, pendingIntent);
    }
}

I am expecting the alarm to go off from next time it hit the time. Where am I making mistake?


Solution

  • This is the expected behavior.

    From the documentation of setRepeating() (and other AlarmManager set methods):

    If the stated trigger time is in the past, the alarm will be triggered immediately

    If you would like to prevent that happening, then simply do not set alarms with a past trigger time (e.g. check against System.currentTimeMillis() when setting the alarm).