取消警报后,AlarmManager PendingIntent.FLAG_NO_CREATE返回非空

时间:2018-05-28 16:17:29

标签: android android-pendingintent android-alarms

我正在Android中撰写Kotlin个应用程序。在某些情况下,我会使用AlarmManager每1分钟安排一次任务来执行某些操作,并在某些情况下取消将来的呼叫。

在设置闹钟之前,我会使用标记PendingIntent.FLAG_NO_CREATE检查是否已经安排好了,所以我不会做几次。起初它工作正常,并且有日志

Should set up repeating alarm: true

但是当我取消闹钟然后我尝试再次安排它时,它总是返回false。我希望在取消之后我再次得到true,这表明此PendingIntent操作没有预定的警报。我的代码或我想的方式有问题吗? :)

这是我用来设置和取消闹钟的两种方法。

fun setupAlarm(context: Context) {
    val alarmMgr = context.applicationContext.getSystemService(Context.ALARM_SERVICE) as AlarmManager
    val intent = Intent(context.applicationContext, ScheduledCheckReceiver::class.java)
    val existingIntent = PendingIntent.getBroadcast(context.applicationContext, 100, intent, PendingIntent.FLAG_NO_CREATE)
    Log.d("AlarmUtil","Should set up repeating alarm: " + (existingIntent == null))
    if(existingIntent == null) {
        val alarmIntent = PendingIntent.getBroadcast(context.applicationContext, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT)
        Log.d("AlarmUtil", "Setting up alarm to " + Date(System.currentTimeMillis() + 30 * 1000))
        alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 30 * 1000, 60 * 1000, alarmIntent)
    }
}

fun cancelAlarm(context: Context) {
    Log.d("AlarmUtil", "Cancel alert called")
    val alarmMgr = context.applicationContext.getSystemService(Context.ALARM_SERVICE) as AlarmManager
    val intent = Intent(context.applicationContext, ScheduledCheckReceiver::class.java)
    val alarmIntent = PendingIntent.getBroadcast(context.applicationContext, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT)
    alarmMgr.cancel(alarmIntent)
}

1 个答案:

答案 0 :(得分:1)

取消闹钟后,您需要取消PendingIntent。之后

alarmMgr.cancel(alarmIntent)

添加

alarmIntent.cancel()