I'm making and Android app that sends notifications with actions several times a day, the problem is that at this moment doesn't matter which action the user clicks it always sends the first intent to the broadcast receiver.
My code:
fun sendNotification(title: String, content: String, tomaID: Int){
val takeShotIntent = Intent(context, TreatmentBroadcastReceiver::class.java).apply {
putExtra("TomaID", tomaID)
putExtra("AcctionToma", 0)
}
val takeShotPendingIntent = PendingIntent.getBroadcast(context, NOTIFICACION_ID, takeShotIntent, PendingIntent.FLAG_ONE_SHOT)
val skipShotIntent = Intent(context, TreatmentBroadcastReceiver::class.java).apply {
putExtra("TomaID", tomaID)
putExtra("AcctionToma", 1)
}
val skipShotPendingIntent = PendingIntent.getBroadcast(context, NOTIFICACION_ID, skipShotIntent, PendingIntent.FLAG_ONE_SHOT)
val postPoneShotIntent = Intent(context, TreatmentBroadcastReceiver::class.java).apply {
putExtra("TomaID", tomaID)
putExtra("AcctionToma", 2)
}
val postPoneShotPendingIntent = PendingIntent.getBroadcast(context, NOTIFICACION_ID, postPoneShotIntent, PendingIntent.FLAG_ONE_SHOT)
val notifyBuilder = getNotificationBuilder(title,content)
notifyBuilder.addAction(R.drawable.ic_capsula, context.getString(R.string.tomar), takeShotPendingIntent)
notifyBuilder.addAction(R.drawable.ic_capsula,context.getString(R.string.saltar), skipShotPendingIntent)
notifyBuilder.addAction(R.drawable.ic_capsula,context.getString(R.string.posponer), postPoneShotPendingIntent)
mNotifyManager = context.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
mNotifyManager.notify(NOTIFICACION_ID, notifyBuilder.build())
}
And the broadcast receiver class:
class TreatmentBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val idToma = intent.getIntExtra("TomaID", -1)
val acctionToma = intent.getIntExtra("AcctionToma", -1)
Log.d("EstasReciviendo", idToma.toString() + " " + acctionToma)
}
}
I need to send an ID and a number that represents what the app should do based on the user selection. The ID is sent without problems but as a I mention above the "AccionToma" is always 0 in the onReceive method no matter which action is tapped.
My logcat output:
2019-07-21 17:09:10.993 20286-20286/com.kps.spart.moskimedicationreminder D/EstasReciviendo: 1049 0
So, How can I differentiate which action has been clicked?
Use different unique values, instead of NOTIFICACION_ID
, for your three PendingIntent.getBroadcast()
calls.
As it stands, your second PendingIntent.getBroadcast()
call replaces the first one, and the third PendingIntent.getBroadcast()
call replaces the second.