我正在使用以下代码 (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))
因此,当点击通知时,MainActivity
将选择用户,通知来自该用户。
override fun onNewIntent(intent: Intent?) {
val id = intent?.getStringExtra("id") ?: return
selectUser(extra)
}
我从 2 个不同的用户发送 2 个通知。单击第一个通知后,它可以正常工作 (id==_User1UUID) 并选择用户。然后我按回键,从第二个用户发送另一个通知,点击它并且 Intent 仍然包含以前的用户 ID 并选择它(通过断点检查)。
我知道,这是因为 FLAG_ACTIVITY_REORDER_TO_FRONT
,但我必须只保留一个 MainActivity
实例。
最佳答案
您可能遇到的问题是您没有生成唯一的 PendingIntent
。如果您有 2 个针对不同用户的通知,他们都将使用相同的 PendingIntent
,因此您会在两者中看到相同的 id
extra。
要创建唯一的 PendingIntent
,请更改:
.setContentIntent(PendingIntent.getActivity(ctx, 891, ctx.newIntent<MainActivity>()
.putExtra("id", member.id)
.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT), 0))
为此:
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))
关于android - 覆盖 Intent 额外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41299808/