在Android中从FCM获取自定义有效负载

时间:2016-11-14 06:47:25

标签: java android push-notification firebase-cloud-messaging

我必须从FCM推送通知中阅读下面提到的密钥。

    { 
      "from_id": "",
      "data": {  
        "sender_id": "15", 
        "receiver_id": "42", 
        "sender_name": "Addy", 
        "alert": "Addy sent you a message.",
        "notification_type": "message",
        "message": "testing" 
              }
     }

我正在使用

      public void onMessageReceived(RemoteMessage remoteMessage) {

      String title=remoteMessage.getData().get("sender_name");

      sendNotification(title, "");

      }

问题是title=remoteMessage.getData.get("sender_name"); returns null,当我在浏览器中查看时,它向我显示sender_name中存在数据。

2 个答案:

答案 0 :(得分:2)

public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.e(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage == null)
            return;

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
            handleNotification(remoteMessage.getNotification().getBody());
        }

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

            try {
                JSONObject json = new JSONObject(remoteMessage.getData().toString());
                handleDataMessage(json);
            } catch (Exception e) {
                Log.e(TAG, "Exception: " + e.getMessage());
            }
        }
    }

答案 1 :(得分:-1)

你能试试吗

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