Addy Addy - 25 days ago 25
Android Question

Get custom payload from FCM in android

I have to read below mentioned keys from FCM Push notification.

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


I am using

public void onMessageReceived(RemoteMessage remoteMessage) {

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

sendNotification(title, "");

}


Problem is
title=remoteMessage.getData.get("sender_name"); returns null
, and when I view in browser it shows me that data is present in
sender_name
.

Answer
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());
            }
        }
    }