Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent Android notifications from overwriting themselves?

I am using XMPP (smack) to create a messaging application and I am sending notifications whenever I receive a new message. The problem is that if I receive messages from two different users I can only see the last notification. How can I change it? Here is my code.

Intent thisIntent = new Intent(mApplicationContext, ChatActivity.class);
thisIntent.putExtra("EXTRA_CONTACT_JID",contactJid);
PendingIntent contentIntent = PendingIntent.getActivity(mApplicationContext, 0, thisIntent, PendingIntent.FLAG_UPDATE_CURRENT);

NotificationCompat.Builder b = new NotificationCompat.Builder(mApplicationContext);

b.setAutoCancel(true)
        .setDefaults(Notification.DEFAULT_ALL)
        .setWhen(System.currentTimeMillis())
        .setSmallIcon(R.drawable.fab_bg_mini)
        .setTicker("Hearty365")
        .setContentTitle("New message")
        .setContentText(" You received a new message from " + contactJid)
        .setContentIntent(contentIntent)
        .setContentInfo("Info");
if(!ChatActivity.active){
    b.setDefaults(Notification.DEFAULT_LIGHTS| Notification.DEFAULT_SOUND);
}

NotificationManager notificationManager = (NotificationManager) mApplicationContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, b.build());

And as you can see I put an extra contactJid which is important to me. I need to set it in such a way that if a user clicks one notification its contactJid will be this and if another its contactJid will be another.

like image 886
Prethia Avatar asked Dec 27 '16 03:12

Prethia


1 Answers

notificationManager.notify(1, b.build()); is your problem - you need to supply a unique identifier for this notification, as per the documentation:

If a notification with the same id has already been posted by your application and has not yet been canceled, it will be replaced by the updated information.

You are supplying the constant 1 for each notification, instead of a unique ID. I'd suggest using a hash of the contact JID (which I assume is a string):

notificationManager.notify(contactJid.hashCode(), b.build());
like image 195
Adam S Avatar answered Nov 10 '22 05:11

Adam S