gpt4 book ai didi

Android 通知不会堆叠

转载 作者:行者123 更新时间:2023-11-29 17:10:10 27 4
gpt4 key购买 nike

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

我创建了一个接口(interface),该接口(interface)具有一个在收到消息时将运行的方法。

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

当我初始化服务器对象时,我传递了一个新的监听器接口(interface)实例,其中覆盖的方法创建了通知。思路是,每次创建新通知时,我都会将 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,但我不确定如何向其动态添加通知。我的逻辑有问题还是我只是错误地使用了 Notification API?

最佳答案

答案是创建一个 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;
}

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

内的 MainActivity 中运行它
public static void resetPendingPushes() {
pendingPushes = 0;
style = new NotificationCompat.InboxStyle();
if (nm != null) {
nm.cancel(NEW_PUSH_NOT);
}
}

主要 Activity

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

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

关于Android 通知不会堆叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40754254/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com