Search code examples
androidalarmmanager

Alarm manager starts immediately instead of after 15 minutes from now


I wrote the below code:

var alarmMgr: AlarmManager? = null
lateinit var alarmIntent: PendingIntent

class MainActivity : AppCompatActivity() {
alarmMgr = this.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmIntent = Intent(this, MyAlarm::class.java).let { intent ->
                PendingIntent.getBroadcast(this, 0, intent, 0)
            }
alarmMgr?.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME, AlarmManager.INTERVAL_FIFTEEN_MINUTES, alarmIntent)
}

With MyAlarm class as:

class MyAlarm : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        Toast.makeText(context, "Alarm Triggered", Toast.LENGTH_SHORT).show()
    }
}

My intention is to get the alert run after 15 minutes, but what is happening in real, is I'm getting the toast immediately upon the app startup, what mistake did I made, and how to fix it?


Solution

  • The second parameter to setExactAndAllowWhileIdle() is the time when the alarm should occur, expressed in the timebase of the first parameter.

    Your first parameter is ELAPSED_REALTIME, so the second parameter needs to be SystemClock.elapsedRealtime() plus some amount, to schedule the alarm for that amount of time in the future.

    Right now, you just have INTERVAL_FIFTEEN_MINUTES as the second parameter. The value of that constant happens to be 15 minutes in milliseconds. However, that will schedule the alarm to go off 15 minutes from whenever your phone last rebooted, which probably is a time in the past.

    So, replace:

    alarmMgr?.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME,
      AlarmManager.INTERVAL_FIFTEEN_MINUTES, alarmIntent)
    

    with:

    alarmMgr?.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME,
      SystemClock.elapsedRealtime()+AlarmManager.INTERVAL_FIFTEEN_MINUTES, alarmIntent)