Android Dev: How to Group Notifications by String Instead of int

Currently, I'm working on a project which relies a lot on its notifications. So far, the logic was fairly simple:

  • display the notification
  • if there is already a notification, replace the previous one

The code for that logic is to use the same ID when creating the notification:

// constant notification id
final int NOTIFICATION_ID = 3000;

// create your notification
NotificationCompat.Builder mBuilder =  
        new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("title")
                .setContentText("content message");

// display notification
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);  
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());  

If you are using PendingIntents do not forget to set the flag: PendingIntent.FLAG_UPDATE_CURRENT.

The Logic Change

Last week, the notification display logic was changed. There are different entities that can display notifications. With the previous system, various entities could override the others' notifications.

The new system is that the app can display multiple notifications, but only one per entity. In other words, the previous system did not work anymore, since it gives every notification the same ID. Now, we need to give every notification from the same entity an identical ID.

My initial idea was to use the entity ID as the notification ID. Unfortunately, the entity ID is a GUID and thus is a String and not an int. I attempted to use a specialized hash-function to create a unique int for each String ID. This did not work very well so I looked for a different solution.

The Implementation

The solution was actually very straight-forward. The NotificationManager class has a second way to create notifications. It requires two IDs: A string and an int.

Now the implementation was easy:

String entityId = getEntityID();

// now with entityId to group by entity
mNotificationManager.notify(entityId, NOTIFICATION_ID, mBuilder.build());  

This displays a notification for every entity and only replaces a notification, if there is already a notification from that entity.


Explore the Library

Find interesting tutorials and solutions for your problems.