I am developing an Android application in which I would like to receive push notification by FCM.
The onMessageReceived callback is triggered but the RemoteMessage.getData() has returned null value and when I evaluated the expression , the RemoteMessage.mBundle has the required data but not in JSON format
The following is the data I am getting from RemoteMessage.mBundle
Bundle[{google.sent_time=1519016906113, gcm.notification.categoryId=80302, google.ttl=2419200, gcm.notification.notificationId=127647, gcm.notification.e=1, gcm.notification.threadId=127093, gcm.notification.title=Moni Expert has commented on your post, from=612005318045, gcm.notification.roleId=115442, gcm.notification.userId=76284, gcm.notification.profileUrl=/image/user_male_portrait?img_id=122306&img_id_token=%2B99KTi28KTf7%2BehhVakxUyPqAuU%3D&t=1519016037919, google.message_id=0:1519016906118429%c05b1316c05b1316, gcm.notification.lastName=Expert, gcm.notification.notificationDate=2018-02-19 05:07:17.821, gcm.notification.timeStamp=Fri Feb 16 14:57:08 GMT 2018, gcm.notification.body=Moni Expert has commented on your post, gcm.notification.flag=0, gcm.notification.type=1, gcm.notification.firstName=Moni, gcm.notification.threadStatus=Published, gcm.notification.subject=posted, gcm.notification.roleName=D4E Admin, gcm.notification.userName=moniexpert, gcm.notification.postedUserId=76284, collapse_key=digital.engineers.club, gcm.notification.notification=Moni Expert has commented on your post}]
I have searched a lot to convert this data to Json format but nothing helped.
Update :
The code snippet has mentioned below
public class D4EPushService extends FirebaseMessagingService {
private static final String TAG = "MyFMService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// Handle data payload of FCM messages.
Log.d(TAG, "FCM Message Id: " + remoteMessage.getMessageId());
Log.d(TAG, "FCM Notification Message: " +
remoteMessage.getNotification());
Log.d(TAG, "FCM Data Message: " + remoteMessage.getData());
remoteMessage.mBundle;
}
I am not able to even assign remoteMessage.mBundle to new bundle variable in my code snippet as it has privately declared in RemoteMessage class
Please anyone help me to find the solution.
Try below solution it is work for me.
if (remoteMessage.getData().size() > 0) {
Map<String, String> data = remoteMessage.getData();
String message = data.get("your key");}
Related
In my app, i couldn't parse the "payload" object coming from push notification. There is automatically added '/' in each property in payload after push sent from server. How can i parse the payload property/object and get the notification data in my code?
Here is the payload object :
"payload":"{\"android\":{\"badge\":\"2\",\"alert\":\"Microfinaa_new_ne\",\"sound\":\"door_bell\",\"icon\":\"little_star\",\"vibrate\":true,\"title\":\"Mahboob Zaman\"}}"
And here is the full notification message coming from fcm server:
{"type":"callback","source":{"showTrayNotification":true,"pushType":"gcm","enabled":false,"showTrayNotificationsWhenFocused":false,"singleCallback":false,"focusAppOnPush":false,"showAppOnTrayClick":true,"debug":false,"apiName":"Ti.Module","bubbleParent":true,"invocationAPIs":[],"__propertiesDefined__":true,"_events":{"callback":{}}},"payload":"{\"android\":{\"badge\":\"2\",\"alert\":\"Microfinaa_new_ne\",\"sound\":\"door_bell\",\"icon\":\"little_star\",\"vibrate\":true,\"title\":\"Mahboob Zaman\"}}","bubbles":false,"cancelBubble":false}
And here is my code -
CloudPush.addEventListener('callback', function(evt) {
var json = JSON.stringify(evt.payload);
Ti.API.info("datos = " + json.android);// This line shows undefined
});
Payload is already string you need to parse it and use inverse function
var json = JSON.stringify(evt.payload);
JSON.stringify(Object) -> return String
JSON.parse(StringOject) -> return Object
this question is asked before here and here but i dont get answer from there.
I'm developing application in which i'm using pubsub and xmpp, for android i'm using smack library. i want to send custom payload to the node and on receiving custom payload how to parse and display it in to list? now i am able to send and receive message but it is just a small example from documentaion. here is my example,
String msg = "room pubsub test";
SimplePayload payload = new SimplePayload("message", "pubsub:test:message", "<message xmlns='pubsub:test:message'><body>" + msg + "</body></message>");
PayloadItem<SimplePayload> item = new PayloadItem<>(null, payload);
node.publish(item);
and when i receive item
node.addItemEventListener(new ItemEventListener() {
#Override
public void handlePublishedItems(ItemPublishEvent items) {
System.out.println("======================handlePublishedItems==============================");
System.out.println(items.getItems());
}
}
and the output i'm getting is
[org.jivesoftware.smackx.pubsub.PayloadItem |
Content [<item id='5E277A9C33A58'>
<message xmlns='pubsub:test:message'>
<body xmlns='pubsub:test:message'>room pubsub test</body><
/message>
</item>]]
i want to send custom payload like the time at which message is sent, who have sent this message etc.
so, how can i send custom payload? and how to parse it and show it to user?
Send custom payload for time and sender using below code:
SimplePayload payload = new SimplePayload("message", "pubsub:test:message", "<message xmlns='pubsub:test:message'><body>" + textMessage + "</body><from>"+Sender+"</from><time>"+time+"</time></message>");
For parsing you can use XmlPullParser and parse response using Tag name
I can succesfully send Firebase cloud messages to my Android sample project. As described in here, I apply step 2 and it works so far.
My JSON body:
{
"to": "/topics/testTopic",
"data": {
"key1" : "val1",
"key2" : true
}
}
has a data field which I can access properly in my onMessageReceived() method:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String toVal = remoteMessage.getTo();
Map<String, String> data = remoteMessage.getData();
}
But the getTo() method gets null.
How can I access the 'to' field in my originating JSON?
I was expecting to have "/topics/testTopic" in im variable toVal.
I think you're looking for RemoteMessage.getFrom():
Get the sender of this message.
This will be the sender ID or the topic for topic messages.
I'm having difficulty in passing background data to a screen. In the background the app is calling the screen correctly but the data that this screen needs that is in the "data" (id from data object) in the notification is not being picked up.
In foreground I got "data" correctly.
notification json
{
"to" : "akshih890uhnkjh389jfkn3...",
"priority" : "normal",
"time_to_live" : 0,
"data" : {
"type" : "my_type",
"id" : "my_id"
},
"notification" : {
"body" : "Test body",
"title" : "Test title",
"click_action" : ".MyActivity"
}
}
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String title = remoteMessage.getNotification().getTitle();
String body = remoteMessage.getNotification().getBody();
String clickAction = remoteMessage.getNotification().getClickAction();
Map<String, String> data = remoteMessage.getData();
Gson gson = new Gson();
MyObject myObject = new MyObject(data.get("id"), data.get("type"), remoteMessage.getNotification().getTitle(),
remoteMessage.getNotification().getBody());
Intent intent = new Intent(myObject.getClickAction());
intent.putExtra("id", myObject.getId());
PendingIntent contentIntent = PendingIntent.getActivity(
this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
sendFCMNotification(title, body, contentIntent);
}
MyActivity
if(getIntent() != null) {
Bundle extras = getIntent().getExtras();
code = extras.getString("id");
}
int id = Integer.valueOf(remoteMessage.getData().get("id"));
Since you use remoteMessage.getData(), you get entire data object, not an object who has data json inside, you get actual data json with your fields.
String data = remoteMessage.getData();
Gson gson = new Gson();
MyObject myObject = gson.fromJson(data, MyObject.class);
If your app is in background, Firebase will not trigger onMessageReceived(). Why.....? I have no idea. In this situation, I do not see any point in implementing FirebaseMessagingService.
According to docs, if you want to process background message arrival, you have to send 'click_action' with your message. But it is not possible if you send message from Firebase console, only via Firebase API. It means you will have to build your own "console" in order to enable marketing people to use it. So, this makes Firebase console also quite useless!
There is really good, promising, idea behind this new tool, but executed badly.
I suppose we will have to wait for new versions and improvements/fixes!
in the background, you can get data from intent extras if you want to call specific activity then specify it in click_action attribute of data
refer:
Firebase Server reference
Firebase Push
I found the problem, when the server sends me the notification object in the background I can not see the date. But when the server sends only the date I get the id however how will I be able to build a notification without the title and body data?
As you wrote in the title , when the application is closed it's working well and the onMessageReceived gets the message body and the title but if the app is in the foreground mode (running mode) the notifications can be sent but without message and title !
What to do please ?
The Code :
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String title = remoteMessage.getData().get("title");
String message = remoteMessage.getData().get("body");
sendNotification(title,message);
}
I know there are alot of issues published here in Stackoverflow but I've tried their solutions but the problem still exist !
Replace
String title = remoteMessage.getData().get("title");
String message = remoteMessage.getData().get("body);
By
String title = remoteMessage.getNotification().getTitle();
String message = remoteMessage.getNotification().getBody();
What you used is for data payload that you set as key-value pair while sending a notification. You may find input fields for them under Advanced Options section as Custom Data in firebase notification console.