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

妖精的绣舞 提交于 2019-11-30 09:11:44
Mortimer

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.

dondondon

Well this codes work for me:

Notification n = new Notification(R.drawable.yourownpicturehere, 
                                   getString(R.string.noticeMe), 

System.currentTimeMillis());    
PendingIntent i=PendingIntent.getActivity(this, 0,
                                           new Intent(this, NotifyActivity.class),0);

n.setLatestEventInfo(getApplicationContext(), 
                     getString(R.string.title),
                     getString(R.string.message), i);
n.number=++count;
n.flags |= Notification.FLAG_AUTO_CANCEL;
n.flags |= Notification.DEFAULT_SOUND;
n.flags |= Notification.DEFAULT_VIBRATE;
n.ledARGB = 0xff0000ff;
n.flags |= Notification.FLAG_SHOW_LIGHTS;

// Now invoke the Notification Service
String notifService = Context.NOTIFICATION_SERVICE;
NotificationManager mgr = (NotificationManager) getSystemService(notifService);
mgr.notify(NOTIFICATION_ID, n);

Follow this link for complete tutorial.
I think the n.number=++count; is the one responsible for counting the notification

You will need a different bitmap for each number, and set the icon to show the bitmap that corresponds to the number of notifications left.

To keep track of the notifications, you can simply set a counter in SharedPreferences, add to it with each new notification, and reduce by one when a notification is read (or to zero if you show all the notifications at once).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!