无法使用24 API上的AlarmManager.cancel()取消警报

时间:2019-06-30 00:12:41

标签: android kotlin alarmmanager

有2种方法:

  1. 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.
*/
  1. 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有问题吗?我想念什么?

1 个答案:

答案 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)