我正在尝试在特定日期发送通知。我的方法“setNextNotification”使用 AlarmManager 安排下一个通知。
Java Time 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()
返回一个带有修改值的新 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);
}
}
关于java - 为什么 PendingIntent 会被触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61482929/