Android 通知不会堆叠

Android notifications won't stack

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

我创建了一个接口,该接口有一个方法,当收到消息时该方法将为 运行。

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

当我初始化服务器对象时,我传递了侦听器接口的一个新实例,其中覆盖的方法创建了通知。思考过程是每次创建新通知时,我将 NEW_POST_NOTI 整数加一并将其添加到一个组中。

我的代码如下所示:

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,但我不确定如何向其动态添加通知。我的逻辑有问题还是我只是错误地使用了通知 API?

我建议你使用 Notification ID,它在 NotificationManager 中使用。此 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。然后,应用调用 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;
    }

然后我创建了一个方法来重新启动挂起计数,并关闭通知。我运行那个在我MainActivity里面的onResume()

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

感谢大家的回答,你们帮了大忙!! 对于任何有类似问题的人,如果我的回答中有错别字,我很抱歉,我很快就从我的手机中输入了它。