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

后端 未结 2 1840
旧巷少年郎
旧巷少年郎 2021-01-29 08:01

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 e

相关标签:
2条回答
  • 2021-01-29 08:27

    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
    
    0 讨论(0)
  • 2021-01-29 08:35

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

    0 讨论(0)
提交回复
热议问题