Android 安卓通知赢得';t堆栈

Android 安卓通知赢得';t堆栈,android,notifications,Android,Notifications,我正在开发一个从服务器接收消息的应用程序。收到消息时,将显示通知。当收到第二条消息时,它应该堆叠起来,而不是创建一个全新的通知 我创建了一个接口,该接口有一个在收到消息时运行的方法 Server对象是接收消息的地方,构造函数接受上面提到的接口 当我初始化服务器对象时,我传递了侦听器接口的一个新实例,在该实例中重写的方法创建了通知。思想过程是每次创建新通知时,我将new\u POST\u NOTI整数增加1,并将其添加到组中 我的代码如下所示: final int PUSHES_GROUP = 6

我正在开发一个从服务器接收消息的应用程序。收到消息时,将显示通知。当收到第二条消息时,它应该堆叠起来,而不是创建一个全新的通知

我创建了一个接口,该接口有一个在收到消息时运行的方法

Server
对象是接收消息的地方,构造函数接受上面提到的接口

当我初始化服务器对象时,我传递了侦听器接口的一个新实例,在该实例中重写的方法创建了通知。思想过程是每次创建新通知时,我将
new\u POST\u NOTI
整数增加1,并将其添加到组中

我的代码如下所示:

final int PUSHES_GROUP = 67;
int NEW_POST_NOTI = 56;


每次收到消息时都会运行相同的代码,但会为每条消息创建单独的通知,而不是对它们进行分组。我还尝试使用
setStyle
使其成为
InboxStyle
,但我不确定如何动态添加通知。我的逻辑有问题吗?还是我只是错误地使用了通知API?

我建议您使用
通知ID
,该ID在
通知管理器中使用。此NotificationID基本上代表每个应用程序的唯一ID,因此如果使用相同的通知ID,则可以加入所有通知。试试下面的,让我知道

static final int MY_NOTIFICATION_ID = 1;
像这样声明一个静态通知ID。并以同样的方式通知! 所以不是

nm.notify(NEW_PUSH_NOTI++, noti);
你写

nm.notify(MY_NOTIFICATION_ID, noti);

答案是创建一个
InboxStyle
实例变量,并在每次收到新消息时对其调用
addLine
。然后,一旦应用程序在Resume上调用
onResume
,请重置
Inbox样式

例如:

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;
    }
然后我创建了一个方法来重新启动挂起计数,并关闭通知。我在
onResume()的
main活动中运行它

主要活动

@Override
protected void onResume() {
    super.onResume();
    ServerService.resetPendingPushes();
}
感谢所有回答的人,你帮了大忙!!
对于任何有类似问题的人,如果我的答案有拼写错误,我会很快从手机中输入答案。

分组适用于android wear。对于android掌上电脑,使用带有行和摘要的收件箱样式:你是对的。虽然不像我想象的那么简单,但还是相当简单。不仅仅是这个。检查我的答案。
public static void resetPendingPushes() {
    pendingPushes = 0;
    style = new NotificationCompat.InboxStyle();
    if (nm != null) {
        nm.cancel(NEW_PUSH_NOT);
    }
}
@Override
protected void onResume() {
    super.onResume();
    ServerService.resetPendingPushes();
}