'Why does my alarm not cancel after setting it with thesame request code

I set my alarm this way:

  val broadcastReceiverIntent = Intent(context, AlarmReceiver::class.java)
  broadcastReceiverIntent.putExtra(Constants.ALARM_INTENT_TIME, alarm.time)
  broadcastReceiverIntent.putExtra(Constants.ALARM_INTENT_ID, alarm.id)
  broadcastReceiverIntent.action = System.currentTimeMillis().toString()
  val newPendingIntent = PendingIntent.getBroadcast(
        context,
        alarm.id?:0,
        broadcastReceiverIntent,
        PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
  )
 //schedule alarm
 val alarmClockInfo = AlarmManager.AlarmClockInfo(calendar.timeInMillis, null)
 alarmManager.setAlarmClock(alarmClockInfo, newPendingIntent)

Then I cancel this way:

val broadcastReceiverIntent = Intent(context, AlarmReceiver::class.java)
val newPendingIntent = PendingIntent.getBroadcast(
        context,
        alarm.id?:0,
        broadcastReceiverIntent,
        PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
    )

alarmManager.cancel(newPendingIntent)

The alarm still fires off, even when I cancel it. The request code I used to set the alarm is thesame as the one I am using to cancel it.

What could be the cause?



Solution 1:[1]

The problem was from:

 broadcastReceiverIntent.action = System.currentTimeMillis().toString()

when setting that alarm.

It appears that that same action is required to cancel the alarm.

Removing that line solved the problem.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ouflak