首页 > 解决方案 > 通知 ID 不同时,Android 徽章计数错误

问题描述

我想在徽章上显示未读总数,但当通知 ID 不同时 setNumber(count) 错误。

这是我通过通知渠道显示徽章计数的代码。

val notification = NotificationCompat.Builder(context, "CHANNEL_ID_MESSAGE").apply {
                priority = chatNotificationData.channelImportance
                setGroup(NOTI_GROUP_ID)
                setContentTitle(roomName)
                setDefaults(NotificationCompat.DEFAULT_ALL)
                setCategory(NotificationCompat.CATEGORY_MESSAGE)
                setContentText(body)
                setTicker(body)
                setWhen(System.currentTimeMillis())
                setContentIntent(pendingIntent)
                setSmallIcon(smallIcon)
                setLargeIcon(ImageUtil.getCircularBitmap(profileImage))
                setNumber(unReadCount)
                setAutoCancel(true)
            }.build()
NotificationManagerCompat.from(context).apply { notify(roomSeq.toInt(), notification)}

setNumber unReadCount = 1, notify ID roomSeq = 100 Badge count is 1 OK!!

setNumber unReadCount = 2, notify ID roomSeq = 200 Badge count is 3 .. 为什么要加?我预计2。

setNumber unReadCount = 3, notify ID roomSeq = 200 Badge count is 4 ..

setNumber unReadCount = 4, notify ID roomSeq = 100 Badge count is 8 Oops....我不知道会发生什么

如何解决这个问题呢。

标签: androidandroid-notifications

解决方案


我在 Xamarin Android 中开发时遇到了同样的问题。

原因是我增加了“ .setNumber(value) ”的值。

在android文档中说:

默认情况下,每个通知都会增加一个显示在长按菜单上的数字(如图 1 所示),但您可以为您的应用覆盖此数字。例如,如果您只使用一个通知来表示多条新消息,但您希望此处的计数表示新消息的总数,这可能会很有用。

只是不增加 setNumber( 1 ) 值并且工作正常。

val notification = NotificationCompat.Builder(context, "CHANNEL_ID_MESSAGE").apply {
            priority = chatNotificationData.channelImportance
            setGroup(NOTI_GROUP_ID)
            setContentTitle(roomName)
            setDefaults(NotificationCompat.DEFAULT_ALL)
            setCategory(NotificationCompat.CATEGORY_MESSAGE)
            setContentText(body)
            setTicker(body)
            setWhen(System.currentTimeMillis())
            setContentIntent(pendingIntent)
            setSmallIcon(smallIcon)
            setLargeIcon(ImageUtil.getCircularBitmap(profileImage))
            setNumber(1)
            setAutoCancel(true)
        }.build()

安卓文档


推荐阅读