如何使 GCM / FCM 通知类型消息不可折叠

How to make a GCM / FCM notification-type message non-collapsible

Google 云消息 (GCM) 支持两种类型的推送消息:"notification" 消息和 "data" 消息。根据the documentation,通知消息默认是可折叠的,而数据消息默认是不可折叠的。

为了使数据消息可折叠,您需要指定 collapseKey。我的问题是:如何使通知消息不可折叠?

注意:该问题也适用于 Firebase 云消息传递 (FCM)。

message concepts and options documentation 状态:

messages are non-collapsible by default except for notification messages, which are always collapsible

但后来在同一页上,它继续说:

except for notification messages, all messages are non-collapsible by default

这有点模棱两可。但是,在 payload section 中,它指出:

[notification messages] may have optional data payload. Always collapsible

因此,似乎无法使通知消息不可折叠。

我建议这是设计使然,因为在 Android 中创建通知时,它们是 automatically replaced when another notification with the same ID is posted(类似于折叠消息的工作方式)。如果我没记错的话,FCM/GCM 对所有通知消息使用相同的 ID。

可能的解决方案

如果您确实想要一个不可折叠的通知消息,我建议您发送一个纯数据负载(没有通知或 collapseKey),然后覆盖 onMessageReceived() from the FirebaseMessagingService 来创建您的自己的通知。

Android quickstart sample:

上有一个例子
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // ...

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());

        // ...
    }

    // ...

    // Also if you intend on generating your own notifications as a result of a received FCM
    // message, here is where that should be initiated. See sendNotification method below.
}

那里的最后一条评论指向示例 sendNotification() method

对于您的情况,您需要将唯一 ID 传递给 notificationManager.notify() 调用,以便 Android 创建一个新通知并且不会替换任何现有通知 - 因此,使消息不可折叠。

首先,将 FCM docs reference here:

A non-collapsible message denotes that each individual message is delivered to the device. A non-collapsible message delivers some useful content, as opposed to a collapsible message like a content-free "ping" to the mobile app to contact the server to fetch data.

根据您的问题——“如何使通知消息不可折叠?”——您是否为每个 [= 指定了不同的 collapse_key 11=] 您发送的消息?

可折叠消息的工作方式就好像每条消息都具有 相同 collapse_key。但是,如果您为每条消息指定一个不同的消息,那么它将无法替换之前的消息。这将使 notification 消息 表现得 类似于 不可折叠 消息。

但是,由于您使用的是 collapse_key,它在技术上仍被视为 可折叠消息。这意味着它仍然受到一次四个折叠键的限制:

FCM allows a maximum of four different collapse keys per Android device to be used by the app server at any given time. In other words, the FCM server can simultaneously store four different collapsible messages per device, each with a different collapse key. If you exceed this number, FCM only keeps four collapse keys, with no guarantees about which ones are kept.

综上所述,您为什么不只使用 data 消息负载?我们在我们的应用程序上使用它,我发现它比 notification 消息更灵活。