How to count number of notification and display single icon in Android?

Tung Nguyen picture Tung Nguyen · Jun 17, 2011 · Viewed 28k times · Source

I have multiple Android notification, but when I send a message from my web server, the android device creates a new notification icon on status bar. I want to count the number of unread notification, display it on statusbar with single icon, and when a notification is read, the notification has to change the number of unread notification count. How can I do it? It's look like "3 Others" in this image: Notification Icon

Answer

Mortimer picture Mortimer · Sep 6, 2011

Check out the answer here: How to give counter if more than one Notifications are there

You just have to set Notification.number:

Notification notification = new Notification(R.drawable.direction, "Cool Notification",
                System.currentTimeMillis());
        /********LIKE THIS*********/
        notification.number = notificationCount++;
        /********LIKE THIS*********/

        notification.setLatestEventInfo(context, "Cool Notification Title",
                "updated notificaiton message", null);


        NotificationManager nm = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
        nm.notify(R.id.my_motification, notification);

You have to send your notification through the NotificationManager.notify method, with the same id all the time. As the documentation says, the id is a unique identifier for that notification within your application. If you reuse the same id, it will just update the text and number for that notification.

To check when the user clicks on the notification, you need to provide a PendingIntent (see the tutorial). To check when the user clears the notifications, you need to use the Notification.Builder that is only available in the Api Level 11.