Android 通知操作 - Intent Extra 未按预期工作

Android Notification Action - Intent Extra not working as expected

我正在创建一个包含多个操作的 notification。我正在使用 broadcast intents 来传达一个已被推送并采取具体行动。有 4 个按钮,我创建了 4 个独立的意图。每个都有相同的 Action 字符串,但 StringExtra.

Intent intNow = new Intent(mThis, MyReceiver.class).setAction(actionNotify).putExtra("button", ACT_NOW);
    Intent intEmail = new Intent(mThis, MyReceiver.class).setAction(actionNotify).putExtra("button", ACT_EMAIL);
    Intent intLater = new Intent(mThis, MyReceiver.class).setAction(actionNotify).putExtra("button", ACT_LATER);
    Intent intNever = new Intent(mThis, MyReceiver.class).setAction(actionNotify).putExtra("button", ACT_NEVER);

    Notification.Builder myRatingNotification = new Notification.Builder(mThis)
            .setContentTitle(title)
            .setContentText(text)
            .setSmallIcon(R.mipmap.ic_launcher)
            .addAction(0, mThis.getString(R.string.Rate_Act_Now), PendingIntent.getBroadcast(mThis, 0, intNow, PendingIntent.FLAG_UPDATE_CURRENT))
            .addAction(0, mThis.getString(R.string.Rate_App_Email), PendingIntent.getBroadcast(mThis, 0, intEmail, PendingIntent.FLAG_UPDATE_CURRENT))
            .addAction(0, mThis.getString(R.string.Rate_Act_Later), PendingIntent.getBroadcast(mThis, 0, intLater, PendingIntent.FLAG_UPDATE_CURRENT))
            .addAction(0, mThis.getString(R.string.Rate_Act_Never), PendingIntent.getBroadcast(mThis, 0, intNever, PendingIntent.FLAG_UPDATE_CURRENT))
            .setAutoCancel(true);

    Notification notification = new Notification.BigTextStyle(myRatingNotification).bigText(text).build();
    ((NotificationManager) mThis.getSystemService(Context.NOTIFICATION_SERVICE)).notify(notificationId, notification);

所以通知创建成功。按钮在那里。但无论我推哪一个,传递给 receiver 的额外内容始终是最后定义的操作。也就是说,在上面的示例中,每个按钮 returns 都是一个等于 ACT_NEVER 的 String Extra。如果我重新排序 .addAction 所以 intLater 是最后一个,接收者告诉我 String Extra 等于 ACT_LATER,无论我按下哪个按钮。

我不明白为什么 - 4 Intents 是完全独立的。这些操作指定了正确的 Intent。这是怎么回事?我被难住了。

我已经阅读了关于 addAction() 的文档,其中有一些非常有趣的内容:

  • 展开形式的通知最多可以显示 3 个操作
  • 每个动作必须有一个图标

你用0个作为图标,4个动作,可能对行为有一些影响

  1. 您应该将图标设置为第一个参数,而不是 0。
  2. 你现在的结果是因为你用了相同的action和相同的requestCode构造了一个PendingIntent,所以4个PendingIntent是一样的,而你用的是PendingIntent.FLAG_UPDATE_CURRENT,所以最后一个PendingIntent的extra会替换之前的。

所以要解决你的问题,你只需要为四个PendingIntent设置不同的requestCode,就像这样:

.addAction(0, mThis.getString(R.string.Rate_Act_Now), PendingIntent.getBroadcast(mThis, 0, intNow, PendingIntent.FLAG_UPDATE_CURRENT))
.addAction(0, mThis.getString(R.string.Rate_App_Email), PendingIntent.getBroadcast(mThis, 1, intEmail, PendingIntent.FLAG_UPDATE_CURRENT))
.addAction(0, mThis.getString(R.string.Rate_Act_Later), PendingIntent.getBroadcast(mThis, 2, intLater, PendingIntent.FLAG_UPDATE_CURRENT))
.addAction(0, mThis.getString(R.string.Rate_Act_Never), PendingIntent.getBroadcast(mThis, 3, intNever, PendingIntent.FLAG_UPDATE_CURRENT))