覆盖意图额外

我使用下面的代码创建通知(Kotlin)

val builder = NotificationCompat.Builder(ctx) ........ .setContentIntent(PendingIntent.getActivity(ctx, 891, ctx.newIntent() .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)并选择用户。 然后我按回来,从第二个用户发送另一个通知,点击它,意图仍然包含以前的用户ID并选择它(通过断点检查)。

我知道,这是因为FLAG_ACTIVITY_REORDER_TO_FRONT ,但我必须只保留MainActivity一个实例。

您可能遇到的问题是您没有生成唯一的PendingIntent 。 如果您针对不同的用户提供了2个通知,那么他们都将使用相同的PendingIntent ,因此您将在两者中看到相同的id

要创建独特的PendingIntent ,请更改:

  .setContentIntent(PendingIntent.getActivity(ctx, 891, ctx.newIntent() .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() .putExtra("id", member.id) .addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT), u)) 

你实际上需要给定的代码来使每个通知都是唯一的

 notificationManager.notify( (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE) /* ID of notification */, notificationBuilder.build()); 

如果你已经这样做,然后尝试下面给出的代码

 Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);