Okan
Okan

Reputation: 1389

Setting notification intent for multiple notifications

I have a method like this:

private void createNotification(String sender) {
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
        .setContentTitle(sender+" sent you a message")
        .setAutoCancel(true)
        .setSmallIcon(R.drawable.ribony_top_icon)
        .setContentText("Touch for reply")
        Intent resultIntent = new Intent(this, LoginActivity.class);
        resultIntent.putExtra("gcm_username",sender);
        resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent,  PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);
        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(NotificationID.getID(sender), mBuilder.build());
}

I am creating 3 three notifications like this:

createNotification("test1");
createNotification("test2");
createNotification("test3");

Notifications are creating without any problem.But when I touch the notification test1 or test2 it is calling test3 I mean all notification intents sets to last intent.How can I resolve it ?

Upvotes: 2

Views: 1149

Answers (2)

Tolgay Toklar
Tolgay Toklar

Reputation: 4343

If the PendingIntent has the same operation, action, data, categories, components, and flags it will be replaced.

Depending on the situation i usually solve this by providing a unique request code either as static values (0,1,2) or the row id of the data I'm receiving from the DB.

PendingIntent.getActivity(context, MY_UNIQUE_VALUE , notificationIntent, PendingIntent.FLAG_ONE_SHOT);

Then I use the same unique value for notify() as

mNotificationManager.notify(MY_UNIQUE_VALUE, notification);

Answer:Multiple notifications to the same activity

Upvotes: 2

f3rn4nd000
f3rn4nd000

Reputation: 434

This happends because when you create your PendingIntent, the last argument indicate if has some other pending intent to the same activity, just gonna be updated instead create a new one. You only need change the last argument to some of the other flags or only put 0 to indicate don't need a special flag.

PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, 0);

EDIT

Add the message like a extra in the intent.

resultIntent.putExtra("message_extra", sender);

And in the Activity only recover the new extra to show the message.

Upvotes: 0

Related Questions