如何拦截 Android 中的 Stacked 通知

How to intercept Stacked notifications in Android

我很熟悉 stacked notification 的概念。

如果有相应的摘要通知,手机不会显示非摘要通知。但是如果没有摘要通知,则显示非摘要通知

我正在监听 Kitkat 中引入的 NotificationListenerService 发布的每条通知。我拦截并显示每条通知文本。

问题是当堆叠通知到达时,我收到了 groupSummary 和非摘要通知的回调。如果我必须决定是否应显示非摘要,我必须检查所有其他通知以获取摘要。

如何在不重复检查所有当前通知列表的情况下复制移动设备的行为,也就是说,复杂度小于 O(n^2)?或者 Android 源代码是否也以同样复杂的方式进行?

我自己设计了一个复杂度 < O(n^2) 的方法。猜猜我没有考虑使用更好的数据结构。这是功能。如有错误欢迎指出。

private ArrayList<StatusBarNotification> cleanseNonSummary(ArrayList<StatusBarNotification> notifications) throws Exception{
    Set<String> groupSet = new HashSet<>();

    //first run : add all summary notification keys to unique set
    for(StatusBarNotification sbn : notifications){

        if(NotificationCompat.isGroupSummary(sbn.getNotification()))
            groupSet.add(NotificationCompat.getGroup(sbn.getNotification()));
    }

    //second run : remove all non summary notifications whose key matches with set elements
    for(int i=0; i<notifications.size(); i++) {
        StatusBarNotification sbn = notifications.get(i);

        if (!NotificationCompat.isGroupSummary(sbn.getNotification())) {
            String groupId = NotificationCompat.getGroup(sbn.getNotification());

            if (groupId != null && groupSet.contains(groupId))
                notifications.remove(i--);
                //decrement counter if an element is removed
        }
    }

    return notifications;
}