2

I'm writing Android application in Kotlin. In some situations I'm using there AlarmManager to schedule task every 1 minute to do some action and in some condition cancel future calls.

Before setting up alarm I'm checking if it was already scheduled by using flag PendingIntent.FLAG_NO_CREATE so I wouldn't do it few times. At first it's working fine and there is in log

Should set up repeating alarm: true

But when I cancel my alarm and then I try do schedule it again it always return false. I would expect that after cancelling it I should again get true there which would indicate that there's no scheduled alarm for this PendingIntent operation. Is there something wrong with my code or with the way I think? :)

Here's my 2 methods used to set up and cancel alarm.

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)
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
user3626048
  • 706
  • 4
  • 19
  • 52

1 Answers1

3

After canceling the alarm you need to cancel the PendingIntent. After

alarmMgr.cancel(alarmIntent)

add

alarmIntent.cancel()
David Wasser
  • 93,459
  • 16
  • 209
  • 274