2015-12-14 128 views
0

我非常熟悉stacked notification的概念。如何拦截Android中的堆叠通知

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

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

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

我该如何复制移动设备的行为,而不必重复浏览所有当前通知的列表,即在小于O(n^2)的复杂度?还是Android的源代码也做同样复杂的方式?

回答

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; 
}