Home > database >  Why is an extra parameter sent only from a last notification to an activity?
Why is an extra parameter sent only from a last notification to an activity?

Time:06-05

everybody!

I am sending two local push notifications with different content texts. When clicking on each push, I expect that a certain activity (RecallActivity) will open with the text corresponding to the content text of the clicked notification. But I always get extra data from last notification, even if I click on the first one. I can't understand why.

Code from my service that creates the Notification:

override fun doWork(): Result {

    val word = inputData.getString("WORD")

    val intent = Intent(applicationContext, RecallActivity::class.java).apply {
        flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        this.putExtra("word", word)
    }

    val pendingIntent: PendingIntent? = TaskStackBuilder.create(applicationContext).run {
        addNextIntent(intent)
        getPendingIntent(0,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
    }

    val builder = NotificationCompat.Builder(context, "CHANNEL_ID")
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("Scheduled notification")
        .setContentText(word)
        .setContentIntent(pendingIntent)
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setAutoCancel(true)

    with(NotificationManagerCompat.from(context)) {
        notify(nextInt(), builder.build())
    }

    return Result.success()
}

Code from my Activity that tries to fetch the extra parameter from the notification:

class RecallActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_recall)

        wordTextView.text = intent.getStringExtra("word")
    }
}

Please, help :)

CodePudding user response:

    val pendingIntent: PendingIntent? = TaskStackBuilder.create(applicationContext).run {
        addNextIntent(intent)
        getPendingIntent(0,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
    }

Do not always use 0. Use a different requestCode value for each distinct PendingIntent.

I am sending two local push notifications with different content texts

Then you should be using two different requestCode values, such as 0 and 1.

  • Related