I'm creating notification using following code (Kotlin)
val builder = NotificationCompat.Builder(ctx)
........
.setContentIntent(PendingIntent.getActivity(ctx, 891, ctx.newIntent<MainActivity>()
.putExtra("id", member.id)
.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT), 0))
So when notification is tapped MainActivity
will select user, from which notification arrived.
override fun onNewIntent(intent: Intent?) {
val id = intent?.getStringExtra("id") ?: return
selectUser(extra)
}
I'm sending 2 notifications from 2 different users. After click on first notification it works correct (id==_User1UUID) and selects user. Then I press back, send another notification from second user, tap on it and intent still contains previous user id and selects it (checked through breakpoint).
I know, it's because FLAG_ACTIVITY_REORDER_TO_FRONT
, but I must keep only one instance of MainActivity
.
The problem you are probably having is that you aren't generating unique PendingIntent
s. If you had 2 Notifications for different users, they would both be using the same PendingIntent
and you would therefore see the same id
extra in both.
To create unique PendingIntent
s, change this:
.setContentIntent(PendingIntent.getActivity(ctx, 891, ctx.newIntent<MainActivity>()
.putExtra("id", member.id)
.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT), 0))
to this:
int randomNumber = ... // Use some random number here, or use your "id" if your "id" can be converted to an integer here.
// This random number needs to be unique for each Notification you create.
.setContentIntent(PendingIntent.getActivity(ctx, randomNumber, ctx.newIntent<MainActivity>()
.putExtra("id", member.id)
.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT), u))