2016-11-23 89 views
1

我正在研究從服務器接收消息的應用程序。收到消息時,會顯示通知。當收到第二條消息時,它應該堆疊而不是創建一個全新的通知。Android通知不會堆棧

我創建了一個接口,該接口擁有一個將在收到消息時運行的方法。

Server對象是接收消息的地方,構造函數接受上面提到的接口。

當我初始化服務器對象時,我傳遞了偵聽器接口的一個新實例,其中重寫的方法創建通知。思考過程是每次創建新通知時,我都將NEW_POST_NOTI整數增加1,並將其添加到組中。

我的代碼如下所示:

final int PUSHES_GROUP = 67; 
int NEW_POST_NOTI = 56; 

...

Server server = new Server((msg) -> { 
    nm = NotificationManagerCompat.from(ctx); 
    Notification noti = new NotificationCompat.Builder(ctx) 
     .setSmallIcon(R.drawable.ic_noti) 
     .setContentTitle("New Message") 
     .setContentText(msg) 
     .setGroup(PUSHES_GROUP) 
     .build(); 
    nm.notify(NEW_PUSH_NOTI++, noti); 
}); 

這相同的代碼運行每次收到消息的時間,但對於每一個消息,而不是創建它們分組單獨通知。我也嘗試使用setStyle使其成爲InboxStyle,但我不確定如何動態地向其添加通知。我的邏輯是否存在問題,或者我是否錯誤地使用Notification API?

+0

分組是針對android磨損的。對於android手持設備,請使用帶有行和摘要的收件箱樣式:https://developer.android。com/training/wearables/notifications/stacks.html#AddSummary – njzk2

+0

你是對的。不像我想象的那麼容易,但相當簡單。 – Plays2

回答

2

答案是創建一個InboxStyle實例變量,並在其上調用addLine每次收到新郵件時。然後,一旦應用程序調用onResume,重置InboxStyle

因此,例如:

public class ServerService extends Service { 
    ... 
    NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle(); 
    private static NotificationManagerCompat nm; 
    private final Context ctx = Server.this; 
    Server server; 
    private static int pendingPushes = 0; 
    private final int NEW_PUSH_NOT = 2; 
    ... 
    @Override 
    public int onStartCommand(Intent i, int f, final int s) { 
     nm = NotificationManagerCompat.from(ctx); 
     try { 
      server = new Server((msg) -> { 
       pendingPushes++; 
       style.setBigContentTitle(pendingPushes +" new pushes");      
       style.addLine(msg); 
       Notification noti = new NotificationCompat.Builder(ctx) 
         .setSmallIcon(R.drawable.ic_noti) 
         .setStyle(style) 
         .setGroupSummary("Click here to view") 
         .setNumber(pendingPushes) //Should make the number in bottom right the amount of pending messages but not tested yet 
         .build(); 
       nm.notify(NEW_PUSH_NOT, noti); 
      }); 
      server.start(); 
     } catch(IOException e) { 
      e.printStackTrace(); 
     } 
     return START_STICKY; 
    } 

然後創建重新啓動掛起計數,並關閉通知的方法。我跑在我的MainActivityonResume()

public static void resetPendingPushes() { 
    pendingPushes = 0; 
    style = new NotificationCompat.InboxStyle(); 
    if (nm != null) { 
     nm.cancel(NEW_PUSH_NOT); 
    } 
} 

MainActivity內

@Override 
protected void onResume() { 
    super.onResume(); 
    ServerService.resetPendingPushes(); 
} 

謝謝大家誰回答,你幫一幫! 對於任何有類似問題的人,如果在我的回答中存在拼寫錯誤,我很快從單元格中輸入它。

1

我建議您利用NotificationManager中使用的Notification ID。此NotificationID基本上代​​表每個應用程序的唯一ID,因此如果您使用相同的通知ID,那麼您將能夠將所有通知分開。嘗試以下並讓我知道。

static final int MY_NOTIFICATION_ID = 1; 

聲明一個這樣的靜態通知ID。並通知相同! 所以不是

nm.notify(NEW_PUSH_NOTI++, noti); 

你寫

nm.notify(MY_NOTIFICATION_ID, noti); 
+0

它適合你嗎? – San

+0

這不僅僅是這個。檢查我的答案。 – Plays2