How to stop Android AlarmManager when there is a manual system time change?

岁酱吖の 提交于 2019-12-13 03:34:09

问题


Here is an extended example of the problem. It is 1:30AM. Alarm is set for later today, at 10AM. I change my phones time to 1159PM yesterday. Alarm Manager instantly triggers, at the wrong time.

How do I stop the AlarmManager from ringing if the time is in the past?

If however, I change the time forward, nothing happens.

I do not want this to happen with my app, as it does not happen with other Alarm apps. Is there a way to make sure that the Alarm manager only rings at the exact minute it is set (if not skip it)?

Here is my Alarm Manager code.

        Calendar alarmCal = closestAlarm.toCalendar();

        Intent alarmIntent = new Intent(this, ActiveAlarmService.class);
        alarmIntent.putExtra("alarm", closest);

        pendingAlarm = PendingIntent.getService(AlarmService.this, 0, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);

        alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, alarmCal.getTimeInMillis(), pendingAlarm);

I have tried using a BroadcasetReceiver to catch the Time/Date change events, but there is too much lag between the broadcast, and the AlarmManager firing because it is set in the past.


回答1:


I have found the solution. It feels odd, but it is solid.

Here is what I was using originally.

alarmManager.set(AlarmManager.RTC_WAKEUP, 
    alarmTimeCalendar.getTimeInMillis(), pendingAlarmIntent);

This was the solution.

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarmTimeCalendar.getTimeInMillis(),
    AlarmManager.INTERVAL_DAY, pendingAlarmIntent);

You will have to manage and cancel this AlarmManager as if it was the first method. If you forget, your alarm will ring when it should not.



来源:https://stackoverflow.com/questions/35932969/how-to-stop-android-alarmmanager-when-there-is-a-manual-system-time-change

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