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

时间:2019-03-01 17:46:43

标签: android android-intent android-notifications

我有一个名为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(this,0, notificationIntent,PendingIntent.FLAG_IMMUTABLE);

但是我没有运气就尝试了不同的标志。

如何创建许多附加了OWN PendingIntent的通知?

谢谢

1 个答案:

答案 0 :(得分:0)

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