【问题标题】:Firebase cloud messaging in android application only working for notifications and not data messagesandroid 应用程序中的 Firebase 云消息传递仅适用于通知而不是数据消息
【发布时间】:2020-04-12 19:18:27
【问题描述】:

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

<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。有人可以帮忙吗?

【问题讨论】:

  • 应用在前台时是否有效?
  • 不是数据一,但通知它工作
  • 如果你使用data,不管是后台还是前台,它都应该可以工作,在onmessagereceived里面添加一个日志来检查
  • 我这样做了...我切换到数据不起作用
  • 反正最近发生了一些奇怪的事情,通知突然不起作用。可能是 firebase 出现故障或其他原因,因为我以前能够接收带有通知的通知(从不数据),但我没有更改任何内容。

标签: android firebase firebase-cloud-messaging


【解决方案1】:

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

您的回复必须是这样的

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

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

【讨论】:

  • 我认为您误解了我的意思,我是说当它的数据对我不起作用时。只有通知对我有用
  • 使用"data": 响应并在您的remoteMessage.data 方法中将remoteMessage.notification 替换为onMessageReceived 方法并告诉我它是否有效?
  • 这很好。我没有意识到这一点。奇怪的是,我的通知现在也不起作用。像刚才一样突然停止工作。
【解决方案2】:

当应用程序关闭时系统将处理通知如果通知 有效负载具有将自动显示通知的通知键 基于此。下面的有效载荷显示通知标题和正文时 应用程序关闭,如果您处理数据 json,它将在应用程序之前不会显示 开始了。

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

此问题的解决方案是从有效负载中删除通知 将允许应用程序处理 json。

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

**

如果负载包含通知键系统将在应用关闭时处理, 如果有效载荷不包含通知密钥应用程序将处理它。

**

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    • 2020-11-07
    • 1970-01-01
    • 2021-07-22
    • 2019-06-12
    相关资源
    最近更新 更多