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

和自甴很熟 提交于 2019-12-02 14:53:19

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!