0

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?

Ibccx
  • 105
  • 3
  • 11
  • the problem with request code . but what did you put as request code by alarm.id?:0 ? – Niaj Mahmud Mar 07 '22 at 07:57
  • The request code for creation is: val id = Random().nextInt(Integer.MAX_VALUE), which is the alarm id; So, for cancelling I just cancel using same id – Ibccx Mar 07 '22 at 14:36
  • you can try with static number first .. i think the problem you are facing is for request code . – Niaj Mahmud Mar 07 '22 at 15:30
  • Its not the request code, I just tried with a static number. – Ibccx Mar 07 '22 at 16:46
  • if you want to use alarm manager and want to push notification by broadcaster receiver you must have to send a request code by pending intent for every alarm .. with out request code you cant access.. so first for test purpose you can try using request code as 1 or 2 then you can set random number for dynamic purpose then put the number in database then you can cancel the alarm by reading data from database . https://stackoverflow.com/questions/34699662/how-does-alarmmanager-alarmclockinfos-pendingintent-work – Niaj Mahmud Mar 07 '22 at 17:21
  • I did so, the problem was not from the request code. See my answer. – Ibccx Mar 07 '22 at 17:29

1 Answers1

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.

ouflak
  • 2,458
  • 10
  • 44
  • 49
Ibccx
  • 105
  • 3
  • 11