当闹钟时间与实际时间相差 1 小时的倍数时,将触发 PendingIntent - Android
PendingIntent fires when the alarm time is a multiple of 1 hour away from real time - Android
我正在创建一个闹钟应用程序。我可以设置 PendingIntent
,取消它们,并在到达我使用 AlarmManager
设置的时间时使用我的 BroadcastReceiver
接收它们。不过我最近发现了一个问题。
以前,我已经能够为将来的任何时间设置闹钟,并且 BroadcastReceiver 不会 "receive" PendingIntent 直到到达那个时间。我想我从来没有涉及过要设置的警报恰好在 1 小时或更多(仅整数)小时后的情况。比如现在时间是11:54,我设置闹钟12:54,或者1:54,2:54等。当我这样做的时候,BroadcastReceiver收到PendingIntent并执行我告诉它要做的动作。
为什么会这样?当我将分钟更改为不同的内容时,它不会发生,只有当分钟相同时,应用程序的行为就像我为当前时间设置了闹钟一样。
我是这样设置闹钟的:
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);
}
我查看了闹钟设置的时间,确认不是现在时间,应该不会响。在尝试设置多个闹钟并发现问题仍然存在后,我从 phone 中卸载了该应用程序并重新安装。之后一切正常,并且仍在正常运行。
我正在创建一个闹钟应用程序。我可以设置 PendingIntent
,取消它们,并在到达我使用 AlarmManager
设置的时间时使用我的 BroadcastReceiver
接收它们。不过我最近发现了一个问题。
以前,我已经能够为将来的任何时间设置闹钟,并且 BroadcastReceiver 不会 "receive" PendingIntent 直到到达那个时间。我想我从来没有涉及过要设置的警报恰好在 1 小时或更多(仅整数)小时后的情况。比如现在时间是11:54,我设置闹钟12:54,或者1:54,2:54等。当我这样做的时候,BroadcastReceiver收到PendingIntent并执行我告诉它要做的动作。
为什么会这样?当我将分钟更改为不同的内容时,它不会发生,只有当分钟相同时,应用程序的行为就像我为当前时间设置了闹钟一样。
我是这样设置闹钟的:
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);
}
我查看了闹钟设置的时间,确认不是现在时间,应该不会响。在尝试设置多个闹钟并发现问题仍然存在后,我从 phone 中卸载了该应用程序并重新安装。之后一切正常,并且仍在正常运行。