我正在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)
}
答案 0 :(得分:1)
取消闹钟后,您需要取消PendingIntent
。之后
alarmMgr.cancel(alarmIntent)
添加
alarmIntent.cancel()