Search code examples
kotlinandroid-recyclerviewalarmmanagerandroid-contextandroid-pendingintent

Accessing AlarmManager from inside a RecyclerView Adapter


I'm making an Android alarm app in class. The alarms are displayed inside a recyclerview in the main activity, and I want them to be deleted when pressed. I am able to clear it from the alarm database I set up but I cannot access AlarmManager to cancel the alarm, and the PendingIntent's context also appears to be wrong.

 override fun onBindViewHolder(holder: RecyclerView.ViewHolder, index: Int) {
        val myViewHolder = holder as MyViewHolder
        val sdf = SimpleDateFormat("HH:mm EEEE")
        myViewHolder.tvAlarmTime.text = sdf.format(alarms[index].milliseconds)
        myViewHolder.tvAlarmFrequency.text = alarms[index].frequency
        myViewHolder.itemView.setOnClickListener {
            launch {
                withContext(Dispatchers.IO) {
                    val db = AlarmDatabase.getDatabase(myViewHolder.tvAlarmTime.context)
                    db.alarmDao().deleteTriggeredAlarm((alarms[index].id))
                }

            }
            val pi = PendingIntent.getBroadcast(this, (alarms[index].id).toInt(), Intent("alarmTask"), PendingIntent.FLAG_UPDATE_CURRENT)
            val alarmMgr = getSystemService(Context.ALARM_SERVICE) as AlarmManager
            alarmMgr.cancel(pi)

        }
    }

In the last 3 lines, the context has a type mismatch as this is a MyAdapter type - I'm not sure what I need to put here, something similar to MainActivity.context I would assume

getSystemService also shows a type inference error as a string, and I assume this is causing the type mismatch for context.ALARM_SERVICE as a string rather than the context.

What is the correct context and how can I access the AlarmManager inside the adapter?


Solution

  • You can use the context of your item view:

    val context = myViewHolder.itemView.context
    val pi = PendingIntent.getBroadcast(context, (alarms[index].id).toInt(), Intent("alarmTask"), PendingIntent.FLAG_UPDATE_CURRENT)
    val alarmMgr = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
    alarmMgr.cancel(pi)