AlarmManager alarm is called immediately when trig

2019-03-07 04:43发布

问题:

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?

回答1:

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).



回答2:

Well, I ran into same problem and after studying I found that alarm will be run as soon when past time is set for the alarm. Source: Here is documentation of Alarm Manager - setRepeating()

So, I resolved the issue by checking if "Calendar time is in past from system time than I add a day"

Working code:

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, hour);
    calendar.set(Calendar.MINUTE, min);
    calendar.set(Calendar.SECOND, 0);
    alarmManager.cancel(pendingIntent);

    // Check if the Calendar time is in the past
    if (calendar.getTimeInMillis() < System.currentTimeMillis()) {
        Log.e("setAlarm","time is in past");
        calendar.add(Calendar.DAY_OF_YEAR, 1); // it will tell to run to next day
    }


    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, id, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager =  (AlarmManager)getSystemService(ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent); //Repeat every 24 hours