从FCM onMessageReceived方法获取RemoteMessage的值

Jat*_*tel 22 java android android-notifications google-cloud-messaging firebase-cloud-messaging

我有迁移gcm to fcm推送通知消息.但我如何从RemoteMessage获取捆绑数据收到onMesssageReceived方法.

Old GCM give bundle data onMessageReceiced method but in FCM there is RemoteMessage data.
Run Code Online (Sandbox Code Playgroud)

所以请告诉我如何解析remotemessage获取所有通知值.

我的PAYROL

{
"collapse_key":"score_update",
"priority":"high",
"content_available":true,
"time_to_live":108,
"delay_while_idle":true,
"data": 
{ 
    "message": "Message for new task",
    "time": "6/27/2016 5:24:28 PM"
},
"notification": {
    "sound": "simpleSound.wav",
    "badge": "6",
    "title": "Test app",
    "icon": "myicon",
    "body": "hello 6 app",
    "notification_id" : "1140",
    "notification_type" : 1,
    "notification_message" : "TEST MESSAGE",
    "notification_title" : "APP"
  },
"registration_ids": ["cRz9SJ-gGuo:APA91bFJPX7_d07AR7zY6m9khQro81GmSX-7iXPUaHqqcOT0xNTVsOZ4M1aPtoVloLNq71-aWrMCpIDmX4NhMeDIc08txi6Vc1mht56MItuVDdA4VWrnN2iDwCE8k69-V8eUVeK5ISer"
]
}
Run Code Online (Sandbox Code Playgroud)

Pri*_*shi 43

这是代码片段,几乎是自我解释.

您可以使用Map的形式获取数据

public void onMessageReceived(RemoteMessage remoteMessage)
        {
            Log.e("dataChat",remoteMessage.getData().toString());
            try
            {
                Map<String, String> params = remoteMessage.getData();
                JSONObject object = new JSONObject(params);
                Log.e("JSON_OBJECT", object.toString());
          }
       }
Run Code Online (Sandbox Code Playgroud)

从服务器确保您正在以正确的格式发送数据,即在"数据"键中

这是演示Json文件

{
  "to": "registration_ids",
  "data": {
    "key": "value",
    "key": "value",
    "key": "value",
    "key": "value"
  }
}
Run Code Online (Sandbox Code Playgroud)

  • `remoteMessage.getData()` returns blank array (11认同)
  • 感谢您的回答,但我在通知对象下的其他数据不在数据对象中,那么我该如何获取它. (3认同)

小智 28

在FCM中,您收到了RemoteMessage而不是Bundle.

以下是我在我的应用程序中使用的方式,其中数据是我的RemoteMessage

int questionId = Integer.parseInt(data.get("questionId").toString());
String questionTitle = data.get("questionTitle").toString();
String userDisplayName = data.get("userDisplayName").toString();
String commentText = data.get("latestComment").toString();
Run Code Online (Sandbox Code Playgroud)

以下是我从服务器发送的通知数据

{
  "registration_ids": "",
  "data": {
    "questionId": 1,
    "userDisplayName": "Test",
    "questionTitle": "Test",
    "latestComment": "Test"
  }
}
Run Code Online (Sandbox Code Playgroud)

因此,您必须根据您的回复解析每个字段.当我调试代码时,您将在RemoteMessage中接收映射并将这些字段转换为适当的数据类型,因为所有这些数据都以字符串形式出现.