android 应用程序中的 Firebase 云消息传递仅适用于通知而非数据消息

Firebase cloud messaging in android application only working for notifications and not data messages

使用 firebase 向 android 设备发送推送通知。

<service
     android:name=".util.MyFirebaseMessagingService"
     android:exported="false">
     <intent-filter>
           <action android:name="com.google.firebase.MESSAGING_EVENT" />
     </intent-filter>
</service>


class MyFirebaseMessagingService: FirebaseMessagingService()  {

    private val TAG = "FirebaseMessaging"

    override fun onNewToken(token: String) {
        super.onNewToken(token)
        Log.d(TAG, token)
    }

    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        super.onMessageReceived(remoteMessage)

        if (remoteMessage.notification != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.notification!!.body)
        }
    }
}

我可以使用邮递员接收消息通知。

{
    "registration_ids": ["KEY_HERE"],
    "notification": {
        "title": "HIMAN",
        "body": "werwkejh"
    }
}

这非常有效,我可以添加一个断点,然后通知就会通过。但是,我需要这是一个数据类型的推送通知,因为当应用程序在后台时它不会触发 onMessageReceived 回调 - 仅在前台。据说在邮递员里也成功了。

{
    "multicast_id": 863107467701827657,
    "success": 1,
    "failure": 0,
    "canonical_ids": 0,
    "results": [
        {
            "message_id": "MESSAGE_ID"
        }
    ]
}

数据推送通知的请求体如下:

{
    "registration_ids": ["KEY_HERE"],
    "data":{
        "message": "hi!"
    }
}

只是没有触发我需要的 onMessageReceived。有人可以帮忙吗?

如果您的通知包含 "notification":,它会显示通知,但如果应用不是 运行,则 onMessageReceived 不会调用。对于这种情况,您已在 "data": 字段中传递数据并从响应中删除 notification":

你的回复必须是这样的

{
"to": "your device token",
 "data":{
   "name": "John",
    "message": "Hii! "
    }
 }

我遇到了同样的问题,这对我有用。

when application close system will handle notification if notification payload have notification key that will auto display notification based on that. below payload display notification title and body when app close and if you handle data json it will not show until app started.

{
    "to":"some_device_token"
    "notification": {
        "title": "HIMAN",
        "body": "werwkejh"
    },"data": {
           "extra":"juice"
}
}

Solution for this problem is to remove notification from payload that will allow application to handle the json.

{
"to":"some_device_token"
"data": {
"extra":"juice"
}
}

**

if payload contain notification key system will handle when app close, if payload not contain notification key application will handle it.

**