每个通知都有自己的包含唯一数据的 PendingIntent

Notifications each with their own PendingIntent containing unique data

我有一个名为 sendNotification 的方法,可以多次调用。

private PendingIntent createNotificationIntent(Context context, String
type, int notificationId, String extra) {

   Intent notificationIntent = new Intent(this, ShimmyMobileActivity.class);
   notificationIntent.putExtra("com.****.****.action", type);
   notificationIntent.putExtra("com.****.****.notification_id",
notificationId);
   notificationIntent.putExtra("com.****.****.notification_extra",
extra);

   notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
         | Intent.FLAG_ACTIVITY_SINGLE_TOP);

   PendingIntent intent = PendingIntent.getActivity(this, 0,
         notificationIntent, PendingIntent.FLAG_IMMUTABLE);

   return intent;
}


private void sendNotification(int id, String message, String extra) {

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

   Notification.Builder builder = new
Notification.Builder(ShimmyMobileActivity.this);

   builder.setContentTitle("Shimmy Notification");
   builder.setContentText(message);
   builder.setSmallIcon(R.mipmap.ic_launcher);

   //builder.setDeleteIntent(this.createNotificationIntent(this,
"notification_delete", id, extra));
   builder.setContentIntent(this.createNotificationIntent(this,
"notification_clicked", id, extra));
   builder.setPriority(Notification.PRIORITY_MAX);

   if(this.preferences.getBoolean("vibrate", true)) {
      builder.setVibrate(new long[]{500, 500});
           Vibrator vibrator = (Vibrator) this
.getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(500);
       }

   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

      if (this.channel == null) {

         this.channel = new NotificationChannel(this.channelId,
"ShimmyMobile Notifications", NotificationManager.IMPORTANCE_DEFAULT);
         notificationManager.createNotificationChannel(this.channel);
      }

      builder.setChannelId(this.channelId);
   }

   Notification notification = builder.build();
   notificationManager.notify(id, notification);

}

当用户选择通知时 我会舔取与 onResume 方法中的通知关联的数据。

我正在 onResume

中执行以下操作
if(action != null && action.equals("notification_clicked".toString())) {

         int notification_id =
this.getIntent().getIntExtra("com.****.****.notification_id",
-1);
         String extra = this.getIntent().getStringExtra("com.****.****.notification_extra");

}

麻烦的是通知,notification_extra用户点击通知后,数据总是属于错误的通知。

我认为这是因为

PendingIntent 意图 = PendingIntent.getActivity(这, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);

但我尝试了不同的标志,但没有成功。

如何创建许多通知并附有它们自己的 PendingIntent

谢谢

我必须为每个通知发送一个唯一的整数到 PendingIntent。 上面我只是传递了 0