androidalarmmanagerandroid-pendingintentrepeatingalarm

Alarm Pending intent returns null when app started again after killing from background


I am trying to check if a repeating alarm already exist. I am testing in MIUI 11 (OS v8.1) device, where i have set an alarm then removed the application from background. If i again opens the app a new alarm is created again

Here is my code to set a repeating alarm

   private fun startAlarm() {
    val CUSTOM_INTENT = "com.test.intent.action.ALARM"
    val intent = Intent(this, AlarmHelper::class.java)
    intent.action = CUSTOM_INTENT
    val pendingIntent: PendingIntent =
        getBroadcast(this, 101, intent, PendingIntent.FLAG_UPDATE_CURRENT)
    val alarmManager = getSystemService(ALARM_SERVICE) as AlarmManager

    alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
        System.currentTimeMillis()+60*60*1000, pendingIntent)
}

This checks if an alarm already exist then i will not create a new one.

 private fun isAlarmExist() :Boolean =
        PendingIntent.getBroadcast(this, 101,
               Intent(this, AlarmHelper::class.java),
               PendingIntent.FLAG_NO_CREATE) != null

Already tried this

private fun isAlarmExist() :Boolean =
        PendingIntent.getBroadcast(this, 101,
               Intent("com.example.dozemodepoc.MY_UNIQUE_ACTION"),
               PendingIntent.FLAG_NO_CREATE) != null

// this didnot work either

Already gone through How to check if AlarmManager already has an alarm set?

When force stopped the application and started the app again, new instance is again created. Any kind of help will be highly appreciated!!.


Solution

  • I did a silly mistake in my isAlarmExist()

      private fun isAlarmExist() :Boolean {
    
        val CUSTOM_INTENT = "com.test.intent.action.ALARM"
        val intent = Intent(this@MainActivity, AlarmHelper::class.java)
        intent.action = CUSTOM_INTENT
    
        return getBroadcast(this@MainActivity, 101, intent, PendingIntent.FLAG_NO_CREATE)!=null
    }
    

    This pending intent should be exact of the pending intent which was created when alarm was set up.