How to handle notification data payload while app is in background? - android

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>

Related

Getting a java.lang.numberformatexception invalid int null in android [duplicate]

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>

Android 7.1.1 Push Notification and FirebaseMessagingService not work

I am developing an app that works with FirebaseMessagingService and NotificationCompat. My target API is 26. The problem I have is that notifications in android 7.1.1 appear and close at once, they are not kept in the notification bar. However, in Android 7.0 it works perfectly. I saw many tutorials and in all they do the same thing that I do. I would like to know what I may be missing.
My Services
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
Map data = remoteMessage.getData();
if (SinchHelpers.isSinchPushPayload(data)) {
//comentario
} else {
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload => " + remoteMessage.getData());
Map<String, String> params = remoteMessage.getData();
JSONObject object = new JSONObject(params);
try {
sendNotification(object.get("message").toString(), object.get("chatId").toString(), object.get("user").toString());
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
scheduleJob();
} else {
// Handle message within 10 seconds
handleNow();
}
} catch (JSONException e) {
e.printStackTrace();
Log.d(TAG, "JSONException => " + e.getMessage());
}
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body => " + remoteMessage.getNotification().getBody());
}
}
}
}
private void sendNotification(String messageBody, String chatId, String userName) {
try {
Intent intent = new Intent(this, ChatActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXTRA_CHAT_ID", chatId);
intent.putExtra("EXTRA_USER", userName);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 , intent, PendingIntent.FLAG_ONE_SHOT);
String channelId = "fcm_default_channel";
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher_foreground)
.setContentTitle(userName)
.setContentText(messageBody)
.setAutoCancel(true)
.setGroup(userName)
.setSound(defaultSoundUri)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
} catch (Exception e) {
Log.e(TAG, "userName => " + userName + " => " + e.getMessage());
}
}
Notification channels: Android 8.0 introduces notification channels that allow you to create a user-customizable channel for each type of notification you want to display.
Please have a look at the documentation.
Build a notification.

Android/Firebase - Error while parsing timestamp in GCM event - Null timestamp

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>

Error when push notification by postman but not when send by Firebase console [duplicate]

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>

Firebase (FCM): open activity and pass data on notification click. android

There should be clear implementation of how to work with Firebase notification and data. I read many answers but can't seem to make it work. here are my steps:
1.) I am passing notification and data to android in PHP and it seems to be fine:
$msg = array
(
"body" => $body,
"title" => $title,
"sound" => "mySound"
);
$data = array
(
"user_id" => $res_id,
"date" => $date,
"hal_id" => $hal_id,
"M_view" => $M_view
);
$fields = array
(
'registration_ids' => $registrationIds,
'notification' => $msg,
'data' => $data
);
$headers = array
(
'Authorization: key='.API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
2.) when notification and data is received in Android it shows notification. When I click on this notification it opens app. But I can not figure out the way to handle the data when the app is opened. There are couple differences when app is in foreground and backround. The code that I have now is the following:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String user_id = "0";
String date = "0";
String cal_id = "0";
String M_view = "0";
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
user_id = remoteMessage.getData().get("user_id");
date = remoteMessage.getData().get("date");
hal_id = remoteMessage.getData().get("hal_id");
M_view = remoteMessage.getData().get("M_view");
}
//Calling method to generate notification
sendNotification(remoteMessage.getNotification().getBody(), user_id, date, hal_id, M_view);
}
private void sendNotification(String messageBody, String user_id, String date, String hal_id, String M_view) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("fcm_notification", "Y");
intent.putExtra("user_id", user_id);
intent.putExtra("date", date);
intent.putExtra("hal_id", hal_id);
intent.putExtra("M_view", M_view);
int uniqueInt = (int) (System.currentTimeMillis() & 0xff);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), uniqueInt, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setSmallIcon(R.drawable.ic_launcher)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}}
3.) When I use the code above and when I click on notification all it does it opens the app if in background. If app in foreground then on notification click it simply dismisses notification. However, I want to receive data and open specific Activity in both scenarios (background and foreground). I have in MainActivity the following code, but I am not able to get data. fcm_notification, date, hal_id returns null.
public class MainActivity extends Activity {
UserFunctions userFunctions;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
Intent intent_o = getIntent();
}
#Override
protected void onResume() {
super.onResume();
userFunctions = new UserFunctions();
if(userFunctions.isUserLoggedIn(getApplicationContext())){
Intent intent_o = getIntent();
String fcm_notification = intent_o.getStringExtra("fcm_notification") ;
String user_id = intent_o.getStringExtra("user_id");
String date = intent_o.getStringExtra("date");
String hal_id = intent_o.getStringExtra("hal_id");
String M_view = intent_o.getStringExtra("M_view");
Intent intent = new Intent(this, JobList.class);
// THIS RETURNS NULL, user_id = null
System.out.print("FCM" + user_id);
startActivity(intent);
finish();
}else{
// user is not logged in show login screen
Intent login = new Intent(this, LoginActivity.class);
startActivity(login);
// Closing dashboard screen
finish();
}
}}
IF anyone can direct or advice how can I retrieve data in MainActivity.java from Firebase in either scenario (foreground or background) that would be fantastic.
So first off, I'll put in the detail mentioned in the Handling Messages docs.
In the summary under the Both row, it shows that when the app is on foreground, the payload will be handled in your onMessageReceived().
In order to open the activity from onMessageReceived(), you should check if the data you need is in the payload, if it does, call your specific activity then pass all the other details you need via intent.
Now if the app is in background, it is mentioned in the docs that the notification is received by the Android system tray and that the data payload can be retrieved from the extras of the intent.
Just adding in the details from my answer here which pretty much just gives the docs statement and a link to a sample:
Handle notification messages in a backgrounded app
When your app is in the background, Android directs notification messages to the system tray. A user tap on the notification opens the app launcher by default.
This includes messages that contain both notification and data payload (and all messages sent from the Notifications console). In these cases, the notification is delivered to the device's system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.
I think this answer by #ArthurThompson explains it very well:
When you send a notification message with a data payload (notification and data) and the app is in the background you can retrieve the data from the extras of the intent that is launched as a result of the user tapping on the notification.
From the FCM sample which launches the MainActivity when the notification is tapped:
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
String value = getIntent().getExtras().getString(key);
Log.d(TAG, "Key: " + key + " Value: " + value);
}
}
After trying all the answers and blogs came up with solution. if anyone needs please use this video as reference
https://www.youtube.com/watch?v=hi8IPLNq59o
IN ADDITION to the video to add intents do in MyFirebaseMessagingService:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String user_id = "0";
String date = "0";
String hal_id = "0";
String M_view = "0";
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
user_id = remoteMessage.getData().get("user_id");
date = remoteMessage.getData().get("date");
cal_id = remoteMessage.getData().get("hal_id");
M_view = remoteMessage.getData().get("M_view");
}
String click_action = remoteMessage.getNotification().getClickAction();
//Calling method to generate notification
sendNotification(remoteMessage.getNotification().getBody(), remoteMessage.getNotification().getTitle(), user_id, date, hal_id, M_view, click_action);
}
private void sendNotification(String messageBody, String messageTitle, String user_id, String date, String hal_id, String M_view, String click_action) {
Intent intent = new Intent(click_action);
intent.putExtra("user_id", user_id);
intent.putExtra("date", date);
intent.putExtra("hal_id", hal_id);
intent.putExtra("M_view", M_view);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}}
and in new NotificationReceive activity in onCreate or onResume add this
notification_Y_N = (TextView) findViewById(R.id.notification_Y_N);
user_id_text = (TextView) findViewById(R.id.user_id_text);
Intent intent_o = getIntent();
String user_id = intent_o.getStringExtra("user_id");
String date = intent_o.getStringExtra("date");
String hal_id = intent_o.getStringExtra("hal_id");
String M_view = intent_o.getStringExtra("M_view");
notification_Y_N.setText(date);
user_id_text.setText(hal_id);
To invoke the onMessageReceived() method you will need to use another method to send notifications (like creating a Web API to send notifications). Then using it,
remove the notification payload from your FCM messages in order to have the data payload delivered to the onMessageReceived() method.
When your app is in the background, data payload is delivered to the onMessageReceived method only if there is no notification payload.
In case both payloads exist then system automatically handles the
notification part (system tray) and your app gets the data payload in
the extras of the intent of launcher Activity (after the user tap on
the notification).
For more info please refer to the following links:
Why is this happening? How to? How to handle push notifications?
Original answer by kws. Give him an upvote.
You don't need to implement sendNotification and onMessageReceived yourself.
When sending:
$data = array
(
"user_id" => $res_id
//whatever fields you want to include
);
$msg = array
(
"body" => $body,
"title" => $title,
"data" => $data
// more fields
);
android side (on your MainACtivity:
private void handleIntent(Intent intent) {
String user_id= intent.getStringExtra("user_id");
if(user_id!= null)
Log.d(TAG, user_id);
}
and of course:
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
handleIntent(intent);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handleIntent(getIntent());
}
whatever fields you put in data will be sent to your intent extra.
firstly, if you have data object and notification object in response . then ask the backend developer to remove notification object.
i hope my own class help .
public class MyFirebaseService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
Log.d(TAG, "Message data payload:id " + remoteMessage.getData().get("mode_id"));
sendNotification(remoteMessage.getData().get("body"),
remoteMessage.getData().get("mode_id"), remoteMessage.getData().get("click_action"));
}
}
private void sendNotification(String messageBody, String id, String clickAction) {
Intent intent = new Intent(clickAction);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntentWithParentStack(intent);
intent.putExtra("id", id);
intent.putExtra("body", messageBody);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "111")
.setSmallIcon(R.drawable.venus_logo)
.setContentText(messageBody)
.setAutoCancel(true)
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(pendingIntent)
.setLights(Color.GREEN, 3000, 3000);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel("111", "NOTIFICATION_CHANNEL_NAME", importance);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setShowBadge(false);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
assert notificationManager != null;
notificationBuilder.setChannelId("111");
notificationManager.createNotificationChannel(notificationChannel);
notificationManager.notify(0, notificationBuilder.build());
} else {
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(0, notificationBuilder.build());
}
}
}
then add this to your manifest file .
<service
android:name=".data.services.MyFirebaseService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<activity
android:name=".ui.notifications.NotificationsDetailsActivity"
android:excludeFromRecents="true"
android:launchMode="singleTask"
android:parentActivityName=".ui.home.HomeActivity"
android:taskAffinity="">
<intent-filter>
<action android:name="co.example.yourApp.ui.notifications_TARGET_NOTIFICATION" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Firebase documentation has a great table to explain how it works
https://firebase.google.com/docs/cloud-messaging/android/receive#handling_messages
So if you have both data and notification and app is in a foreground when your receive it then you should create a notification by yourself in your service which extends FirebaseMessagingService (in onMessageReceived method)
In other case (app is in background) you can get your data from intent.extras of Activity, a notification will be created by a system to open main activity of the app

Categories

Resources