您应该将代码更改为:
PendingIntent pi=PendingIntent.getBroadcast(context,0,myIntent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calSet.getTimeInMillis(), pi);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, calSet.getTimeInMillis(), pi);
}
@Edit
上面的代码将用于设置准确的时间。但本节将解释有关警报管理器的重复。
对于 19 以下的 api,我们使用AlarmManager.setRepeating()
将定期在指定时间准确触发警报。但是从 19 和更高版本开始,此方法将不再起作用,并且没有任何 api 支持此行为。我认为这种 api 更改使开发人员在创建计时器时更加仔细地思考。因为定时定时触发会消耗大量电池电量。
如果你愿意,你必须自己做。首先,您设置AlarmManager.setExact()
,当警报触发时,您将再次手动触发警报
这是代码:
PendingIntent pi=PendingIntent.getBroadcast(context,0,myIntent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
alarmManager. setExact(AlarmManager.RTC_WAKEUP, calSet.getTimeInMillis(), pi);
} else {
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calSet.getTimeInMillis(), pi);
}
在您放置句柄代码的意图中,您应该检查 android api >= 19,应用程序将为下一个事件创建新警报。
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
doSomething();
// calculate time for next event
Calendar nextEvent = calcNextEvent();
// and set alarm again
alarmManager. setExact(AlarmManager.RTC_WAKEUP, nextEvent.getTimeInMillis(), pi);
} else {
doSomething();
}
我认为这是android api设计中的问题。旧代码应该适用于新版本。无论如何,这个新的 api 设计让开发人员的一切都变得更清晰,对系统更好(节省电池)。当然,当你使用新的 api 时 :)
希望这有帮助:)