我有一个简单的代码设置,可以在特定时间间隔通知用户。虽然 getDate 方法返回的是 future 时间,但它仍然会立即触发!
Intent notificationIntent = new Intent(act, NotificationPublisher.class);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, idTT);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, notification);
PendingIntent pendingIntent = PendingIntent.getBroadcast(act, idTT, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) act.getSystemService(Context.ALARM_SERVICE);
Date dd = getDate(dateTT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.MONTH, dd.getMonth());
calendar.set(Calendar.YEAR, dd.getYear());
calendar.set(Calendar.DAY_OF_MONTH, dd.getDay());
calendar.set(Calendar.HOUR_OF_DAY, dd.getHours());
calendar.set(Calendar.MINUTE, dd.getMinutes());
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,calendar.getTimeInMillis(), pendingIntent);
Calendar 对象的固定日期 - 由于 date.getMonth() 和其他方法已被弃用,我不得不创建一个日历对象,然后获取 Year
从日期创建一个日历对象-
Calendar calTemp = Calendar.getInstance();
calTemp.setTime(ddTT);
获取月、年等字段-
calendar.set(Calendar.MONTH, calTemp.get(Calendar.MONTH));
calendar.set(Calendar.YEAR, calTemp.get(Calendar.YEAR));
calendar.set(Calendar.DATE, calTemp.get(Calendar.DATE));
calendar.set(Calendar.HOUR_OF_DAY, calTemp.get(Calendar.HOUR_OF_DAY));
calendar.set(Calendar.MINUTE, calTemp.get(Calendar.MINUTE));
getDate方法j只是将日期转换为系统时区
private Date getDate(String dateString) {
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm z");
//formatter.setTimeZone(TimeZone.getTimeZone("EDT"));
Date value = null;
try {
value = formatter.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy HH:mm");
dateFormatter.setTimeZone(TimeZone.getDefault());
String dt = dateFormatter.format(value);
try {
value = dateFormatter.parse(dt);
} catch (ParseException e) {
e.printStackTrace();
}
return value;
}
我可能在这里遗漏了一些明显的东西,但我不知道它是什么!
最佳答案
您应该使用 RTC_WAKEUP
而不是 ELAPSED_REALTIME_WAKEUP
。
示例:
int trigger_time= System.currentTimeMillis() + 30 * 1000; //thirtySecondsFromNow
if(Build.VERSION.SDK_INT >= 19) {
am.setExact(AlarmManager.RTC_WAKEUP, trigger_time,
pendingIntent);
} else {
am.set(AlarmManager.RTC_WAKEUP, trigger_time,
pendingIntent);
}
解释:
1) ELAPSED_REALTIME 根据设备启动后的时间量触发挂起的 Intent,但不唤醒设备。耗时包括设备处于休眠状态的任何时间。
2) ELAPSED_REALTIME_WAKEUP 在设备启动后经过指定的时间长度后唤醒设备并触发挂起的 Intent 。
3) RTC 在指定时间触发未决 Intent 但不唤醒设备。
4) RTC_WAKEUP 唤醒设备以在指定时间触发未决 Intent 。
关于android - 警报管理器无法通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33139392/