SoFunction
Updated on 2025-03-11

Notification Monitoring NotificationListenerService onNotificationPosted Repeated Callback Problem

text

Listen to notifications from third-party applications through NotificationListenerService and finds that the same notification will call back twice onNotificationPosted method.

// The first callback2023-01-31 11:42:31.082330  2483  2483 I NotificationMonitorService: onNotificationPosted:StatusBarNotification(pkg= user=UserHandle{0} id=11499522 tag=null key=0||11499522|null|10076: Notification(channel=wemeet shortcut=null contentView=null vibrate=default sound=:///2131623938 tick defaults=0x6 flags=0x11 color=0x00000000 vis=PRIVATE)) - 1
2023-01-31 11:42:31.086442  2483  2483 I NotificationMonitorReceiver: notify time: 1675136670845, pending size: 1
// The second callback2023-01-31 11:42:31.088771  2483  2483 I NotificationMonitorService: onNotificationPosted:StatusBarNotification(pkg= user=UserHandle{0} id=11499522 tag=null key=0||11499522|null|10076: Notification(channel=wemeet shortcut=null contentView=null vibrate=default sound=:///2131623938 tick defaults=0x6 flags=0x11 color=0x00000000 vis=PRIVATE)) - 1
2023-01-31 11:42:31.090506  2483  2483 I NotificationMonitorReceiver: notify time: 1675136670845, pending size: 2

The idea to solve this problem is how to determine whether the StatusBarNotification object of the two callbacks is the same notification.

After log analysis, the timestamp of onNotificationPosted differs in milliseconds, and the postTime of the StatusBarNotification object is the same twice.

By recording the last StatusBarNotification object and comparing it to the second StatusBarNotification object,

The StatusBarNotification object has an attribute key that can be used as a unique identifier:

    private String key() {
        String sbnKey = () + "|" + pkg + "|" + id + "|" + tag + "|" + uid;
        if (overrideGroupKey != null && getNotification().isGroupSummary()) {
            sbnKey = sbnKey + "|" + overrideGroupKey;
        }
        return sbnKey;
    }

And deduplication with the postTime property:

// Filter the same notificationif (lastSbn?.key ==  && lastSbn?.postTime == ) {
		return
}

Of course, if you know some extra information in the Intent, it can also be used as a filter:

val text = (Notification.EXTRA_TEXT)
val title = (Notification.EXTRA_TITLE)
// other ...

The above is the detailed content of the notification monitoring of NotificationListenerService onNotificationPosted duplicate callback problem. For more information about NotificationListenerService onNotificationPosted, please follow my other related articles!