通知监控NotificationListenerServiceonNotificationPosted重复回调问题

Oralie ·
更新时间:2024-09-20
· 773 次阅读

正文

通过 NotificationListenerService 监听第三方应用的通知发现,同一条通知,会回调两次 onNotificationPosted 方法。

// 第一次回调 2023-01-31 11:42:31.082330 2483 2483 I NotificationMonitorService: onNotificationPosted:StatusBarNotification(pkg=com.tencent.wemeet.app user=UserHandle{0} id=11499522 tag=null key=0|com.tencent.wemeet.app|11499522|null|10076: Notification(channel=wemeet shortcut=null contentView=null vibrate=default sound=android.resource://com.tencent.wemeet.app/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 // 第二次回调 2023-01-31 11:42:31.088771 2483 2483 I NotificationMonitorService: onNotificationPosted:StatusBarNotification(pkg=com.tencent.wemeet.app user=UserHandle{0} id=11499522 tag=null key=0|com.tencent.wemeet.app|11499522|null|10076: Notification(channel=wemeet shortcut=null contentView=null vibrate=default sound=android.resource://com.tencent.wemeet.app/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

解决该问题的思路是如何判断两次回调的 StatusBarNotification 对象是同一个通知。

经过日志分析,onNotificationPosted 的时间戳相差毫秒级别,且两次 StatusBarNotification 对象的 postTime 是相同的。

通过记录上一次 StatusBarNotification 对象,并与第二次的 StatusBarNotification 对象进行比较去重,

StatusBarNotification 对象有个属性 key,可以作为唯一识别符:

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

并配合 postTime 属性进行去重:

// 过滤同一条通知 if (lastSbn?.key == sbn.key && lastSbn?.postTime == sbn.postTime) { return }

当然,如果你知道一些 Intent 中的额外信息,也可以作为过滤条件:

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

以上就是通知监控NotificationListenerService onNotificationPosted重复回调问题的详细内容,更多关于NotificationListenerService onNotificationPosted的资料请关注软件开发网其它相关文章!



回调

需要 登录 后方可回复, 如果你还没有账号请 注册新账号
相关文章