Android AlarmManager: Multiple Alarm With Arguments/Parameters (Pass Value)

May 9, 2019

NOTE: If you are new to AlarmManager, you might want to refer to Android AlarmManager: Setup Repeating Alarm (Daily Reminder).

For multiple alarms, use different requestCode for PendingIntent.getBroadcast.

For parameters passing, use Intent.putExtra.

class ReminderReceiver : BroadcastReceiver() {

    companion object {
        private const val PARAM_NAME = "name"
        private const val REQUEST_TIMER1 = 1
        private const val REQUEST_TIMER2 = 2

        fun getIntent(context: Context, requestCode: Int, name: String? = null): PendingIntent? {
            val intent = Intent(context, ReminderReceiver::class.java)
            intent.putExtra(PARAM_NAME, name)
            return PendingIntent.getBroadcast(context, requestCode, intent, PendingIntent.FLAG_CANCEL_CURRENT)
        }

        fun startAlarm1(context: Context) {
            Timber.d("startAlarm1")
            val pendingIntent = getIntent(context, REQUEST_TIMER1, "Timer 01")
            val alarm = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager

            // start immediately, the once every 2 minutes
            val intervalMillis = 2L * 60L * 1_000L
            val triggerAtMillis = System.currentTimeMillis()
            alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, triggerAtMillis, intervalMillis, pendingIntent)
        }

        fun startAlarm2(context: Context) {
            Timber.d("startAlarm2")
            val pendingIntent = getIntent(context, REQUEST_TIMER2, "Timer 02")
            val alarm = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager

            // start once every 1 minute
            val intervalMillis = 1L * 60L * 1_000L
            val triggerAtMillis = System.currentTimeMillis() + intervalMillis

            alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, triggerAtMillis, intervalMillis, pendingIntent)
        }

        fun cancelAlarm(context: Context) {
            Timber.d("stopAlarm1+2")

            val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager

            getIntent(context, REQUEST_TIMER1).apply {
                alarmManager.cancel(this)
            }

            getIntent(context, REQUEST_TIMER2).apply {
                alarmManager.cancel(this)
            }
        }
    }

    override fun onReceive(context: Context, intent: Intent) {
        val name = intent.getStringExtra(PARAM_NAME)
        Timber.d("onReceive, name=$name")
        Toast.makeText(context, name, Toast.LENGTH_LONG).show()
    }
}

Usage

ReminderReceiver.startAlarm1(context)
ReminderReceiver.startAlarm2(context)
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.