Get value from RemoteMessage from FCM onMessageReceived method

后端 未结 3 1060
囚心锁ツ
囚心锁ツ 2021-01-03 19:49

I have migrate gcm to fcm for push notification message. but how I Get bundle data from RemoteMessage received onMesssageReceived method.

Old GC         


        
相关标签:
3条回答
  • 2021-01-03 20:06

    For your data that looks like:

    "data":{ 
        "message": "Message for new task",
        "time": "6/27/2016 5:24:28 PM"
    }
    

    you should get them through

    Log.d(TAG, "Key Data : " +  remoteMessage.getData().get("message").toString());
    Log.d(TAG, "Key Data : " +  remoteMessage.getData().get("time").toString());
    

    Wrap them in try catch to be sure

    0 讨论(0)
  • 2021-01-03 20:12

    In FCM you received RemoteMessage instead of Bundle.

    Below is the way I used in my application where data is my RemoteMessage

    Map<String, String> data = remoteMessage.getData()
    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();
    

    Below is my notification data which I am sending it from server

    {
      "registration_ids": "",
      "data": {
        "questionId": 1,
        "userDisplayName": "Test",
        "questionTitle": "Test",
        "latestComment": "Test"
      }
    }
    

    So you have to parse each and every field as per your response. As I have debugged the code you will receive map in your RemoteMessage and cast those fields in appropriate data types as all those data comes as string.

    0 讨论(0)
  • 2021-01-03 20:29

    Here is the code snippet which is pretty much self Explanatory.

    You get the data in the form of the 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());
              }
           }
    

    Make Sure from server you are sending data in correct format i.e. in the "data" key

    here is the demo Json file

    {
      "to": "registration_ids",
      "data": {
        "key": "value",
        "key": "value",
        "key": "value",
        "key": "value"
      }
    }
    
    0 讨论(0)
提交回复
热议问题