Reputation: 950
I have a method called sendNotification
that can get called multiple times.
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);
}
When the user selects a notification
I would lick to pick up the data I associated with the notification in the onResume
method.
I am doing the following in 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");
}
The trouble is the notification and notification_extra data always belongs to the wrong notification after the user clicks a notification.
This is I think because of
PendingIntent intent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
But I have tried different flags with no luck.
How can I create many notifications with their OWN PendingIntent
attached ?
Thanks
Upvotes: 3
Views: 498
Reputation: 950
I had to send a unique integer to PendingIntent for each notification. Above I was just passing 0
Upvotes: 2