从多个通知启动活动会覆盖之前的意图

Ale*_*dro 5 notifications android android-intent android-pendingintent

public static void showNotification(Context ctx, int value1, String title, String message, int value2){

    NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);

    Intent notificationIntent = new Intent(ctx, ActivityMain.class);
    int not_id = Utils.randInt(1111, 9999);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    notificationIntent.putExtra("key_1", value1);
    notificationIntent.putExtra("key_2", value2);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(ctx.getApplicationContext());
    stackBuilder.addNextIntent(notificationIntent);
    PendingIntent notifPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    notificationManager.notify(not_id, createNotification(ctx, notifPendingIntent, title, message));
}
Run Code Online (Sandbox Code Playgroud)

这是我发送和显示notification. 我从服务发送这个。正如你所看到的,我发送了 2 个额外的值,目的是(key_1key_2);当我单击通知时,我应该打开活动并查看按键的value1和。value2

问题是:如果在我打开其中任何一个之前收到另一个通知,value1并且value2该通知被覆盖。例如:

  • 第一个通知发送foo并且bar

    • 第二个通知发送faz并且baz

    • 第三次通知发送fubarfobaz

所以我会在栏中收到 3 条通知。现在,无论我单击什么通知,第一个、第二个、第三个,我都会看到最后一个发送的值fubar现在,无论我单击什么通知,第一个、第二个、第三个,我都会看到最后一个和fobaz。我想要的是当我单击特定通知时,活动显示该通知发送的值。

任何帮助将不胜感激。谢谢。

bwe*_*egs 5

这是因为您正在使用FLAG_UPDATE_CURRENT

指示如果所描述的 PendingIntent 已经存在,则保留它但用这个新 Intent 中的内容替换其额外数据的标志。

这就是extra用最后一个意图的数据替换您的数据。

相反,在这里为 PendingIntent 的默认行为传递 0:

PendingIntent notifPendingIntent = stackBuilder.getPendingIntent(0, 0);
Run Code Online (Sandbox Code Playgroud)