FCM notification title remains "FCM Message" - android

I'm trying to use the Firebase Cloud Messaging. I send the notifications from a Node.js server to my apps that are registered to the notification system.
My problem is that on Android 5.1 the notification is "FCM Message" even if I setted the title attribute in the nofitification json. It works fine in Android 6.0. I tried to reboot my device as well.
And this is the code I use to send the notification:
function sendNotificationToUser(userToken, message, onSuccess) {
request({
url: 'https://fcm.googleapis.com/fcm/send',
method: 'POST',
headers: {
'Content-Type' :' application/json',
'Authorization': 'key='+API_KEY
},
body: JSON.stringify({
notification: {
"title": 'My App Name',
"body": message,
"sound": 'default'
},
to : userToken
})
}, function(error, response, body) {
if (error) { console.error(error); }
else if (response.statusCode >= 400) {
console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage);
}
else {
onSuccess();
}
});
}
As you can see the notification title I send is "My App Name" but on device it shows "FCM Message".
What do I have to do?!

You need to pass the title and then receive it in remoteMessage.getNotification().getTitle() , this will catch title and then display in the top or pass complete JSON from web and receive like this
JSONObject jsonObject = new JSONObject(remoteMessage.getData());
Here is the complete method:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// ...
// TODO(developer): Handle FCM messages here.
// Not getting messages here? See why this may be: https://firebase.google.com/support/faq/#fcm-android-background
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());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
Ref link

I found that it is a problem related to onMessageReceived callback.
As you can see on the receive a FCM guide

This is expected. (Tested upto Android 10)
FCM has different behaviours for app status (foreground and background / killed).
You should handle this by the payload you sent from server, according to your use case.
The msg sent from server has to be sent in either "notification" or "data" format, from dashboard or server side api.
Note: From firebase dashobard you can only send "notification" body and not data. In such cases, FCM will directly display the notif without giving a callback to your app.
Server side
Below are sample formats :
Notification Type Format
Note : Android System will by default display the notification in the notification tray and you don't need to display it.
{
"to": "your_token_id",
"notification" : {
"title" : "FCM Notification title!",
"body" : "FCM Notification subtext!",
"content_available" : true,
"priority" : "high"
}
}
Data Format (For receiving callback in app, in foreground and background)
Note : You have to handle callback and display notif on your own.
{
"to": "your_token_id",
"data" : {
"title" : "FCM Notification Title ",
"subtext" : "FCM Notification Sub Title",
"type" : "999",
"priority" : "high"
}
}
Android Client
To handle the payload received in your Android receiver, checl the official guide here
override fun onMessageReceived(remoteMessage: RemoteMessage) {
Log.d(TAG, "From: ${remoteMessage.from}")
// Check if message contains a data payload.
remoteMessage.data.isNotEmpty().let {
Log.d(TAG, "Message data payload: " + remoteMessage.data)
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use WorkManager.
scheduleJob()
} else {
// Handle message within 10 seconds
handleNow()
}
}
// Check if message contains a notification payload.
remoteMessage.notification?.let {
Log.d(TAG, "Message Notification Body: ${it.body}")
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
Check the documentation here

This is how i get the title from remote messages:
var title = ""
override fun onMessageReceived(remoteMessage: RemoteMessage) {
if (remoteMessage.notification != null) {
title = remoteMessage.notification!!.title!!
}
}
val notificationBuilder = NotificationCompat.Builder(applicationContext, channelId)
.setContentTitle(title)

Related

Huawei Push Kit, payload sent does trigger onMessageReceive

Based on the documentation I follow here documentation
the payload I had sent does not trigger onMessageReceived method for me to parse it instead it automatically trigger notification by the Huawei notification center.
this is a sample payload I've sent, and I've already include foreground_show and set it to false as mention in the web:
{
"validate_only":false,
"message": {
"notification": {
"title": "message title",
"body": "message body"
},
"android": {
"notification": {
"foreground_show": false,
"click_action": {
"type": 3
}
}
},
"data":"{'param2':'value1','param3':'value2'}",
"token": [
"ABW18Q4Rw5CAB68f9yS_1f859k0s-t3G1aIZheq5l6TedFj_Iold4I6M2EK-pwPTzt6HXxL_"
]
}
}
the result was, it does not trigger onMessageReceive function but it automatically creates the notification on the device.
but if I remove notification and android from the payload and only sending data it successfully trigger onMessageReceive :
{
"validate_only": false,
"message": {
"data": "{'param1':'value1','param2':'value2'}",
"token": [
"ABW18Q4Rw5CAB68f9yS_1f859k0s-t3G1aIZheq5l6TedFj_Iold4I6M2EK-pwPTzt6HXxL_"
]
}
}
this is the class where I already override the onMessageReceived:
class CustomPushService : HmsMessageService() {
private val TAG = "PushTokenLog"
override fun onNewToken(token: String?, bundle: Bundle?) {
super.onNewToken(token, bundle)
Log.d(TAG, "receive token:$token")
}
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
Log.d(TAG, "onMessageReceived")
Log.d(TAG, "onMessageReceived:title:${remoteMessage?.notification?.title}")
super.onMessageReceived(remoteMessage)
}
}
I already include foreground_show: false and it wont trigger onMessageReceived unless if I only sending data in the payload then it will trigger onMessageReceived.
so is it not possible to send full payload as shown in the first payload and trigger onMessageReceived so that I can process the payload? and please let me know if my method wrong
In your request payload, you've set "message.android.notification.foreground_show” to “false”, which means your app is in the foreground and you will get the message data in the function onMessageReceived. Please double-check if your app is in the foreground.
Your device EMUI must be greater than EMUI 9.1.0, and Push SDK version must be greater than 4.0.
The class CustomPushService definition is good.
I used your 1st sample payload to test on my project. It worked very well. Please see below screenshot. The process entered into the function onMessageReceived as below.
Please refer to https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/android-server-dev-0000001050040110 and https://developer.huawei.com/consumer/en/doc/development/HMSCore-References/https-send-api-0000001050986197 for more information.
If you still have issues, please share logcat logs with me.

How to read the payload of a Firebase Cloud Messaging notification?

I am using Firebase Cloud Messaging to send data notifications to other users. I'm sending a json similar to this:
{
"message":{
"to":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification":{
"title":"Portugal vs. Denmark",
"body":"great match!"
},
"data" : {
"type" : "MSG",
"id" : "abcdefg123456...."
}
}
}
And this code to receive notifications:
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
remoteMessage.notification?.let { notificacao ->
//How to read payload?
enviarNotificacao(notificacao.title ?: "", notificacao.body ?: "")
}
}
How do I read the data contained in "id" and "type"?
The id and type are both inside a data payload, to be able to read these values then try the following:
override fun onMessageReceived(remoteMessage: RemoteMessage) {
Log.d(TAG, "From: ${remoteMessage.from}")
// Check if message contains a data payload.
remoteMessage.data.isNotEmpty().let {
Log.d(TAG, "Message data payload: " + remoteMessage.data)
}
// Check if message contains a notification payload.
remoteMessage.notification?.let {
Log.d(TAG, "Message Notification Body: ${it.body}")
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
remoteMessage.data will contain both the id and type
Check here for more info:
https://firebase.google.com/docs/cloud-messaging/android/receive
You can send data this way :
{
"to": "wOAT...",
"data": {
"title": "Notification title",
"message": "Notification message",
"key1" : "value1",
"key2" : "value2",
"key3" : "value3"
}
}
and fetch data this way :
MyFirebaseMessagingService
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(p0: RemoteMessage) {
val data = p0.data
val title = data["title"]
val message = data["message"]
val key1= data["value1"]
val key2= data["value2"]
val key3= data["value3"]
showNotification(title, message, ...)
}
}

remoteMessage.getNotification() is always null when notification is sent from server - Android

In my project, I need to send a notification from server to client. I am able to send notifications from FCM console but when I send a notification from server to client, remoteMessage.getNotification() always return null. While data is received correctly. When I send both data and notification only data is a non-null while the notification is null.
I already checked this question. But the solution isn't working for me.
Below is a snippet of client and server side code along with a screenshot while debugging client app.
Client App:(onMessageReceived)
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
super.onMessageReceived(remoteMessage)
Log.e(TAG, "From: " + remoteMessage?.from)
// Check if message contains a data payload.
if ((remoteMessage?.data?.size ?: 0) > 0) {
Log.e(TAG, "Message data payload: ${remoteMessage?.data}")
}
val a = remoteMessage?.notification
if (a != null) {
Log.e(TAG, "Message Notification Body: " + remoteMessage.notification?.body)
}
}
server side code(node.js)
var request = require('request');
// Set the headers
var headers = {
'Content-Type':'application/json',
'Authorization': 'key=AIzaSyAzMLMp....'
}
// Configure the request
var options = {
url: 'https://fcm.googleapis.com/fcm/send',
method: 'POST',
headers: headers,
form: {
"to": "eZoeSIRba6g:AP...",
"notification" : { "body" : "my body"} }
}
// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Print out the response body
console.log(body)
}
console.log(body + " error : " + error)
})
while if I use following part then the code works fine.
form: {
"to": "eZoeSIRba6g:APA91bEYrP...",
"data" : { "body" : "my body"} }
Screenshot while debugging the app.(Check value of variable 'a')
If someone has any idea of how to resolve this issue then please help me.
Thank you in advance.
{
"to" : "YOUR_FCM_TOKEN_WILL_BE_HERE",
"data" : {
"body" : "First Notification",
"title": "Collapsing A",
"key_1" : "Data for key one",
"key_2" : "Hellowww"
}
}
Use a JSON like this , then your onMessageReceived will be called.

FCM Status bar icon not showing

I am trying to add a white icon for push notifications sent via FCM admin. Per the guides here, I should be able to just add in the "icon" key and its corresponding URL to the notification. However, it is not working. My default app Icon gets used instead when the notification is received on my phone. Any idea why it's not working? Here is my code
var message = {
notification: {
title: "title here",
body: "body message here"
},
android: {
notification: {
"sound": "default",
"click_action": "FCM_PLUGIN_ACTIVITY",
"icon": "https://firebasestorage.googleapis.com/xxxxx"
}
},
data: {
tab: "message",
subsection: "notification"
},
token: registrationToken
};
// send the push notification
var sentMessage = admin.messaging().send(message)
.then(function (response) {
console.log("Successfully sent message: ", response);
})
.catch(function (error) {
console.log("Error sending message: ", error);
});

How to handle FCM upstream message in Node server?

I am using node-xcs module to create XMPP CCS server in NodeJs, But in that module there is no method to send ACK message which is required to send back to FCM.
do you use fcm-node package for get FCM token . using that we can register device look at my full coding i have use it for send notification to mobile
var FCM = require('fcm-node');
exports.SendNotification = function(msg,title,type,id,user_id,api_token)
{
var fcm = new FCM(constants.serverKey);
var message = {
registration_ids : api_token,
notification: {
title: title,
body:msg
},
data: {
type: type,
id:id,
user_id:user_id
}
};
fcm.send(message, function(err, response){
if (err)
{
console.log("Error for Send Notification",err);
return;
}
else
{
console.log("Successfully sent Notification", response);
return;
}
});
}
and than call this function like this
msg='new notification for you'
title='Hello'
id='34'
user_id='34'
result='api_token'//save this token in database and retrive using user_id
SendNotification(msg,title,'START_APPOINTMENT',id,user_id,result);

Categories

Resources