简体   繁体   中英

PendingIntent fires when the alarm time is a multiple of 1 hour away from real time - Android

I am creating an Alarm clock app. I can set PendingIntent 's, cancel them, and receive them using my BroadcastReceiver when the time that I set using AlarmManager is reached. I discovered a recent problem however.

Previously, I have been able to set an alarm for any time in the future, and the BroadcastReceiver wouldn't "receive" the PendingIntent until that time was reached. I guess I never covered the scenario where the alarm to be set is exactly 1 or more (integers only) hours away. For example, the current time is 11:54, and I set an alarm for 12:54, or 1:54, 2:54, etc. When I do this, the BroadcastReceiver receives the PendingIntent and performs the actions that I told it to do.

Why does this happen? When I change the minute to something different, it doesn't happen, only if the minute is the same the app behaves as if I set the alarm for the current time.

This is how I set the alarms:

public void scheduleAlarm(Context aContext) {
    AlarmManager am = (AlarmManager) aContext.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(aContext, MyBroadcastReceiver.class);

    String id = this.getId().replaceAll("[^0-9]+", "");      // this.getId returns a string such as "alarm1". We only need the "1".

    PendingIntent alarmIntent = PendingIntent.getBroadcast(aContext, Integer.parseInt(id), intent, 0);

    // "this" in this context is the Alarm object. So you can get the hour and minute from the timepicker used to set the alarm
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, this.getHour());
    calendar.set(Calendar.MINUTE, this.getMinute());

    long calendarTime = calendar.getTimeInMillis();
    am.setExact(AlarmManager.RTC_WAKEUP, calendarTime, alarmIntent);
}

I checked the time that the alarm is set for, and confirmed that they were not the present time so they should not go off. After trying to set multiple alarms and seeing that the problem was still happening, I uninstalled the app from my phone, and gave it a fresh install. Everything worked fine afterwards and is still functioning correctly.

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