为什么 PendingIntent 会触发?
Why is the PendingIntent firing?
我正在尝试在特定日期发送通知。我的方法 "setNextNotification" 使用 AlarmManager 安排下一个通知。
Java时间API用于查看当前日期。如果它等于星期二,则将一天添加到 ZonedDateTime 并为该日期设置警报。这至少是我想要完成的。
今天是星期二,无论如何都会触发通知。
我错过了什么?
private static void setNextNotification(Context context) {
LocalDateTime ldt = LocalDateTime.now();
ZonedDateTime zdt = ldt.atZone(ZoneId.of("Europe/Stockholm"));
DayOfWeek dayOfWeek = zdt.getDayOfWeek();
Intent intent = new Intent(context, ReminderReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
if(dayOfWeek.getValue() == 2){
zdt.plusDays(1);
alarmManager.set(AlarmManager.RTC_WAKEUP, zdt.toInstant().toEpochMilli(), alarmIntent);
}
}
ZonedDateTime
是带有时区的日期时间的不可变表示。因此,即使您调用了 plusDays(1)
,ZoneDateTime
对象中的原始时间仍保持不变。
plusDays()
returns 具有修改值的新 ZonedDateTime
对象。在您的代码中,您没有在任何地方分配。所以你需要更换
zdt.plusDays(1);
与 zdt = zdt.plusDays(1);
以便它按您的预期工作。
修改后的代码:
private static void setNextNotification(Context context) {
LocalDateTime ldt = LocalDateTime.now();
ZonedDateTime zdt = ldt.atZone(ZoneId.of("Europe/Stockholm"));
DayOfWeek dayOfWeek = zdt.getDayOfWeek();
Intent intent = new Intent(context, ReminderReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
if(dayOfWeek.getValue() == 2){
zdt = zdt.plusDays(1);
alarmManager.set(AlarmManager.RTC_WAKEUP, zdt.toInstant().toEpochMilli(), alarmIntent);
}
}
我正在尝试在特定日期发送通知。我的方法 "setNextNotification" 使用 AlarmManager 安排下一个通知。
Java时间API用于查看当前日期。如果它等于星期二,则将一天添加到 ZonedDateTime 并为该日期设置警报。这至少是我想要完成的。
今天是星期二,无论如何都会触发通知。
我错过了什么?
private static void setNextNotification(Context context) {
LocalDateTime ldt = LocalDateTime.now();
ZonedDateTime zdt = ldt.atZone(ZoneId.of("Europe/Stockholm"));
DayOfWeek dayOfWeek = zdt.getDayOfWeek();
Intent intent = new Intent(context, ReminderReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
if(dayOfWeek.getValue() == 2){
zdt.plusDays(1);
alarmManager.set(AlarmManager.RTC_WAKEUP, zdt.toInstant().toEpochMilli(), alarmIntent);
}
}
ZonedDateTime
是带有时区的日期时间的不可变表示。因此,即使您调用了 plusDays(1)
,ZoneDateTime
对象中的原始时间仍保持不变。
plusDays()
returns 具有修改值的新 ZonedDateTime
对象。在您的代码中,您没有在任何地方分配。所以你需要更换
zdt.plusDays(1);
与 zdt = zdt.plusDays(1);
以便它按您的预期工作。
修改后的代码:
private static void setNextNotification(Context context) {
LocalDateTime ldt = LocalDateTime.now();
ZonedDateTime zdt = ldt.atZone(ZoneId.of("Europe/Stockholm"));
DayOfWeek dayOfWeek = zdt.getDayOfWeek();
Intent intent = new Intent(context, ReminderReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
if(dayOfWeek.getValue() == 2){
zdt = zdt.plusDays(1);
alarmManager.set(AlarmManager.RTC_WAKEUP, zdt.toInstant().toEpochMilli(), alarmIntent);
}
}