我有一个名为 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和notification_extra数据总是属于错误的通知。
我认为这是因为
PendingIntent Intent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
但我尝试了不同的标志,但没有成功。
我如何创建许多通知并附有它们自己的 PendingIntent
?
谢谢
最佳答案
我必须为每个通知发送一个唯一的整数到 PendingIntent。 上面我只是传递了 0
关于android - 每个通知都有自己的包含唯一数据的 PendingIntent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54949825/