有2种方法:
addAlarm()
val myIntent = Intent(context, AlarmReceiver::class.java)
if (SDK_INT > Build.VERSION_CODES.M) {
myIntent.action = "ADD_ALARM"
} else {
myIntent.putExtra("alarm", alarm)
}
val pendingIntent = PendingIntent.getBroadcast(context, 1, myIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
if (SDK_INT < Build.VERSION_CODES.M)
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent)
else
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent)
/*
if I try to cancel alarm after creating like this:
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmManager.cancel(pendingIntent)
it would work and alarm would be canceled. Seems like problem is
in pendingIntent.
*/
deleteAlarm()
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
var myIntent = Intent(context, AlarmReceiver::class.java)
//with flag FLAG_NO_CREATE return null
val pendingIntent = PendingIntent.getBroadcast(context, 1, myIntent, PendingIntent.FLAG_UPDATE_CURRENT)
alarmManager.cancel(pendingIntent)
一切都在api 23上运行良好,但在api 24上,警报不会取消。 intent.action
有问题吗?我想念什么?
答案 0 :(得分:0)
好吧,我通过添加intent.action
来解决此问题:
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
var myIntent = Intent(context, AlarmReceiver::class.java)
if (SDK_INT > Build.VERSION_CODES.M) {
myIntent.action = "ADD_ALARM"
}
val pendingIntent = PendingIntent.getBroadcast(context, 1, myIntent, PendingIntent.FLAG_UPDATE_CURRENT)
alarmManager.cancel(pendingIntent)