具有独特数据的PendingIntent的通知

3
我有一个名称为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");

}

问题在于当用户点击通知后,通知和通知额外数据总是属于错误的通知。

我认为这是由于

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

但我已经尝试了不同的标志,没有运气。

如何创建许多带有它们自己的 PendingIntent 的通知?

谢谢


2
不确定标志是否正确或存在问题,但您始终使用相同的请求代码(0)启动相同的操作,并且使用不同的额外信息并不重要:您的PendingIntent都被视为相同的PendingIntent,请参阅文档 - Bö macht Blau
感谢您的请求代码,问题已解决。 - Glenn Pierce
请回答您自己的问题并接受答案。这将有助于其他遇到类似问题的人,并从未回答的问题列表中移除该问题。 - David Wasser
1个回答

2
我之前在发送通知时,每个通知的PendingIntent都需要传递一个唯一的整数值。但是我之前只是传递了0这个整数值。现在需要修改为每个通知都传递一个不同的整数值。"最初的回答"。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接