简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM