I'm building an Android app which will receive push notifications. I've got Firebase Cloud Messaging setup and pretty much working, such that I can send the following payload to a valid token and the notification and data are received.
Using url https://fcm.googleapis.com/fcm/send
{
"to":"<valid-token>",
"notification":{"body":"BODY TEXT","title":"TITLE TEXT","sound":"default"},
"data":{"message":"This is some data"}
}
My app receives it correctly and can deal with it.
The only slight wrinkle is that I get the following exception thrown in the debug:
Error while parsing timestamp in GCM event
java.lang.NumberFormatException: Invalid int: "null"
at java.lang.Integer.invalidInt(Integer.java:138)
...
It doesn't crash the app, it just looks untidy.
I've tried adding a timestamp item to the main payload, the notification, the data, and also tried variations such as time but can't seem to get rid of the exception (and google as I might, I can't find an answer).
How do I pass the timestamp so it stops complaining?
Edited: Here is my onMessageReceived method, but I think the exception is thrown before it gets here
#Override
public void onMessageReceived(RemoteMessage 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());
//TODO Handle the data
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
}
Thanks in advance,
Chris
Even though notification is apparently a supported element (according to the Firebase web docs), the only way I could get rid of the exception was to remove it entirely, and use the data section only, and then in my app create a notification (rather than letting firebase do the notification).
I used this site to work out how to raise the notifications: https://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/
My notification now looks like the following:
$fields = array("to" => "<valid-token>",
"data" => array("data"=>
array(
"message"=>"This is some data",
"title"=>"This is the title",
"is_background"=>false,
"payload"=>array("my-data-item"=>"my-data-value"),
"timestamp"=>date('Y-m-d G:i:s')
)
)
);
...
<curl stuff here>
...
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
My onMessageReceived looks like this:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
// 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());
}
}
}
which calls handleDataMessage which looks like this:
private void handleDataMessage(JSONObject json) {
Log.e(TAG, "push json: " + json.toString());
try {
JSONObject data = json.getJSONObject("data");
String title = data.getString("title");
String message = data.getString("message");
boolean isBackground = data.getBoolean("is_background");
String timestamp = data.getString("timestamp");
JSONObject payload = data.getJSONObject("payload");
// play notification sound
NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
notificationUtils.playNotificationSound();
if (!NotificationUtils.isBackgroundRunning(getApplicationContext())) {
// app is in foreground, broadcast the push message
Intent pushNotification = new Intent(ntcAppManager.PUSH_NOTIFICATION);
pushNotification.putExtra("message", message);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
} else {
// app is in background, show the notification in notification tray
Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
resultIntent.putExtra("message", message);
showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent);
}
} catch (JSONException e) {
Log.e(TAG, "Json Exception: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
this then calls showNotificationMessage
/**
* Showing notification with text only
*/
private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) {
notificationUtils = new NotificationUtils(context);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
notificationUtils.showNotificationMessage(title, message, timeStamp, intent);
}
And subsequently notificationUtils.showNotificationMessage
public void showNotificationMessage(String title, String message, String timeStamp, Intent intent) {
showNotificationMessage(title, message, timeStamp, intent, null);
}
public void showNotificationMessage(final String title, final String message, final String timeStamp, Intent intent, String imageUrl) {
// Check for empty push message
if (TextUtils.isEmpty(message))
return;
// notification icon
final int icon = R.mipmap.ic_launcher;
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
final PendingIntent resultPendingIntent =
PendingIntent.getActivity(
mContext,
0,
intent,
PendingIntent.FLAG_CANCEL_CURRENT
);
final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
mContext);
final Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
+ "://" + mContext.getPackageName() + "/raw/notification");
showSmallNotification(mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);
playNotificationSound();
}
private void showSmallNotification(NotificationCompat.Builder mBuilder, int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) {
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.addLine(message);
Notification notification;
notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
.setAutoCancel(true)
.setContentTitle(title)
.setContentIntent(resultPendingIntent)
.setSound(alarmSound)
.setStyle(inboxStyle)
.setWhen(getTimeMilliSec(timeStamp))
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
.setContentText(message)
.build();
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(ntcAppManager.NOTIFICATION_ID, notification);
}
More detail in the link above, and it's a lot of handling but at least the exception's gone and I'm in control of the notifications.
I've updated com.google.firebase:firebase-messaging to 17.3.4 and issue disappeared.
I was running into this same error, I resolved by adding a ttl value to the payload.
{
"to":"<valid-token>",
"notification":{"body":"BODY TEXT","title":"TITLE TEXT","sound":"default"},
"data":{"message":"This is some data"},
"ttl": 3600
}
I had the same problem, I've just set "body" parameter in notification and error dissapeared.
What worked for me:
Upgrading, not only firebase-messaging, but all Firebase libraries to the last version. In android/app/build.gradle:
dependencies {
implementation "com.google.firebase:firebase-core:16.0.0" // upgraded
implementation "com.google.firebase:firebase-analytics:16.0.0" // upgraded
implementation 'com.google.firebase:firebase-messaging:17.3.4' // upgraded
// ...
implementation "com.google.firebase:firebase-invites:16.0.0" // upgraded
// ...
}
Not all of them are at version 17.x
Format below (no notification body, nor are there any arrays) fixed the timestamp exception for me:
{
"to": "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
"data": {
"message": "message",
"title": "hello",
}
}
Tested fine with http://pushtry.com/
The only reason I included the long 'eeee...' is that is the exact size of my token.
replace
"notification" : {
"title" : "title !",
"body" : "body !",
"sound" : "default"
},
"condition" : "'xxx' in topics",
"priority" : "high",
"data" : {
....
by (remove notification) :
{
"condition" : "'xxxx' in topics",
"priority" : "high",
"data" : {
"title" : "title ! ",
"body" : "BODY",
......
}
And on you code :
Replace :
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
remoteMessage.getNotification().getTitle();
remoteMessage.getNotification().getBody();
}
by
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
remoteMessage.getData().get("title");
remoteMessage.getData().get("body");
}
In my case My error was "AndrodManifest.xml"
I miss one service (actually Android studio's firebase assistant is missing my permission. :) )
original
<service android:name=".fcm.MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
</application>
solution
<service android:name=".fcm.MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service android:name=".fcm.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
Related
Here is my MyFirebaseMessagingService.class
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public MyFirebaseMessagingService() { }
DataBaseUtil dataBaseUtil = null;
String sname;
Intent intent= new Intent();
String orderId;
String strmessage,strmsgtext;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
dataBaseUtil = new DataBaseUtil();
if (remoteMessage.getNotification() != null) {
L.e( "Message Notification Body: " + remoteMessage.getNotification().getBody());
RemoteMessage.Notification fcm = remoteMessage.getNotification();
PojoNotification pojo = new PojoNotification();
pojo.setTitle(fcm.getTitle());
pojo.setContent(fcm.getBody());
Map<String, String> dataMap = remoteMessage.getData();
orderId = dataMap.get("orderId").toString().trim();
sname = dataMap.get("screen_name").toString().trim();
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}
pojo.setId(new Random().nextInt(9000));
dataBaseUtil.insertNotification(pojo);
if (SP.getBoolean(SP.LOGIN) ){
showNotification(pojo);
}
else {
}
}else {
L.e( "Message Notification Body: " + "abcv");
}
}
And here is my showNotification method:
void showNotification(PojoNotification pojo) {
intent= new Intent(getApplicationContext(),MainActivity.class);
intent.putExtra("screen_name", sname);
// intent.putExtra(Constance.id,pojo.getId());
PendingIntent pendingIntent = PendingIntent.getActivity(this,0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("default",
"SGrip",
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("YOUR_NOTIFICATION_CHANNEL_DISCRIPTION");
mNotificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(), "default")
.setSmallIcon(R.mipmap.ic_launcher) // notification icon
.setContentTitle(pojo.getTitle()) // title for notification
.setContentText(pojo.getContent())// message for notification
// .setSound(alarmSound) // set alarm sound for notification
.setAutoCancel(true); // clear notification after click
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pi);
mNotificationManager.notify(0, mBuilder.build());
}
Here i am getting all the notification background and foreground but the problem i am facing is that when my app is in background the data payload data is not fetching and when my app is foreground all data are getting as required
Here, my launcher activity were i get intent extra
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
String value = getIntent().getExtras().getString(key);
Log.d(TAG, "Key: " + key + " Value: " + value);
}
}
and here is the notification code server side
{
"registration_ids" : ["cFxiduH5j9I:APA91bEFAYPOR57yDga8urRuhmPuj_CI9h-bIyEwCcQeyFsvnFU_Nh9zkTmQVE7oiwdXchvIIz4DmUW1nqIOslBg_3oV7cWDZBjwb7WFqQ3E4RZ2T2vXCFN6IQ_1pBIfL67pHwthEZA4"],
"notification" : {
"title" : "First Notification",
"text": "Collapsing A",
"sound":"default"
},
"data" : {
"screen_name" : "acc_screen"
}
}
I read many tutorials many stackoverflow Q&A but nothing helping me out. i know the same type of questions are many but am not getting the solution from there so i posted the question.
When your app is in background, intent caught in Launcher activity.
I implemented the same in Kotlin, please refer:
val bundle = intent.extras
if (bundle != null) {
val notificationModel = NotificationModel()
try {
val target = Target()
if (bundle.containsKey("view"))
target.view = bundle.getString("view")
if (bundle.containsKey("circle_id"))
target.circleId = bundle.getString("circle_id")
if (bundle.containsKey("user_id"))
target.userId = bundle.getString("user_id")
if (bundle.containsKey("group_id"))
target.groupId = bundle.getString("group_id")
if (bundle.containsKey("file_id"))
target.fileId = bundle.getString("file_id")
notificationModel.target = target
} catch (ex: JSONException) {
ex.printStackTrace()
}
}
Updated
When your app is in background and click on your notification your default launcher will be launched. To launch your desired activity you need to specify click_action in your notification payload.
$noti = array
(
'icon' => 'new',
'title' => 'title',
'body' => 'new msg',
'click_action' => 'your activity name comes here'
);
And in your android.manifest file
Add the following code where you registered your activity
<activity
android:name="your activity name">
<intent-filter>
<action android:name="your activity name" />
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
I'm building an Android app which will receive push notifications. I've got Firebase Cloud Messaging setup and pretty much working, such that I can send the following payload to a valid token and the notification and data are received.
Using url https://fcm.googleapis.com/fcm/send
{
"to":"<valid-token>",
"notification":{"body":"BODY TEXT","title":"TITLE TEXT","sound":"default"},
"data":{"message":"This is some data"}
}
My app receives it correctly and can deal with it.
The only slight wrinkle is that I get the following exception thrown in the debug:
Error while parsing timestamp in GCM event
java.lang.NumberFormatException: Invalid int: "null"
at java.lang.Integer.invalidInt(Integer.java:138)
...
It doesn't crash the app, it just looks untidy.
I've tried adding a timestamp item to the main payload, the notification, the data, and also tried variations such as time but can't seem to get rid of the exception (and google as I might, I can't find an answer).
How do I pass the timestamp so it stops complaining?
Edited: Here is my onMessageReceived method, but I think the exception is thrown before it gets here
#Override
public void onMessageReceived(RemoteMessage 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());
//TODO Handle the data
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
}
Thanks in advance,
Chris
Even though notification is apparently a supported element (according to the Firebase web docs), the only way I could get rid of the exception was to remove it entirely, and use the data section only, and then in my app create a notification (rather than letting firebase do the notification).
I used this site to work out how to raise the notifications: https://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/
My notification now looks like the following:
$fields = array("to" => "<valid-token>",
"data" => array("data"=>
array(
"message"=>"This is some data",
"title"=>"This is the title",
"is_background"=>false,
"payload"=>array("my-data-item"=>"my-data-value"),
"timestamp"=>date('Y-m-d G:i:s')
)
)
);
...
<curl stuff here>
...
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
My onMessageReceived looks like this:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
// 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());
}
}
}
which calls handleDataMessage which looks like this:
private void handleDataMessage(JSONObject json) {
Log.e(TAG, "push json: " + json.toString());
try {
JSONObject data = json.getJSONObject("data");
String title = data.getString("title");
String message = data.getString("message");
boolean isBackground = data.getBoolean("is_background");
String timestamp = data.getString("timestamp");
JSONObject payload = data.getJSONObject("payload");
// play notification sound
NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
notificationUtils.playNotificationSound();
if (!NotificationUtils.isBackgroundRunning(getApplicationContext())) {
// app is in foreground, broadcast the push message
Intent pushNotification = new Intent(ntcAppManager.PUSH_NOTIFICATION);
pushNotification.putExtra("message", message);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
} else {
// app is in background, show the notification in notification tray
Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
resultIntent.putExtra("message", message);
showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent);
}
} catch (JSONException e) {
Log.e(TAG, "Json Exception: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
this then calls showNotificationMessage
/**
* Showing notification with text only
*/
private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) {
notificationUtils = new NotificationUtils(context);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
notificationUtils.showNotificationMessage(title, message, timeStamp, intent);
}
And subsequently notificationUtils.showNotificationMessage
public void showNotificationMessage(String title, String message, String timeStamp, Intent intent) {
showNotificationMessage(title, message, timeStamp, intent, null);
}
public void showNotificationMessage(final String title, final String message, final String timeStamp, Intent intent, String imageUrl) {
// Check for empty push message
if (TextUtils.isEmpty(message))
return;
// notification icon
final int icon = R.mipmap.ic_launcher;
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
final PendingIntent resultPendingIntent =
PendingIntent.getActivity(
mContext,
0,
intent,
PendingIntent.FLAG_CANCEL_CURRENT
);
final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
mContext);
final Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
+ "://" + mContext.getPackageName() + "/raw/notification");
showSmallNotification(mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);
playNotificationSound();
}
private void showSmallNotification(NotificationCompat.Builder mBuilder, int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) {
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.addLine(message);
Notification notification;
notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
.setAutoCancel(true)
.setContentTitle(title)
.setContentIntent(resultPendingIntent)
.setSound(alarmSound)
.setStyle(inboxStyle)
.setWhen(getTimeMilliSec(timeStamp))
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
.setContentText(message)
.build();
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(ntcAppManager.NOTIFICATION_ID, notification);
}
More detail in the link above, and it's a lot of handling but at least the exception's gone and I'm in control of the notifications.
I've updated com.google.firebase:firebase-messaging to 17.3.4 and issue disappeared.
I was running into this same error, I resolved by adding a ttl value to the payload.
{
"to":"<valid-token>",
"notification":{"body":"BODY TEXT","title":"TITLE TEXT","sound":"default"},
"data":{"message":"This is some data"},
"ttl": 3600
}
I had the same problem, I've just set "body" parameter in notification and error dissapeared.
What worked for me:
Upgrading, not only firebase-messaging, but all Firebase libraries to the last version. In android/app/build.gradle:
dependencies {
implementation "com.google.firebase:firebase-core:16.0.0" // upgraded
implementation "com.google.firebase:firebase-analytics:16.0.0" // upgraded
implementation 'com.google.firebase:firebase-messaging:17.3.4' // upgraded
// ...
implementation "com.google.firebase:firebase-invites:16.0.0" // upgraded
// ...
}
Not all of them are at version 17.x
Format below (no notification body, nor are there any arrays) fixed the timestamp exception for me:
{
"to": "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
"data": {
"message": "message",
"title": "hello",
}
}
Tested fine with http://pushtry.com/
The only reason I included the long 'eeee...' is that is the exact size of my token.
replace
"notification" : {
"title" : "title !",
"body" : "body !",
"sound" : "default"
},
"condition" : "'xxx' in topics",
"priority" : "high",
"data" : {
....
by (remove notification) :
{
"condition" : "'xxxx' in topics",
"priority" : "high",
"data" : {
"title" : "title ! ",
"body" : "BODY",
......
}
And on you code :
Replace :
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
remoteMessage.getNotification().getTitle();
remoteMessage.getNotification().getBody();
}
by
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
remoteMessage.getData().get("title");
remoteMessage.getData().get("body");
}
In my case My error was "AndrodManifest.xml"
I miss one service (actually Android studio's firebase assistant is missing my permission. :) )
original
<service android:name=".fcm.MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
</application>
solution
<service android:name=".fcm.MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service android:name=".fcm.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
I'm building an Android app which will receive push notifications. I've got Firebase Cloud Messaging setup and pretty much working, such that I can send the following payload to a valid token and the notification and data are received.
Using url https://fcm.googleapis.com/fcm/send
{
"to":"<valid-token>",
"notification":{"body":"BODY TEXT","title":"TITLE TEXT","sound":"default"},
"data":{"message":"This is some data"}
}
My app receives it correctly and can deal with it.
The only slight wrinkle is that I get the following exception thrown in the debug:
Error while parsing timestamp in GCM event
java.lang.NumberFormatException: Invalid int: "null"
at java.lang.Integer.invalidInt(Integer.java:138)
...
It doesn't crash the app, it just looks untidy.
I've tried adding a timestamp item to the main payload, the notification, the data, and also tried variations such as time but can't seem to get rid of the exception (and google as I might, I can't find an answer).
How do I pass the timestamp so it stops complaining?
Edited: Here is my onMessageReceived method, but I think the exception is thrown before it gets here
#Override
public void onMessageReceived(RemoteMessage 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());
//TODO Handle the data
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
}
Thanks in advance,
Chris
Even though notification is apparently a supported element (according to the Firebase web docs), the only way I could get rid of the exception was to remove it entirely, and use the data section only, and then in my app create a notification (rather than letting firebase do the notification).
I used this site to work out how to raise the notifications: https://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/
My notification now looks like the following:
$fields = array("to" => "<valid-token>",
"data" => array("data"=>
array(
"message"=>"This is some data",
"title"=>"This is the title",
"is_background"=>false,
"payload"=>array("my-data-item"=>"my-data-value"),
"timestamp"=>date('Y-m-d G:i:s')
)
)
);
...
<curl stuff here>
...
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
My onMessageReceived looks like this:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
// 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());
}
}
}
which calls handleDataMessage which looks like this:
private void handleDataMessage(JSONObject json) {
Log.e(TAG, "push json: " + json.toString());
try {
JSONObject data = json.getJSONObject("data");
String title = data.getString("title");
String message = data.getString("message");
boolean isBackground = data.getBoolean("is_background");
String timestamp = data.getString("timestamp");
JSONObject payload = data.getJSONObject("payload");
// play notification sound
NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
notificationUtils.playNotificationSound();
if (!NotificationUtils.isBackgroundRunning(getApplicationContext())) {
// app is in foreground, broadcast the push message
Intent pushNotification = new Intent(ntcAppManager.PUSH_NOTIFICATION);
pushNotification.putExtra("message", message);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
} else {
// app is in background, show the notification in notification tray
Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
resultIntent.putExtra("message", message);
showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent);
}
} catch (JSONException e) {
Log.e(TAG, "Json Exception: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
this then calls showNotificationMessage
/**
* Showing notification with text only
*/
private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) {
notificationUtils = new NotificationUtils(context);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
notificationUtils.showNotificationMessage(title, message, timeStamp, intent);
}
And subsequently notificationUtils.showNotificationMessage
public void showNotificationMessage(String title, String message, String timeStamp, Intent intent) {
showNotificationMessage(title, message, timeStamp, intent, null);
}
public void showNotificationMessage(final String title, final String message, final String timeStamp, Intent intent, String imageUrl) {
// Check for empty push message
if (TextUtils.isEmpty(message))
return;
// notification icon
final int icon = R.mipmap.ic_launcher;
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
final PendingIntent resultPendingIntent =
PendingIntent.getActivity(
mContext,
0,
intent,
PendingIntent.FLAG_CANCEL_CURRENT
);
final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
mContext);
final Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
+ "://" + mContext.getPackageName() + "/raw/notification");
showSmallNotification(mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);
playNotificationSound();
}
private void showSmallNotification(NotificationCompat.Builder mBuilder, int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) {
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.addLine(message);
Notification notification;
notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
.setAutoCancel(true)
.setContentTitle(title)
.setContentIntent(resultPendingIntent)
.setSound(alarmSound)
.setStyle(inboxStyle)
.setWhen(getTimeMilliSec(timeStamp))
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
.setContentText(message)
.build();
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(ntcAppManager.NOTIFICATION_ID, notification);
}
More detail in the link above, and it's a lot of handling but at least the exception's gone and I'm in control of the notifications.
I've updated com.google.firebase:firebase-messaging to 17.3.4 and issue disappeared.
I was running into this same error, I resolved by adding a ttl value to the payload.
{
"to":"<valid-token>",
"notification":{"body":"BODY TEXT","title":"TITLE TEXT","sound":"default"},
"data":{"message":"This is some data"},
"ttl": 3600
}
I had the same problem, I've just set "body" parameter in notification and error dissapeared.
What worked for me:
Upgrading, not only firebase-messaging, but all Firebase libraries to the last version. In android/app/build.gradle:
dependencies {
implementation "com.google.firebase:firebase-core:16.0.0" // upgraded
implementation "com.google.firebase:firebase-analytics:16.0.0" // upgraded
implementation 'com.google.firebase:firebase-messaging:17.3.4' // upgraded
// ...
implementation "com.google.firebase:firebase-invites:16.0.0" // upgraded
// ...
}
Not all of them are at version 17.x
Format below (no notification body, nor are there any arrays) fixed the timestamp exception for me:
{
"to": "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
"data": {
"message": "message",
"title": "hello",
}
}
Tested fine with http://pushtry.com/
The only reason I included the long 'eeee...' is that is the exact size of my token.
replace
"notification" : {
"title" : "title !",
"body" : "body !",
"sound" : "default"
},
"condition" : "'xxx' in topics",
"priority" : "high",
"data" : {
....
by (remove notification) :
{
"condition" : "'xxxx' in topics",
"priority" : "high",
"data" : {
"title" : "title ! ",
"body" : "BODY",
......
}
And on you code :
Replace :
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
remoteMessage.getNotification().getTitle();
remoteMessage.getNotification().getBody();
}
by
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
remoteMessage.getData().get("title");
remoteMessage.getData().get("body");
}
In my case My error was "AndrodManifest.xml"
I miss one service (actually Android studio's firebase assistant is missing my permission. :) )
original
<service android:name=".fcm.MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
</application>
solution
<service android:name=".fcm.MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service android:name=".fcm.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
I have created and setup Firebase console completely as Google tutorial mentioned. I have implemented Services in my project as well. While I am sending the message from Firebase console it is not receiving in my app. When I am trying to send using the single device then it is showing "Unregistered registration token".
Here is my MyFirebaseInstanceIDService:
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
#Override
public void onTokenRefresh() {
//Getting registration token
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
System.out.println("TOKEN::" + refreshedToken);
//Displaying token on logcat
SmartApplication.REF_SMART_APPLICATION.writeSharedPreferences("regId", refreshedToken);
// SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
// SharedPreferences.Editor editor = pref.edit();
// editor.putString("regId", refreshedToken);
// editor.commit();
}
}
Here is my MyFirebaseMessagingService:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
private static int count = 0;
String TYPE = "type";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//Displaying data in log
//It is optional
System.out.println("data getting");
Log.d(TAG, "Notification Message TITLE: " + remoteMessage.getNotification().getTitle());
Log.d(TAG, "Notification Message BODY: " + remoteMessage.getNotification().getBody());
Log.d(TAG, "Notification Message DATA: " + remoteMessage.getData().toString());
//Calling method to generate notification
//remoteMessage.getNotification().getBody()
sendNotification(remoteMessage.getNotification().getTitle(),
remoteMessage.getNotification().getBody(), remoteMessage.getData());
}
//This method is only generating push notification
//It is same as we did in earlier posts
private void sendNotification(String messageTitle, String messageBody, Map<String, String> row) {
PendingIntent contentIntent = null;
try {
Intent groupDetailIntent = new Intent(this, UnanimousHomeActivity.class);
contentIntent = PendingIntent.getActivity(this, (int) (Math.random() * 100),
groupDetailIntent, PendingIntent.FLAG_UPDATE_CURRENT);
} catch (Exception e) {
e.printStackTrace();
}
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(contentIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(count, notificationBuilder.build());
count++;
}
}
I have stucked since 4 days, please someone help me out as no logical problem found here, some unusual things are happening while integration push.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.e(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.e(TAG, "Message data: " + remoteMessage.getData().toString());
}
if (remoteMessage.getNotification() != null) {
Log.e(TAG, "Message data: " + remoteMessage.getData().toString());
sendnotification(remoteMessage.getNotification().getBody());
}
}
private void sendnotification(String body) {
Intent intent = new Intent(this,MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
Uri notificationsound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Emoji Keyboard")
.setDefaults(-1)
.setContentText(body)
.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
.setSound(notificationsound)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0,notificationBuilder.build());
}
}
and after this in manifests add this:
<!-- Firebase Notifications -->
<service android:name=".services.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".services.MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<!-- ./Firebase Notifications -->
After you've successfully obtained the token, make sure that you've send it correctly to your server.
Try the recommended action for Invalid Registration Token:
Check the format of the registration token you pass to the server. Make sure it matches the registration token the client app receives from registering with Firebase Notifications. Do not truncate or add additional characters.
For more information, see this documentation.
Code is working Fine in my application
Add googleservices-json file in app folder created from firebase and
add services in manifest
<service
android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<service
android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
I am making a simple messaging app using firebase cloud messaging service but and I am using cloud functions to handle the notifications, however whenever I test it it always says successful in the logs but the devices receive nothing
Here is the cloud function used :
exports.sendNotifications = functions.database.ref('/meesages/{messageId}').onCreate(event => {
var eventSnapshot = event.data;
var str1 = "Sender : ";
var str = str1.concat(eventSnapshot.child("messageOwner").val());
console.log(str);
var topic = "Messaging";
var payload = {
notification: {
Message: eventSnapshot.child("messageText").val(),
Sender: eventSnapshot.child("messageOwner").val()
}
};
// Send a message to devices subscribed to the provided topic.
return admin.messaging().sendToTopic(topic,payload)
.then(function (response) {
// See the MessagingTopicResponse reference documentation for the
// contents of response.
console.log("Successfully sent message:", response);
})
.catch(function (error) {
console.log("Error sending message:", error);
});
});
Here is the class responsible for handling the notifications part on the android device :
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
showNotification(remoteMessage.getData().get("Sender"), remoteMessage.getData().get("Message"));
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
}
#Override
public void onDeletedMessages() {
super.onDeletedMessages();
}
private void showNotification(String Message, String Sender) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setContentTitle("New message : " + Message)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText("By : " + Sender)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
and yes I made sure to add the topic subscription in the mainactivity class
FirebaseMessaging.getInstance().subscribeToTopic("Messaging");
so what is exactly wrong here ??
The code in onMessageReceived() expects the message to have a data payload. This is explained in the documentation, which includes three tabs, showing notification, data, and combined payloads. Change notification to data:
var payload = {
data: {
Message: eventSnapshot.child("messageText").val(),
Sender: eventSnapshot.child("messageOwner").val()
}
};