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

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)

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.