How to get value from FCM data message in Android? - android

I'm trying to implement FCM notification in my app. I have read FCM data message type will receive notification even when app is in background so am trying to implementing that in onMessageRecieved method am getting unexpected response like this:
{title =2, message={"Status":"UNASSIGNED","CompanyName":"gd","LastModifiedDateTime":"2017-04-25 18:59:41","IsPartRequired":false,"ProblemCategory":"CONFIGURATION","IsGeneralClaim":false,"RegistrationID":1057,"IncidentCode":"INS\/2017\/04\/25-0010","StatusID":0,"CreatedDateTime":"2017-04-25 18:59:41","IsInstallationCall":false}}
Don't know how to parse this get separate value from title and message let me post my firebase message code:
public class FireBaseMessage extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Map<String,String> data = remoteMessage.getData();
Log.d(TAG, "From: " + data.toString());
//
}
}
In this log message am getting response like that how to get value from that is try like:
int title=data.get("title");
getting null pointer as this is not in valid format. In my server side i have am trying to post json format like this:
{
"to":"es_OToDkj00:APA91bFqxbVMAaXy5fPtDbNVAkIwyVrPCmfGci2otHZPvdRoXPv-oDdjgtLR92Nqe8w6f57nCVceLbc3_zBWsInG9g1Pfdp3LvsMKyuaiYps0L1y3tn0N0XbzGseEI6jyiqs1r-sT9lb",
"data":{
"message":{
"RegistrationID":1057,
"IncidentCode":"INS/2017/04/25-0010",
"CompanyName":"ABM INFOTECH",
"StatusID":5,
"Status":"ASSIGNED",
"CreatedDateTime":"2017-04-25T12:03:45",
"LastModifiedDateTime":"2017-04-25T18:59:41",
"ProblemCategory":"CONFIGURATION",
"IsPartRequired":false,
"IsInstallationCall":false,
"IsGeneralClaim":false
},
"title ":"1"
}
Don't know where I'm making a mistake. Can anyone help me? Thanks in advance!

To get the Title: from message payload
use:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
//In case when notification was send in "notification" parameter we need to check wheather data is null or not.
if (remoteMessage.getData()!=null && remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
String title = remoteMessage.getData().get("title").toString();
}
}
EDIT
check if your remoteMessage contain the specific key:
if (remoteMessage.getData()!=null){
for (Map.Entry<String, String> entry : remoteMessage.getData().entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
Log.d(TAG, "key, " + key + " value " + value);
}}

There are two types of FCM messages:
1) Notification Messages
2) Data Messages
Notification Message Structure:
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification":{
"title":"Portugal vs. Denmark",
"body":"great match!"
}
}
}
In order to get data from the notification payload/messages:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message From " + remoteMessage.getFrom()); //sender ID
Log.d(TAG, "Notification Title " + remoteMessage.getNotification().getTitle()); //notification title
Log.d(TAG, "Notification Body " + remoteMessage.getNotification().getBody()); //notification body
}
}
Data Message Structure:
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data":{
"Nick" : "Mario",
"body" : "great match!",
"Room" : "PortugalVSDenmark"
}
}
}
In order to get data from the data payload/messages:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Data: " + remoteMessage.getData()); //Whole data
Log.d(TAG, "Key Data : " + remoteMessage.getData().get("key").toString()); //Get specific key data
}
}

You have an extra space character in your "title" parameter:
"title ":"1"
It's hard to see since it's just a space. It should be:
"title":"1"
The reason you're note getting any value is because technically, the key being sent is "title " (with a space), while in your client code, you're only using "title" (without a space).
You should be able to receive it correctly after you remove the extra space.

After many search I have found this answer, it working perfect
To make firebase library to call your onMessageReceived() in the following cases
App in foreground
App in background
App has been killed
you must not put JSON key 'notification' in your request to firebase API but instead use 'data', see below.
The following message will not call your onMessageReceived() when your app is in the background or killed, and you can't customize your notification.
{
"to": "/topics/journal",
"notification": {
"title" : "title",
"text": "data!",
"icon": "ic_notification"
}
}
but instead using this will work
{
"to": "/topics/dev_journal",
"data": {
"text":"text",
"title":"",
"line1":"Journal",
"line2":"刊物"
}
}
Basically, the message is sent in the argument RemoteMessage along with your data object as Map, then you can manage the notification in onMessageReceived as in the snippet here
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> data = remoteMessage.getData();
//you can get your text message here.
String text= data.get("text");
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
// optional, this is to make beautiful icon
.setLargeIcon(BitmapFactory.decodeResource(
getResources(), R.mipmap.ic_launcher))
.setSmallIcon(smallIcon) //mandatory
.......
/*You can read more on notification here:
https://developer.android.com/training/notify-user/build-notification.html
https://www.youtube.com/watch?v=-iog_fmm6mE
*/
}
reference: How to handle notification when app in background in Firebase

Related

Firebase Remote message returns null data on remotemessage.getDate()

Using FirebaseMessagingService to send Remote Message Using PHP.
It was working fine till date, suddenly app stops receiving notification, after debug i found that
onMessegeReceived(remoteMessage)
remoteMessage.getData() returns null Array Map.
But I can see the payload data in Bundle
Bundle[{google.delivered_priority=high, google.sent_time=1556008551748, google.ttl=2419200, google.original_priority=high,
from=982221224130,
google.message_id=0:1556008551825452%903f05e2903f05e2,
gcm.notification.data={"image":"https:url","nId":1313,"time":"14:05:51","priority":"normal","title":"testttt","message":"","type":"1"}, google.c.a.e=1, collapse_key=com.sam.grapemundo}]
I expect the result remoteMessage.getData() returns
data={"image":"https:url","nId":1313,"time":"14:05:51","priority":"normal","title":"testttt","message":"","type":"1"}, google.c.a.e=1, collapse_key=com.sam.grapemundo}]
First of all you have to check notification is fired or not:-
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.e(TAG, "From: " + remoteMessage.getFrom());
Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
if (remoteMessage.getNotification() == null)
return;
// Check if message contains a notification payload.
if(remoteMessage.getNotification() != null) {
handleNotification(remoteMessage, remoteMessage.getNotification().getBody(), remoteMessage.getNotification().getTitle());
}

How to get the background notification title and body inside the application [duplicate]

I need to use non-collapsible notification by Firebase. For that I am using data-message like this:
{
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data" : {
"Nick" : "Mario",
"body" : "great match!",
"Room" : "PortugalVSDenmark"
},
}
This message is interpreted in the onMessageReceived() method.
I still want to display this data-message in the tray just like notification-messages are displayed by the system automatically.
How to I achieve this? I cannot find documentation on this.
Thanks!
You can retrieve the values from your data payload in onMessageReceived() by calling RemoteMessage.getData(), then .get("<KEY_HERE>"). Like so:
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d(TAG, "onMessageReceived()");
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
String dataTitle = remoteMessage.getData().get("data_title");
String dataBody = remoteMessage.getData().get("data_body");
sendNotification(dataTitle, dataBody);
}
You have to then build and display the Notification yourself. Like so:
private void sendNotification(String title, String body) {
Notification notif = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(body)
.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(0, notif);
}

Notifications not displayed when app is in foreground and onMessageReceived is called

I am trying to display a notification when the fcm message received and the APP is in the background. I tried different flavors of notifications but not luck. The notification won't show
Here is the code
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(GlobalVar.TAG, "From: " + remoteMessage.getFrom());
super.onMessageReceived(remoteMessage);
String channelId = getString(R.string.notification_channel_id);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(remoteMessage.getNotification().getTitle())
.setContentText(remoteMessage.getNotification().getBody()).setAutoCancel(true);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
I know this is getting called because I get the log.
If the app is in the background then FCM displays notifications. It is the above code that is not displaying it when app is in foreground
Any suggestions?
PS: I created the channel in the Application class
I don't get errors in the log cat. I am also setting all the notifications settings as per code below. Please note my device receive and display notifications already from FCM when it is in background. But when it is in foreground and "I" handle the display of notification then it does not work
Hopefully your server is sending you notification in data key.
Here as I saw your code, You are getting notification data using remoteMessage.getNotification()
Now you have to make changes in your server side script that they send in data key as follow (You can test temporary before changing server code):
{
"to" : "YOUR_FCM_TOKEN_WILL_BE_HERE",
"collapse_key" : "type_a",
"data" : {
"body" : "Body of Your Notification in Data",
"title": "Title of Your Notification in Title",
"key_1" : "Value for key_1",
"key_2" : "Value for key_2"
}
}
and after that you can receive like this:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}
}
To know more about it:
Hope you will get help in this. Do let me know if you get any problem.
If you're not using your own server, then you can't achieve this. You need to use your own server to modify the JSON format from this:
{
"to" : "YOUR_FCM_TOKEN_WILL_BE_HERE",
"collapse_key" : "type_a",
"notification" : {
"body" : "Body of Your Notification in Data",
"title": "Title of Your Notification in Title",
"key_1" : "Value for key_1",
"key_2" : "Value for key_2"
}
}
to:
{
"to" : "YOUR_FCM_TOKEN_WILL_BE_HERE",
"collapse_key" : "type_a",
"data" : {
"body" : "Body of Your Notification in Data",
"title": "Title of Your Notification in Title",
"key_1" : "Value for key_1",
"key_2" : "Value for key_2"
}
}
when your server will modify "notification" tag with "data" then only you can recieve notification in background.

FCM Push notifications display raw json even after implementing dats messages

Following is the json that I am trying to send from the firebase console
{
"message": {
"token": "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data": {
"Nick": "Mario",
"body": "great match!",
"Room": "PortugalVSDenmark"
}
}
}
My code in onMessageReceived is as follows
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
String name = remoteMessage.getData().get("Nick").toString();
String body = remoteMessage.getData().get("body").toString();
String room = remoteMessage.getData().get("Room").toString();
String messageBody = name
+ " "
+ body
+ " "
+ room;
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle("Zone")
.setContentText(messageBody)
.setAutoCancel(true)
.setSmallIcon(R.mipmap.ic_launcher)
/*Notification with Image*/;
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
Every time I send the above json from firebase console it does not even enter the if condition because the remoteMessage.getData().size() is not greater than zero.
Why is this happening though I am sending a data payload?
Also when the notification is received I want to create a sentence from the raw json and display it . E.g "Nick liked a picture"
When the notification comes through only the json is displayed.
Been struggling with this for a long time .
Any help will be appreciated. Thank you
Try this.
String nick,body,room, fullString;
if(!remoteMessage.getData().isEmpty()){
Log.d(TAG, "Notification Message Data: " + remoteMessage.getData());
nick=remoteMessage.getData().get("Nick");
body=remoteMessage.getData().get("body");
room=remoteMessage.getData().get("Room");
Log.d(TAG, "All data: " + nick+","+body+","+room);
fullString = "Anything you want"+nick+"anything";
//then use the string anywhere
}

GCM data not being passed by AWS SNS

I'm using Amazon SNS to send push notifications to an Android device. If I send the following JSON I can't read the parameters in the data element.
{
"default": "message here",
"GCM": {
"data": {
"message": "This is the message"
}
}
}
I can read the default element but in my broadcastreceiver I can't do this.
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
Log.d("GCM",extras.getString("message");
}
Trying to read the message element causes an error.
If I send directly through GCM I can read all of the parameters that start with data. using the above method with no problem at all.
What am I doing wrong?
You need escape double quotation in GCM value.
{ "default": "message here", "GCM": "{ \"data\": { \"message\": \"This is the message\" } }" }

Categories

Resources