Android - How to update notification number

后端 未结 3 1506
慢半拍i
慢半拍i 2021-02-06 06:23

Hi i want to show all the notification in a single view .. and want to update number of notification in status bar ... its updating all info but showing number always 1.. please

3条回答
  •  后悔当初
    2021-02-06 07:10

    This is my code, and it works. I have only tested on old Android versions thou. I suspect on newer versions the "number" badge has been made invisible, but I haven't had the chance to test it.

    void notifyMsgReceived(String senderName, int count) {
        int titleResId;
        String expandedText, sender;
    
        // Get the sender for the ticker text
        // i.e. "Message from "
        if (senderName != null && TextUtils.isGraphic(senderName)) {
            sender = senderName;
        }
        else {
            // Use "unknown" if the sender is unidentifiable.
            sender = getString(R.string.unknown);
        }
    
        // Display the first line of the notification:
        // 1 new message: call name
        // more than 1 new message:  + " new messages"
        if (count == 1) {
            titleResId = R.string.notif_oneMsgReceivedTitle;
            expandedText = sender;
        }
        else {
            titleResId = R.string.notif_missedCallsTitle;
            expandedText = getString(R.string.notif_messagesReceivedTitle, count);
        }
    
        // Create the target intent
        final Intent intent = new Intent(this, TargetActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        final PendingIntent pendingIntent =
            PendingIntent.getActivity(this, REQUEST_CODE_MSG_RECEIVED, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    
        // Build the notification
        Notification notif = new Notification(
            R.drawable.ic_notif_msg_received,  // icon
            getString(R.string.notif_msgReceivedTicker, sender), // tickerText
            System.currentTimeMillis()); // when
            notif.setLatestEventInfo(this, getText(titleResId), expandedText, pendingIntent);
        notif.number = count;
        notif.flags = Notification.FLAG_AUTO_CANCEL;
    
        // Show the notification
        mNotificationMgr.notify(NOTIF_MSG_RECEIVED, notif);
    }
    

    It is also easy to update the notification later on: you just have to call the method again with new values. The number will be displayed in the notification icon badge if and only if it was greater than zero when the notification was created.

    Similarily, the number badge won't be hidden (the number will, thou) if you set the number to a number that is less than 1. Maybe clearing the notification before re-showing it could fix it.

提交回复
热议问题