2015-12-14 94 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; 
}