I'm building a "Cancel alarm" button, and a "check alarm" button.
The "Cancel Alarm" button works. I am sure of it.
but when I press the "Check Alarm" button, it still return true.
Some context: I want `true` to mean "Your alarm still exists, and WILL fire at the set time."
Here is the backend code:
fun scheduleChime(context: Context) {
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val pendingIntent = createIntent(context, "create")
val triggerTime = getTriggerTime()
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
triggerTime,
pendingIntent
)
}
fun cancelChime(context: Context) {
val pendingIntent = createIntent(context, "cancel")
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmManager.cancel(pendingIntent)
}
fun checkChime(context: Context): Boolean {
val intent = Intent(context, ChimeReceiver::class.java)
intent.setAction("ChimeScheduler.ALARM_BROADCAST")
return (PendingIntent.getBroadcast(context, 0, intent, (PendingIntent.FLAG_NO_CREATE or PendingIntent.FLAG_IMMUTABLE)) != null)
}
fun createIntent(context: Context, type: String) : PendingIntent {
val intent = Intent(context, ChimeReceiver::class.java)
intent.setAction("ChimeScheduler.ALARM_BROADCAST")
val pendingIntent = PendingIntent.getBroadcast(
context,
0,
intent,
if (type == "cancel") (PendingIntent.FLAG_NO_CREATE or PendingIntent.FLAG_IMMUTABLE) else if (type=="create") (PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_IMMUTABLE) else (PendingIntent.FLAG_NO_CREATE or PendingIntent.FLAG_IMMUTABLE)
)
return pendingIntent
}
And here is the button code:
@Composable
fun TestChime() {
val context = LocalContext.current
Button (
onClick = {
ChimeScheduler.checkChime(context)
Toast.makeText(context, ChimeScheduler.checkChime(context).toString(), Toast.LENGTH_LONG).show()
}
){
Text("Check Alarm")
}
}
@Composable
fun RunDeleteChime() {
val context = LocalContext.current
Button (
onClick = {
ChimeScheduler.cancelChime(context)
Toast.makeText(context, "Done", Toast.LENGTH_LONG).show()
}
) {
Text("Cancel Alarm")
}
}
OK, found the answer.
Canceling the alarm, only is just fine IF you don't need to know if your alarm is active.
But if you want to check if it is, then my function will always return true. (alarm still exists)
You need to cancel BOTH the upcoming alarm, and the pendingIntent you created to cancel the alarm, in order for checkChime() to return false (alarm no longer exists)
The code in my question is all right, except 1 line is missing in function cancelChime()
see line labeled <-- HERE
fun cancelChime(context: Context) {
val pendingIntent = createIntent(context, "cancel")
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmManager.cancel(pendingIntent)
pendingIntent..cancel() <-- HERE
}
I ran it this way, and it worked perfectly.