如何拦截Android中的堆叠通知

时间:2015-12-14 18:57:39

标签: android notifications

我熟悉stacked notification的概念。

如果有相应的摘要通知,则移动设备不会显示非摘要通知。但如果没有摘要通知,则会显示非摘要通知

我正在收听Kitkat中引入的NotificationListenerService发布的每个通知。我拦截并显示每个通知文本到达时。

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

如何重复移动行为,而不重复浏览所有当前通知的列表,即复杂度低于O(n ^ 2)?或者Android源代码也以同样复杂的方式执行它?

1 个答案:

答案 0 :(得分:0)

我自己设计了一种复杂度高的方法。为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;
}