Android 上的 FCM 通知可以覆盖之前的通知吗?

Can FCM notification on Android overwrite previous one?

我正在使用 FCM 向 Android 设备发送通知。当应用程序在后台时,如果我发送 10 个通知,设备将在通知栏上显示 10 个条目。

我希望FCM在通知栏上只创建一个条目,即新的会覆盖旧的。我在 https://firebase.google.com/docs/cloud-messaging/http-server-ref#downstream.

找不到设置它的密钥

有办法吗,还是不可能?谢谢

这是可能的。两种方法。

首先,您使用 collapse_key 参数将消息设置为 可折叠消息。参考 FCM docs:

A collapsible message is a message that may be replaced by a new message containing the same collapse key if it has yet to be delivered to the device.

它实际上包含在您提供的 link 中(Options 下的第一个参数):

collapse_key - This parameter identifies a group of messages (e.g., with collapse_key: "Updates Available") that can be collapsed, so that only the last message gets sent when delivery can be resumed. This is intended to avoid sending too many of the same messages when the device comes back online or becomes active.

Note that there is no guarantee of the order in which messages get sent.

Note: A maximum of 4 different collapse keys is allowed at any given time. This means a FCM connection server can simultaneously store 4 different send-to-sync messages per client app. If you exceed this number, there is no guarantee which 4 collapse keys the FCM connection server will keep.


第二种方法是通知bundling/stacking/grouping。根据我的回答 here:

By grouping the notification, I'm presuming you mean stacking or bundling notifications.

This is more on how you handle the notification in your client app. You simply have to make use of the setGroup() to add all your notifications to a single group then calling notify() to let the NotificationManager of the changes.

This Add Each Notification to a Group documentation pretty much sums it all up.


更新:

来自, using the tag参数之一也是一个选项:

Identifier used to replace existing notifications in the notification drawer.

If not specified, each request creates a new notification.

If specified and a notification with the same tag is already being shown, the new notification replaces the existing one in the notification drawer.

为了实现这一点, 在您的通知负载中,使用标签键

{
    "notification" : {
        "title" : "Notification Title",
        "body" : "Notification Body",
        "tag" : "your_unique_tag"
    }
}

干杯。

对overwrite/update之前的通知使用相同的id

notification:{
...
id:125,
..
}