Related
On the Android app, I need to open a specific activity on clicking push notification. I am directly sending the message from the firebase FCM console. I Did the configuration below, with some condition to open different activities. It is working properly while the app is in the foreground.
While the app is in the foreground, on clicking the received notification, it opens the corresponding activity based on given condition. Everything working fine.
But while the app is in the background, on clicking push notification, it opens the main activity. Also, the message showing is the message I gave in the Notification payload of FCM(Not that given in data payload/Additional section of FCM console).
I need app to open specific activity on clicking push notification while the app is in the background as well.
Can't I do this from the FCM console directly?
please advise
public class MyFireBaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
private static int count = 0;
#Override
public void onNewToken(#NonNull String s) {
super.onNewToken(s);
Log.e(TAG, "onNewToken: " + s);
}
#Override
public void onMessageReceived(#NonNull RemoteMessage remoteMessage) {
Map<String,String> opendata = remoteMessage.getData();
String actionValue = opendata.get("openactivity");
Intent intent=new Intent();
assert actionValue != null;
switch (actionValue) {
case "Activity1":
intent = new Intent(this, Activity1.class);
break;
case "Activity2":
intent = new Intent(this, Activity2.class);
break;
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("pushnotification","True");
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationManager mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel mChannel = new NotificationChannel("MyID", "Myapp", importance);
mChannel.setDescription(remoteMessage.getData().get("message"));
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
mChannel.enableVibration(true);
mNotifyManager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "MyID");
mBuilder.setContentTitle(remoteMessage.getData().get("title"))
.setContentText(remoteMessage.getData().get("message"))
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.maft_logo))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setColor(Color.parseColor("#FFD600"))
.setContentIntent(pendingIntent)
.setChannelId("Myid")
.setPriority(NotificationCompat.PRIORITY_LOW);
mNotifyManager.notify(count, mBuilder.build());
count++;
}
}
Manifest
<service
android:name=".MyFireBaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
If notification clicks on app background state, then that will open app launcher activity. In launcher activity you need to check if there is any pending intent from notification and execute that.
Try this in your launcher activity(MainActivity).
Intent intent=new Intent();
Intent fromIntent = getIntent();
if (fromIntent.getExtras()!=null){
try {
Map<String,String> opendata = remoteMessage.getData();
String actionValue = opendata.get("openactivity");
switch (actionValue){
case "Activity1":
intent=new Intent(this, Activity1.class);
break;
case "Activity2":
intent=new Intent(this, Activity2.class);
break;
default:
intent = new Intent(MainActivity.this, DefaultActivity.class);
break
}
} catch(Exception e){
intent = new Intent(MainActivity.this, DefaultActivity.class);
}
} else{
intent = new Intent(MainActivity.this, DefaultActivity.class);
}
startActivity(intent);
when your app in background, the method onMessageReceived never invoked, system notification auto show on your notification tray instead, so you need implement some logic (same in onMessageReceived method) in your main activity to navigate user to the destination screen.
There are two type of notification :
Data message notification other one is
Normal notification
In Data message notification send from server, when your app is kill then we got payload in onMessageReceive method.
But in case of Notification fire from other like console and your app is kill then you got default notification there is no callback in onMessageReceive method.
For testing you can set log in your onMessageReceive method but your log not print, when your app is kill and you fire notification from console, but with server because of data message
you got callback in onMessageReceive.
In your case everything working fine, you have to try with actual server.
I recently discovered that almost everything about the notification is managed by the cloud messaging function. You don't need to create a NotificationManager inside the onMessageReceived. The function presets the title & body. It can also set the activity to be opened when the notification is clicked.
You just need to include the payload parameter "click_action" that is sent alongside the notification. Your payload needs to look something like this:
return admin.messaging().sendToTopic(
topicId,
{
notification: {
title: "Custom title",
body: "Custom body",
click_action: "DestinationActivity"
},
data: {
"payload": myPayload
}
}
More on cloud functions here.
Now move to your project's Manifest and find the destination activity. Make the following changes (make sure to set the exported attribute to true):
<activity
android:name="DestinationActivity"
android:exported="true">
<intent-filter>
<action android:name="DestinationActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
The intent filter picks the click_action parameter from the payload so any notification with "DestinationActivity" as its click action shall be handled by the Destination activity. I am starting to think that one doesn't even need to override the onMessageReceived method. FCM makes it really convenient.
I'm having a problem using the FCM Push Notification Messaging Service, as I've overridden the handleIntent() method to receive the notification when the app is in the foreground. I am also using the onMessageReceived() method.
But when the app is in the background, I will receive 2 notifications, which one of them only opens up the app and runs the MainActivity while the other is opening up the app how I want it to.
FYI: The notification I receive when I am in the foreground is exactly how I want it to open.
This is the code I've written below :
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private final String NOTIFICATION_TYPE = "type";
private final String NOTIFICATION_ID = "id";
private final String NOTIFICATION_TYPE_PRODUCT_DETAIL = "productdetail";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String title = remoteMessage.getNotification().getTitle();R
String body = remoteMessage.getNotification().getBody();
String token = remoteMessage.getFrom();
Log.d("FireBase TAG: ", token);
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d("FireBaseMessageService","FireBase Data payload : " + remoteMessage.getData());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
}
#Override
public void handleIntent(Intent intent) {
super.handleIntent(intent);
String type = intent.getExtras().getString(NOTIFICATION_TYPE, "");
int id = 0;
try {
id = Integer.valueOf(intent.getExtras().getString(NOTIFICATION_ID, ""));
} catch (NumberFormatException e) {
e.printStackTrace();
}
//Intents
Intent mainIntent = MainActivity.newIntent(this);
Intent editProfileIntent = EditProfileActivity.newIntent(this);
Intent settingsIntent = SettingsActivity.newIntent(this);
Intent productIntent = ProductActivity.newNotificationIntent(this, id, false, true);
if (UserManager.getSingleton().isUserLoggedIn(getApplicationContext())) {
PendingIntent pendingIntent;
if (type.equalsIgnoreCase(NOTIFICATION_TYPE_PRODUCT_DETAIL)) {
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(mainIntent);
stackBuilder.addNextIntent(productIntent);
editProfileIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_ONE_SHOT);
}
else {
pendingIntent = PendingIntent.getActivity(this, 0, productIntent,
PendingIntent.FLAG_ONE_SHOT);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(intent.getExtras().getString("gcm.notification.title"))
.setContentText(intent.getExtras().getString("gcm.notification.body"))
.setDefaults(NotificationCompat.DEFAULT_VIBRATE)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setContentIntent(pendingIntent);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
}
}
I have deleted the NotificationCompat.Builder from the onMessageReceived() method.
But I am still receiving two notifications in the background.
App Gradle :
compile 'com.google.firebase:firebase-core:11.4.2' //Firebase
compile 'com.google.firebase:firebase-messaging:11.4.2' //Firebase Cloud Messaging
I've tried searching for a solution online but unluckily there isn't a solution pointing to Android.
You are handling your Notification stuff into handleIntent(Intent intent). You should probably remove super.handleIntent(intent); to prevent the Firebase system to handle notification while the app is in background.
Solution: remove super.handleIntent(intent);
Just make a sendnotification() method and set whatever parameters you want to pass like body i.e sendnotification(String body). Use pending intent to start you activity and when you click on notification your app parse the data to the launcher activity which is defined in manifest, so once you have data in your launcher activity you can send data to other activity using intent.
I think the .setContentText("") is getting called more than 1 times and are you getting same notification two times?
The notification which works perfectly is generated by your code but when your application is not in foreground android system will generate the notification for you. In this case when you don't have the control to send data in your intent that you were sending to open your desired Activity.
In this case, you have to do some modification on your servers payload. You have to add click_action in your payload, this is how android system will identify the destination activity.
Payload Example:
{ "notification": {
"title":"Notification title",
"body":"Notification body",
"click_action":"<Your_destination_activity>",
}, "data":{
"param1":"value1",
"param2":"value2"
},
"priority":"high",
}
Reference:
https://firebase.google.com/docs/cloud-messaging/http-server-ref
yes,
When you app in background you will receive the push at system tray so system tray will create push with notification title and message.
and when you click on the push your initial launcher activity (which mentioned as launcher in manifest) will open.
you can get your notification data at you launcher activity (bundle).
private void handlePush() {
Intent intent = null;
if (bundle.getString("push_type") != null && bundle.getString("push_type").length() > 0) {
switch (bundle.getString("push_type")) {
case PUSH_TYPE_FOLLOW_USER: {
intent = new Intent(this, ProfileExternalActivity.class);
intent.putExtra(Constants.USER_ID, Integer.parseInt(bundle.getString("id")));
intent.putExtra(Constants.FROM_PUSH_NOTIFICATION_SPLASH, true);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
break;
}
}
if (intent != null)
startActivity(intent);
finish();
}
}
and you need to check activty have data or not
if (bundle != null)
handlePush();
else //your next activity
FYI : https://firebase.google.com/docs/cloud-messaging/android/receive
or
you can get payload object instead of data object inside notification , if you have payload object in your notification object, push all time received at your onMessageReceived().
for people still having this issue:
Here is a hack to prevent this behavior. I've looked all over and there seems to be minimal info about this, but if you save the actual message being sent in shared preferences and then do a check against that value in onRecieve, you can easily prevent this. The only downside is that your user can't send the exact same message two times in a row in the form of a notification (but that would be annoying anyway). example:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
SharedPreferences Settings = getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = Settings.edit();
message = remoteMessage.getNotification().getBody();
from = remoteMessage.getFrom(); //this comes through as the topic, oddly...
if(from.equals("/topics/"+userID+deviceID+"all")) {
if(!message.equals(Settings.getString("messageall",null))) {//this filters any dupe messages
utils.postNotification(title, message, context, extra, "messages");//create notification
editor.putString("messageall", message);//always update to the last message
editor.commit();
}
}
}
I am using FCM to push notification. I am passing intent to launch new activity when notification is clicked.when app is in foreground,app works fine and intent launch new activity, but when app is in background, it does not launch new activity but launch instance of default activity.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//Displaying data in log
//It is optional
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
//Calling method to generate notification
sendNotification(remoteMessage.getNotification().getBody());
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, SecActivity.class);
intent.putExtra("started_from","notification");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Firebase Push Notification")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
Hope you are trying to launch the mainactivity when the message is received. When the app is resumed from background your current activity is getting cleared.
From the documentation for FLAG_ACTIVITY_CLEAR_TOP:
If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.
Try removing this flag.
I too had this same problem but i managed to have it fix with this ,
In your default activity mentioned in the manifest do this in the onCreate
if (bundle != null) {
if ((String) bundle.get("tag") != null) {
String tag = (String) bundle.get("tag");
if (tag.equals("abc")) {
Intent intent = new Intent(SplashActivity.this, MessageDetailsActivity.class);
startActivity(intent);
} else if (tag.equals("def")) {
openSpecificActivity(tag, (String) bundle.get("id"));
}
} else {
Intent i = new Intent(SplashActivity.this, HomeActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
}
i got a solution for that.
just put below code in oncreate method of launcher activity.
if (bundle != null) {
String value = bundle.getString("key");
if (value != null) {
startActivity(new Intent(MainActivity.this, secActivity.class));
}
}
when app is in background or killed,FCM will not call onmessagerecieved method,but it will send data to system tray to display notification.so datapayload(sent from fcm console) will not be handled by onmessagerecieved method.when user click on notification,it will launch default activity of app and datapayload will be passed by intent .so making change in oncreate method of launcher activity(as above)we can get datapayload even when app is in background or killed.(ex key is sent by fcm console).when app is in foreground datapayload and will be handled by onmessagerecieved method of fcm service.
Based upon Antinio's answer
https://stackoverflow.com/a/37845174/4454119
Why is this happening?
There are two types of messages in FCM (Firebase Cloud Messaging):
display-messages: These messages trigger the onMessageReceived() callback only when your app is in foreground
data-messages: Theses messages trigger the onMessageReceived() callback even if your app is in foreground/background/killed
Firebase team have not developed a UI to send data-messages to your devices, yet.
So you need to use data-messages..
In FCM you have two types of messages
Notification Messages
Data Messages
Use notification messages when you want FCM to handle displaying a notification on your client app's behalf. Use data messages when you want to process the messages in your client app.
If you need to process your message before sending it to the system tray, it's better to use Data messages, as for these types of messages, the callback first reaches the onMessageRecieved method before going to the system tray.
Use this:
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
IN YOUR SERVICE
"to": token,
"notification": {
"title": "Title,
"body": "Body"
},
"data" : {
"update": "yes"
}
IN ANDROID KOTLIN
val intent = Intent(this,MainActivity::class.java)
intent.putExtra("update","yes")
......
I'm working with Firebase and testing sending notifications to my app from my server while the app is in the background. The notification is sent successfully, it even appears on the notification centre of the device, but when the notification appears or even if I click on it, the onMessageReceived method inside my FCMessagingService is never called.
When I tested this while my app was in the foreground, the onMessageReceived method was called and everything worked fine. The problem occurs when the app is running in the background.
Is this intended behaviour, or is there a way I can fix this?
Here is my FBMessagingService:
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class FBMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.i("PVL", "MESSAGE RECEIVED!!");
if (remoteMessage.getNotification().getBody() != null) {
Log.i("PVL", "RECEIVED MESSAGE: " + remoteMessage.getNotification().getBody());
} else {
Log.i("PVL", "RECEIVED MESSAGE: " + remoteMessage.getData().get("message"));
}
}
}
This is working as intended, notification messages are delivered to your onMessageReceived callback only when your app is in the foreground. If your app is in the background or closed then a notification message is shown in the notification center, and any data from that message is passed to the intent that is launched as a result of the user tapping on the notification.
You can specify a click_action in your JSON to indicate the intent that should be launched when the notification is tapped by the user. The main activity is used if no click_action is specified.
When the intent is launched you can use the
getIntent().getExtras();
to retrieve a Set that would include any data sent along with the notification message.
For more on notification message see docs.
Remove notification field completely from your server request. Send only data and handle it in onMessageReceived() otherwise your onMessageReceived() will not be triggered when app is in background or killed.
Don't forget to include "priority": "high" field in your notification request. According to the documentation: data messages are sent with a normal priority, thus they will not arrive instantly; it could also be the problem.
Here is what I am sending from server
{
"data":{
"id": 1,
"missedRequests": 5
"addAnyDataHere": 123
},
"to": "fhiT7evmZk8:APA91bFJq7Tkly4BtLRXdYvqHno2vHCRkzpJT8QZy0TlIGs......",
"priority": "high"
}
So you can receive your data in onMessageReceived(RemoteMessage message) like this....let say I have to get id
Object obj = message.getData().get("id");
if (obj != null) {
int id = Integer.valueOf(obj.toString());
}
this method handleIntent() has been depreciated, so handling a notification can be done as below:
Foreground State: The click of the notification will go to the pending Intent's activity which you are providing while creating a notification pro-grammatically as it generally created with data payload of the notification.
Background/Killed State - Here, the system itself creates a notification based on notification payload and clicking on that notification will take you to the launcher activity of the application where you can easily fetch Intent data in any of your life-cycle methods.
Here is more clear concepts about firebase message. I found it from their support team.
Firebase has three message types:
Notification messages : Notification message works on background or foreground. When app is in background, Notification messages are delivered to the system tray. If the app is in the foreground, messages are handled by onMessageReceived() or didReceiveRemoteNotification callbacks. These are essentially what is referred to as Display messages.
Data messages: On Android platform, data message can work on background and foreground. The data message will be handled by onMessageReceived(). A platform specific note here would be: On Android, the data payload can be retrieved in the Intent used to launch your activity. To elaborate, if you have "click_action":"launch_Activity_1", you can retrieve this intent through getIntent() from only Activity_1.
Messages with both notification and data payloads: When in the background, apps receive the notification payload in the notification tray, and only handle the data payload when the user taps on the notification. When in the foreground, your app receives a message object with both payloads available. Secondly, the click_action parameter is often used in notification payload and not in data payload. If used inside data payload, this parameter would be treated as custom key-value pair and therefore you would need to implement custom logic for it to work as intended.
Also, I recommend you to use onMessageReceived method (see Data message) to extract the data bundle. From your logic, I checked the bundle object and haven't found expected data content. Here is a reference to a similar case which might provide more clarity.
From server side, firebase notification should bellow format:
Server side should send "notification" object. Lacks of "notification" object in my TargetActivity didn't getting message using getIntent().
Correct message format is given bellow:
{
"data": {
"body": "here is body",
"title": "Title"
},
"notification": {
"body": "here is body",
"title": "Title",
"click_action": "YOUR_ACTION"
},
"to": "ffEseX6vwcM:APA91bF8m7wOF MY FCM ID 07j1aPUb"
}
Here is more clear concepts about firebase message. I found it from their support team.
For more info visit my this thread and this thread
I had the same problem. It is easier to use the 'data message' instead of the 'notification'. The data message always load the class onMessageReceived.
In that class you can make your own notification with the notificationbuilder.
Example:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
sendNotification(remoteMessage.getData().get("title"),remoteMessage.getData().get("body"));
}
private void sendNotification(String messageTitle,String messageBody) {
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_UPDATE_CURRENT);
long[] pattern = {500,500,500,500,500};
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_name)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setVibrate(pattern)
.setLights(Color.BLUE,1,1)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
As per Firebase Cloud Messaging documentation-If Activity is in foreground then onMessageReceived will get called. If Activity is in background or closed then notification message is shown in the notification center for app launcher activity.
You can call your customized activity on click of notification if your app is in background by calling rest service api for firebase messaging as:
URL-https://fcm.googleapis.com/fcm/send
Method Type- POST
Header- Content-Type:application/json
Authorization:key=your api key
Body/Payload:
{ "notification": {
"title": "Your Title",
"text": "Your Text",
"click_action": "OPEN_ACTIVITY_1" // should match to your intent filter
},
"data": {
"keyname": "any value " //you can get this data as extras in your activity and this data is optional
},
"to" : "to_id(firebase refreshedToken)"
}
And with this in your app you can add below code in your activity to be called:
<intent-filter>
<action android:name="OPEN_ACTIVITY_1" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
onMessageReceived(RemoteMessage remoteMessage) method called based on the following cases.
FCM Response With notification and data block:
{
"to": "device token list",
"notification": {
"body": "Body of Your Notification",
"title": "Title of Your Notification"
},
"data": {
"body": "Body of Your Notification in Data",
"title": "Title of Your Notification in Title",
"key_1": "Value for key_1",
"image_url": "www.abc.com/xyz.jpeg",
"key_2": "Value for key_2"
}
}
App in Foreground:
onMessageReceived(RemoteMessage remoteMessage) called, shows LargeIcon and BigPicture in the notification bar. We can read the content from both notification and data block
App in Background:
onMessageReceived(RemoteMessage remoteMessage) not called, system tray will receive the message and read body and title from notification block and shows default message and title in the notification bar.
FCM Response With only data block:
In this case, removing notification blocks from json
{
"to": "device token list",
"data": {
"body": "Body of Your Notification in Data",
"title": "Title of Your Notification in Title",
"key_1": "Value for key_1",
"image_url": "www.abc.com/xyz.jpeg",
"key_2": "Value for key_2"
}
}
Solution for calling onMessageReceived()
App in Foreground:
onMessageReceived(RemoteMessage remoteMessage) called, shows LargeIcon and BigPicture in the notification bar. We can read the content from both notification and data block
App in Background:
onMessageReceived(RemoteMessage remoteMessage) called, system tray will not receive the message because of notification key is not in the response. Shows LargeIcon and BigPicture in the notification bar
Code
private void sendNotification(Bitmap bitmap, String title, String
message, PendingIntent resultPendingIntent) {
NotificationCompat.BigPictureStyle style = new NotificationCompat.BigPictureStyle();
style.bigPicture(bitmap);
Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = mContext.getString(R.string.default_notification_channel_id);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "channel_name", NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(notificationChannel);
}
Bitmap iconLarge = BitmapFactory.decodeResource(mContext.getResources(),
R.drawable.mdmlogo);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.mdmlogo)
.setContentTitle(title)
.setAutoCancel(true)
.setSound(defaultSound)
.setContentText(message)
.setContentIntent(resultPendingIntent)
.setStyle(style)
.setLargeIcon(iconLarge)
.setWhen(System.currentTimeMillis())
.setPriority(Notification.PRIORITY_MAX)
.setChannelId(NOTIFICATION_CHANNEL_ID);
notificationManager.notify(1, notificationBuilder.build());
}
Reference Link:
https://firebase.google.com/docs/cloud-messaging/android/receive
If app is in the background mode or inactive(killed), and you click on Notification, you should check for the payload in LaunchScreen(in my case launch screen is MainActivity.java).
So in MainActivity.java on onCreate check for Extras:
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
Object value = getIntent().getExtras().get(key);
Log.d("MainActivity: ", "Key: " + key + " Value: " + value);
}
}
I got the same issue. If the app is foreground - it triggers my background service where I can update my database based on the notification type.
But, the app goes to the background - the default notification service will be taken care to show the notification to the user.
Here is my solution to identify app in background and trigger your background service,
public class FirebaseBackgroundService extends WakefulBroadcastReceiver {
private static final String TAG = "FirebaseService";
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "I'm in!!!");
if (intent.getExtras() != null) {
for (String key : intent.getExtras().keySet()) {
Object value = intent.getExtras().get(key);
Log.e("FirebaseDataReceiver", "Key: " + key + " Value: " + value);
if(key.equalsIgnoreCase("gcm.notification.body") && value != null) {
Bundle bundle = new Bundle();
Intent backgroundIntent = new Intent(context, BackgroundSyncJobService.class);
bundle.putString("push_message", value + "");
backgroundIntent.putExtras(bundle);
context.startService(backgroundIntent);
}
}
}
}
}
In the manifest.xml
<receiver android:exported="true" android:name=".FirebaseBackgroundService" android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</receiver>
Tested this solution in latest android 8.0 version. Thanks
Override the handleIntent Method of the FirebaseMessageService works for me.
here the code in C# (Xamarin)
public override void HandleIntent(Intent intent)
{
try
{
if (intent.Extras != null)
{
var builder = new RemoteMessage.Builder("MyFirebaseMessagingService");
foreach (string key in intent.Extras.KeySet())
{
builder.AddData(key, intent.Extras.Get(key).ToString());
}
this.OnMessageReceived(builder.Build());
}
else
{
base.HandleIntent(intent);
}
}
catch (Exception)
{
base.HandleIntent(intent);
}
}
and thats the Code in Java
public void handleIntent(Intent intent)
{
try
{
if (intent.getExtras() != null)
{
RemoteMessage.Builder builder = new RemoteMessage.Builder("MyFirebaseMessagingService");
for (String key : intent.getExtras().keySet())
{
builder.addData(key, intent.getExtras().get(key).toString());
}
onMessageReceived(builder.build());
}
else
{
super.handleIntent(intent);
}
}
catch (Exception e)
{
super.handleIntent(intent);
}
}
By default the Launcher Activity in you app will be launched when your app is in background and you click the notification, if you have any data part with your notifcation you can handle it in the same activity as follows,
if(getIntent().getExtras()! = null){
//do your stuff
}else{
//do that you normally do
}
I might be very late here to answers but the official documentation is a bit confusing.
Also it's clearly stated that there are two types of notification
Notification message: Automatically handled by FCM
Data message: Handled by the client app.
No doubt if the server sends a Data message then onMessageReceived() methods definitely get invoked but in the case of Notification message onMessageReceived() method will get invoked only if the app is in the foreground and when the app is in the background the data we are sending is just null.
Example:
Lets assume server is sending notification message type:
A. In case of Foreground:
remoteMessage.data["key"] will work
B. In case of background:
-remoteMessage.data["key"] will return null
but here if you find the same intent data in defaul activity with getIntent().getExtras().getString("key") will work
C. In case of kill:
-remoteMessage.data["key"] will return null
but here if you find the same intent data in defaul activity with getIntent().getExtras().getString("key") will work
Now, let's assume server is sending data message type:
D. In case of Foreground:
remoteMessage.data["key"] will work
E. In case of background:
remoteMessage.data["key"] will work
F. In case of kill:
remoteMessage.data["key"] will work
No doubt data message will always invokes onMessageReceived() method but in case of notification message and app is in background/kill state you can use the solution of B. Thanks
I hope it will save everyone's time.
according to the solution from t3h Exi i would like to post the clean code here. Just put it into MyFirebaseMessagingService and everything works fine if the app is in background mode. You need at least to compile com.google.firebase:firebase-messaging:10.2.1
#Override
public void handleIntent(Intent intent)
{
try
{
if (intent.getExtras() != null)
{
RemoteMessage.Builder builder = new RemoteMessage.Builder("MyFirebaseMessagingService");
for (String key : intent.getExtras().keySet())
{
builder.addData(key, intent.getExtras().get(key).toString());
}
onMessageReceived(builder.build());
}
else
{
super.handleIntent(intent);
}
}
catch (Exception e)
{
super.handleIntent(intent);
}
}
If app is in background Fire-base by default handling notification But if we want to our custom notification than we have to change our server side, which is responsible for to send our custom data(data payload)
Remove notification payload completely from your server request. Send only Data and handle it in onMessageReceived() otherwise your onMessageReceived will not be triggered when app is in background or killed.
now,your server side code format look like,
{
"collapse_key": "CHAT_MESSAGE_CONTACT",
"data": {
"loc_key": "CHAT_MESSAGE_CONTACT",
"loc_args": ["John Doe", "Contact Exchange"],
"text": "John Doe shared a contact in the group Contact Exchange",
"custom": {
"chat_id": 241233,
"msg_id": 123
},
"badge": 1,
"sound": "sound1.mp3",
"mute": true
}
}
NOTE: see this line in above code
"text": "John Doe shared a contact in the group Contact Exchange"
in Data payload you should use "text" parameter instead of "body" or "message" parameters for message description or whatever you want to use text.
onMessageReceived()
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.e(TAG, "From: " + remoteMessage.getData().toString());
if (remoteMessage == null)
return;
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
/* Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());*/
Log.e(TAG, "Data Payload: " + remoteMessage);
try {
Map<String, String> params = remoteMessage.getData();
JSONObject json = new JSONObject(params);
Log.e("JSON_OBJECT", json.toString());
Log.e(TAG, "onMessageReceived: " + json.toString());
handleDataMessage(json);
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
}
I had similar issue. Based on the answers and references mentioned in this page, here are my two cents on how I resolved my problem with the below approach:
The message format I had earlier was as below:
{
"notification": {
"title": "AppName",
"sound": null,
"body": "Hey!YouhaveaMessage"
},
"data": {
"param1": null,
"param2": [
238
],
"id": 1
},
"to": "--the device push token here--"
}
I modified the message format to the below:
{
"data": {
"title": "AppName",
"body": "Hey! You have a message",
"param1": null,
"param2": [
238
],
"id": 1
},
"priority": "high",
"to": " — device push token here — "
}
Then I retrieved the title, body and all the parameters from the "data" payload itself. This solved the problem and I could then get the OnMessageReceived callback even though the app is in the background.
I wrote a blog post explaining the same issue, you can find it here.
{
"notification": {
"title": "Notification Title",
"body": "Notification Body",
"click_action": "ActivityToOpen"
},
"data": {
"key": "value "
},
"to": "id"
}
If the FCM payload has notification{} block like the above and the app is in the background, the system builds the notification for you with the title and body given in notification{}. When the user clicks on it, the activity mentioned in click_action opens, if nothing is given the default launcher activity opens and data inside the data{} block can be accessed from
intent.extras // of the launcher activity
If the app is in the foreground the function onMessageReceived() in FirebaseMessagingService() class gets triggered. We will have to build the notification by ourselves and we can access the data as following:
val value = message.data.getOrDefault("key", "")
If the FCM payload is without notification block{} like following;
{
"data": {
"title": "Notification Title",
"body": "Notification Body",
"key": "value "
},
"to" : "id"
}
The function onMessageReceived() in FirebaseMessagingService() class gets triggered regardless of app being in background or foreground and we will have to build notification by ourselves.
We can access the data as following:
override fun onMessageReceived(message: RemoteMessage) {
super.onMessageReceived(message)
val title = message.data.getOrDefault("title", "")
val body = message.data.getOrDefault("body", "")
}
Just call this in your MainActivity's onCreate Method :
if (getIntent().getExtras() != null) {
// Call your NotificationActivity here..
Intent intent = new Intent(MainActivity.this, NotificationActivity.class);
startActivity(intent);
}
Try this:
public void handleIntent(Intent intent) {
try {
if (intent.getExtras() != null) {
RemoteMessage.Builder builder = new RemoteMessage.Builder("MyFirebaseMessagingService");
for (String key : intent.getExtras().keySet()) {
builder.addData(key, intent.getExtras().get(key).toString());
}
onMessageReceived(builder.build());
} else {
super.handleIntent(intent);
}
} catch (Exception e) {
super.handleIntent(intent);
}
}
I had this issue(app doesn't want to open on notification click if app is in background or closed), and the problem was an invalid click_action in notification body, try removing or changing it to something valid.
The point which deserves highlighting is that you have to use data message - data key only - to get onMessageReceived handler called even when the app is in background. You shouldn't have any other notification message key in your payload, otherwise the handler won't get triggered if the app is in background.
It is mentioned (but not so emphasized in FCM documentation) here:
https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages
Use your app server and FCM server API: Set the data key only. Can be
either collapsible or non-collapsible.
The backend I'm working with is using Notification messages and not Data messages. So after reading all the answers I tried to retrieve the extras from the bundle of the intent that comes to the launched activity.
But no matter which keys I tried to retrieve from getIntent().getExtras();, the value was always null.
However, I finally found a way to send data using Notification messages and retrieve it from the intent.
The key here is to add the data payload to the Notification message.
Example:
{
"data": {
"message": "message_body",
"title": "message_title"
},
"notification": {
"body": "test body",
"title": "test title"
},
"to": "E4An.."
}
After you do this, you will be able to get your info in this way:
intent.getExtras().getString("title")
will be message_title
and
intent.getExtras().getString("message")
will be message_body
Reference
If your problem is related to showing Big Image i.e. if you are sending push notification with an image from firebase console and it displays the image only if the app in the foreground. The solution for this problem is to send a push message with only data field. Something like this:
{ "data": { "image": "https://static.pexels.com/photos/4825/red-love-romantic-flowers.jpg", "message": "Firebase Push Message Using API" "AnotherActivity": "True" }, "to" : "device id Or Device token" }
When message is received and your app is in background the notification is sent to the extras intent of the main activity.
You can check the extra value in the oncreate() or onresume() function of the main activity.
You can check for the fields like data, table etc ( the one specified in the notification)
for example I sent using data as the key
public void onResume(){
super.onResume();
if (getIntent().getStringExtra("data")!=null){
fromnotification=true;
Intent i = new Intent(MainActivity.this, Activity2.class);
i.putExtra("notification","notification");
startActivity(i);
}
}
I think the answers to tell you change message type to data are clear to you.
But sometimes, if you cannot decide your the message type you received and you have to handle it. I post my method here. You just implemented FirebaseMessagingService and handle your message in handlIntent() method. From there you could customize your own notification. You can implement your own method sendYourNotificatoin()
class FCMPushService : FirebaseMessagingService() {
companion object {
private val TAG = "FCMPush"
}
override fun handleIntent(intent: Intent?) {
Logger.t(TAG).i("handleIntent:${intent.toString()}")
val data = intent?.extras as Bundle
val remoteMessage = RemoteMessage(data)
if (remoteMessage.data.isNotEmpty()) {
val groupId: String = remoteMessage.data[MESSAGE_KEY_GROUP_ID] ?: ""
val title = remoteMessage.notification?.title ?: ""
val body = remoteMessage.notification?.body ?: ""
if (title.isNotEmpty() && body.isNotEmpty())
sendYourNotificatoin(this, title, body, groupId)
}
}
}
I was having the same issue and did some more digging on this. When the app is in the background, a notification message is sent to the system tray, BUT a data message is sent to onMessageReceived()
See https://firebase.google.com/docs/cloud-messaging/downstream#monitor-token-generation_3
and https://github.com/firebase/quickstart-android/blob/master/messaging/app/src/main/java/com/google/firebase/quickstart/fcm/MyFirebaseMessagingService.java
To ensure that the message you are sending, the docs say, "Use your app server and FCM server API: Set the data key only. Can be either collapsible or non-collapsible."
See https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages
There are two types of messages: notification messages and data messages.
If you only send data message, that is without notification object in your message string. It would be invoked when your app in background.
Check the answer of #Mahesh Kavathiya. For my case, in server code has only like this:
{
"notification": {
"body": "here is body",
"title": "Title",
},
"to": "sdfjsdfonsdofoiewj9230idsjkfmnkdsfm"
}
You need to change to:
{
"data": {
"body": "here is body",
"title": "Title",
"click_action": "YOUR_ACTION"
},
"notification": {
"body": "here is body",
"title": "Title"
},
"to": "sdfjsdfonsdofoiewj9230idsjkfmnkdsfm"
}
Then, in case app in Background, the default activity intent extra will get "data"
Good luck!
That is the intended behavior, you need to set click_action in firebase notification data set to be able to receive data from background.
See updated answer here:
https://stackoverflow.com/a/73724040/7904082
There are 2 types of Firebase push-notifications:
1- Notification message(Display message) ->
-- 1.1 If you choose this variant, the OS will create it self a notification if app is in Background and will pass the data in the intent. Then it's up to the client to handle this data.
-- 1.2 If the app is in Foreground then the notification it will be received via callback-function in the FirebaseMessagingService and it's up to the client to handle it.
2- Data messages(up to 4k data) -> These messages are used to send only data to the client(silently) and it's up to the client to handle it for both cases background/foreground via callback-function in FirebaseMessagingService
This is according official docs:https://firebase.google.com/docs/cloud-messaging/concept-options
Just override the OnCreate method of FirebaseMessagingService. It is called when your app is in background:
public override void OnCreate()
{
// your code
base.OnCreate();
}
I'm working with Firebase and testing sending notifications to my app from my server while the app is in the background. The notification is sent successfully, it even appears on the notification centre of the device, but when the notification appears or even if I click on it, the onMessageReceived method inside my FCMessagingService is never called.
When I tested this while my app was in the foreground, the onMessageReceived method was called and everything worked fine. The problem occurs when the app is running in the background.
Is this intended behaviour, or is there a way I can fix this?
Here is my FBMessagingService:
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class FBMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.i("PVL", "MESSAGE RECEIVED!!");
if (remoteMessage.getNotification().getBody() != null) {
Log.i("PVL", "RECEIVED MESSAGE: " + remoteMessage.getNotification().getBody());
} else {
Log.i("PVL", "RECEIVED MESSAGE: " + remoteMessage.getData().get("message"));
}
}
}
This is working as intended, notification messages are delivered to your onMessageReceived callback only when your app is in the foreground. If your app is in the background or closed then a notification message is shown in the notification center, and any data from that message is passed to the intent that is launched as a result of the user tapping on the notification.
You can specify a click_action in your JSON to indicate the intent that should be launched when the notification is tapped by the user. The main activity is used if no click_action is specified.
When the intent is launched you can use the
getIntent().getExtras();
to retrieve a Set that would include any data sent along with the notification message.
For more on notification message see docs.
Remove notification field completely from your server request. Send only data and handle it in onMessageReceived() otherwise your onMessageReceived() will not be triggered when app is in background or killed.
Don't forget to include "priority": "high" field in your notification request. According to the documentation: data messages are sent with a normal priority, thus they will not arrive instantly; it could also be the problem.
Here is what I am sending from server
{
"data":{
"id": 1,
"missedRequests": 5
"addAnyDataHere": 123
},
"to": "fhiT7evmZk8:APA91bFJq7Tkly4BtLRXdYvqHno2vHCRkzpJT8QZy0TlIGs......",
"priority": "high"
}
So you can receive your data in onMessageReceived(RemoteMessage message) like this....let say I have to get id
Object obj = message.getData().get("id");
if (obj != null) {
int id = Integer.valueOf(obj.toString());
}
this method handleIntent() has been depreciated, so handling a notification can be done as below:
Foreground State: The click of the notification will go to the pending Intent's activity which you are providing while creating a notification pro-grammatically as it generally created with data payload of the notification.
Background/Killed State - Here, the system itself creates a notification based on notification payload and clicking on that notification will take you to the launcher activity of the application where you can easily fetch Intent data in any of your life-cycle methods.
Here is more clear concepts about firebase message. I found it from their support team.
Firebase has three message types:
Notification messages : Notification message works on background or foreground. When app is in background, Notification messages are delivered to the system tray. If the app is in the foreground, messages are handled by onMessageReceived() or didReceiveRemoteNotification callbacks. These are essentially what is referred to as Display messages.
Data messages: On Android platform, data message can work on background and foreground. The data message will be handled by onMessageReceived(). A platform specific note here would be: On Android, the data payload can be retrieved in the Intent used to launch your activity. To elaborate, if you have "click_action":"launch_Activity_1", you can retrieve this intent through getIntent() from only Activity_1.
Messages with both notification and data payloads: When in the background, apps receive the notification payload in the notification tray, and only handle the data payload when the user taps on the notification. When in the foreground, your app receives a message object with both payloads available. Secondly, the click_action parameter is often used in notification payload and not in data payload. If used inside data payload, this parameter would be treated as custom key-value pair and therefore you would need to implement custom logic for it to work as intended.
Also, I recommend you to use onMessageReceived method (see Data message) to extract the data bundle. From your logic, I checked the bundle object and haven't found expected data content. Here is a reference to a similar case which might provide more clarity.
From server side, firebase notification should bellow format:
Server side should send "notification" object. Lacks of "notification" object in my TargetActivity didn't getting message using getIntent().
Correct message format is given bellow:
{
"data": {
"body": "here is body",
"title": "Title"
},
"notification": {
"body": "here is body",
"title": "Title",
"click_action": "YOUR_ACTION"
},
"to": "ffEseX6vwcM:APA91bF8m7wOF MY FCM ID 07j1aPUb"
}
Here is more clear concepts about firebase message. I found it from their support team.
For more info visit my this thread and this thread
I had the same problem. It is easier to use the 'data message' instead of the 'notification'. The data message always load the class onMessageReceived.
In that class you can make your own notification with the notificationbuilder.
Example:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
sendNotification(remoteMessage.getData().get("title"),remoteMessage.getData().get("body"));
}
private void sendNotification(String messageTitle,String messageBody) {
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_UPDATE_CURRENT);
long[] pattern = {500,500,500,500,500};
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_name)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setVibrate(pattern)
.setLights(Color.BLUE,1,1)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
As per Firebase Cloud Messaging documentation-If Activity is in foreground then onMessageReceived will get called. If Activity is in background or closed then notification message is shown in the notification center for app launcher activity.
You can call your customized activity on click of notification if your app is in background by calling rest service api for firebase messaging as:
URL-https://fcm.googleapis.com/fcm/send
Method Type- POST
Header- Content-Type:application/json
Authorization:key=your api key
Body/Payload:
{ "notification": {
"title": "Your Title",
"text": "Your Text",
"click_action": "OPEN_ACTIVITY_1" // should match to your intent filter
},
"data": {
"keyname": "any value " //you can get this data as extras in your activity and this data is optional
},
"to" : "to_id(firebase refreshedToken)"
}
And with this in your app you can add below code in your activity to be called:
<intent-filter>
<action android:name="OPEN_ACTIVITY_1" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
onMessageReceived(RemoteMessage remoteMessage) method called based on the following cases.
FCM Response With notification and data block:
{
"to": "device token list",
"notification": {
"body": "Body of Your Notification",
"title": "Title of Your Notification"
},
"data": {
"body": "Body of Your Notification in Data",
"title": "Title of Your Notification in Title",
"key_1": "Value for key_1",
"image_url": "www.abc.com/xyz.jpeg",
"key_2": "Value for key_2"
}
}
App in Foreground:
onMessageReceived(RemoteMessage remoteMessage) called, shows LargeIcon and BigPicture in the notification bar. We can read the content from both notification and data block
App in Background:
onMessageReceived(RemoteMessage remoteMessage) not called, system tray will receive the message and read body and title from notification block and shows default message and title in the notification bar.
FCM Response With only data block:
In this case, removing notification blocks from json
{
"to": "device token list",
"data": {
"body": "Body of Your Notification in Data",
"title": "Title of Your Notification in Title",
"key_1": "Value for key_1",
"image_url": "www.abc.com/xyz.jpeg",
"key_2": "Value for key_2"
}
}
Solution for calling onMessageReceived()
App in Foreground:
onMessageReceived(RemoteMessage remoteMessage) called, shows LargeIcon and BigPicture in the notification bar. We can read the content from both notification and data block
App in Background:
onMessageReceived(RemoteMessage remoteMessage) called, system tray will not receive the message because of notification key is not in the response. Shows LargeIcon and BigPicture in the notification bar
Code
private void sendNotification(Bitmap bitmap, String title, String
message, PendingIntent resultPendingIntent) {
NotificationCompat.BigPictureStyle style = new NotificationCompat.BigPictureStyle();
style.bigPicture(bitmap);
Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = mContext.getString(R.string.default_notification_channel_id);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "channel_name", NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(notificationChannel);
}
Bitmap iconLarge = BitmapFactory.decodeResource(mContext.getResources(),
R.drawable.mdmlogo);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.mdmlogo)
.setContentTitle(title)
.setAutoCancel(true)
.setSound(defaultSound)
.setContentText(message)
.setContentIntent(resultPendingIntent)
.setStyle(style)
.setLargeIcon(iconLarge)
.setWhen(System.currentTimeMillis())
.setPriority(Notification.PRIORITY_MAX)
.setChannelId(NOTIFICATION_CHANNEL_ID);
notificationManager.notify(1, notificationBuilder.build());
}
Reference Link:
https://firebase.google.com/docs/cloud-messaging/android/receive
If app is in the background mode or inactive(killed), and you click on Notification, you should check for the payload in LaunchScreen(in my case launch screen is MainActivity.java).
So in MainActivity.java on onCreate check for Extras:
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
Object value = getIntent().getExtras().get(key);
Log.d("MainActivity: ", "Key: " + key + " Value: " + value);
}
}
I got the same issue. If the app is foreground - it triggers my background service where I can update my database based on the notification type.
But, the app goes to the background - the default notification service will be taken care to show the notification to the user.
Here is my solution to identify app in background and trigger your background service,
public class FirebaseBackgroundService extends WakefulBroadcastReceiver {
private static final String TAG = "FirebaseService";
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "I'm in!!!");
if (intent.getExtras() != null) {
for (String key : intent.getExtras().keySet()) {
Object value = intent.getExtras().get(key);
Log.e("FirebaseDataReceiver", "Key: " + key + " Value: " + value);
if(key.equalsIgnoreCase("gcm.notification.body") && value != null) {
Bundle bundle = new Bundle();
Intent backgroundIntent = new Intent(context, BackgroundSyncJobService.class);
bundle.putString("push_message", value + "");
backgroundIntent.putExtras(bundle);
context.startService(backgroundIntent);
}
}
}
}
}
In the manifest.xml
<receiver android:exported="true" android:name=".FirebaseBackgroundService" android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</receiver>
Tested this solution in latest android 8.0 version. Thanks
Override the handleIntent Method of the FirebaseMessageService works for me.
here the code in C# (Xamarin)
public override void HandleIntent(Intent intent)
{
try
{
if (intent.Extras != null)
{
var builder = new RemoteMessage.Builder("MyFirebaseMessagingService");
foreach (string key in intent.Extras.KeySet())
{
builder.AddData(key, intent.Extras.Get(key).ToString());
}
this.OnMessageReceived(builder.Build());
}
else
{
base.HandleIntent(intent);
}
}
catch (Exception)
{
base.HandleIntent(intent);
}
}
and thats the Code in Java
public void handleIntent(Intent intent)
{
try
{
if (intent.getExtras() != null)
{
RemoteMessage.Builder builder = new RemoteMessage.Builder("MyFirebaseMessagingService");
for (String key : intent.getExtras().keySet())
{
builder.addData(key, intent.getExtras().get(key).toString());
}
onMessageReceived(builder.build());
}
else
{
super.handleIntent(intent);
}
}
catch (Exception e)
{
super.handleIntent(intent);
}
}
By default the Launcher Activity in you app will be launched when your app is in background and you click the notification, if you have any data part with your notifcation you can handle it in the same activity as follows,
if(getIntent().getExtras()! = null){
//do your stuff
}else{
//do that you normally do
}
I might be very late here to answers but the official documentation is a bit confusing.
Also it's clearly stated that there are two types of notification
Notification message: Automatically handled by FCM
Data message: Handled by the client app.
No doubt if the server sends a Data message then onMessageReceived() methods definitely get invoked but in the case of Notification message onMessageReceived() method will get invoked only if the app is in the foreground and when the app is in the background the data we are sending is just null.
Example:
Lets assume server is sending notification message type:
A. In case of Foreground:
remoteMessage.data["key"] will work
B. In case of background:
-remoteMessage.data["key"] will return null
but here if you find the same intent data in defaul activity with getIntent().getExtras().getString("key") will work
C. In case of kill:
-remoteMessage.data["key"] will return null
but here if you find the same intent data in defaul activity with getIntent().getExtras().getString("key") will work
Now, let's assume server is sending data message type:
D. In case of Foreground:
remoteMessage.data["key"] will work
E. In case of background:
remoteMessage.data["key"] will work
F. In case of kill:
remoteMessage.data["key"] will work
No doubt data message will always invokes onMessageReceived() method but in case of notification message and app is in background/kill state you can use the solution of B. Thanks
I hope it will save everyone's time.
according to the solution from t3h Exi i would like to post the clean code here. Just put it into MyFirebaseMessagingService and everything works fine if the app is in background mode. You need at least to compile com.google.firebase:firebase-messaging:10.2.1
#Override
public void handleIntent(Intent intent)
{
try
{
if (intent.getExtras() != null)
{
RemoteMessage.Builder builder = new RemoteMessage.Builder("MyFirebaseMessagingService");
for (String key : intent.getExtras().keySet())
{
builder.addData(key, intent.getExtras().get(key).toString());
}
onMessageReceived(builder.build());
}
else
{
super.handleIntent(intent);
}
}
catch (Exception e)
{
super.handleIntent(intent);
}
}
If app is in background Fire-base by default handling notification But if we want to our custom notification than we have to change our server side, which is responsible for to send our custom data(data payload)
Remove notification payload completely from your server request. Send only Data and handle it in onMessageReceived() otherwise your onMessageReceived will not be triggered when app is in background or killed.
now,your server side code format look like,
{
"collapse_key": "CHAT_MESSAGE_CONTACT",
"data": {
"loc_key": "CHAT_MESSAGE_CONTACT",
"loc_args": ["John Doe", "Contact Exchange"],
"text": "John Doe shared a contact in the group Contact Exchange",
"custom": {
"chat_id": 241233,
"msg_id": 123
},
"badge": 1,
"sound": "sound1.mp3",
"mute": true
}
}
NOTE: see this line in above code
"text": "John Doe shared a contact in the group Contact Exchange"
in Data payload you should use "text" parameter instead of "body" or "message" parameters for message description or whatever you want to use text.
onMessageReceived()
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.e(TAG, "From: " + remoteMessage.getData().toString());
if (remoteMessage == null)
return;
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
/* Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());*/
Log.e(TAG, "Data Payload: " + remoteMessage);
try {
Map<String, String> params = remoteMessage.getData();
JSONObject json = new JSONObject(params);
Log.e("JSON_OBJECT", json.toString());
Log.e(TAG, "onMessageReceived: " + json.toString());
handleDataMessage(json);
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
}
I had similar issue. Based on the answers and references mentioned in this page, here are my two cents on how I resolved my problem with the below approach:
The message format I had earlier was as below:
{
"notification": {
"title": "AppName",
"sound": null,
"body": "Hey!YouhaveaMessage"
},
"data": {
"param1": null,
"param2": [
238
],
"id": 1
},
"to": "--the device push token here--"
}
I modified the message format to the below:
{
"data": {
"title": "AppName",
"body": "Hey! You have a message",
"param1": null,
"param2": [
238
],
"id": 1
},
"priority": "high",
"to": " — device push token here — "
}
Then I retrieved the title, body and all the parameters from the "data" payload itself. This solved the problem and I could then get the OnMessageReceived callback even though the app is in the background.
I wrote a blog post explaining the same issue, you can find it here.
{
"notification": {
"title": "Notification Title",
"body": "Notification Body",
"click_action": "ActivityToOpen"
},
"data": {
"key": "value "
},
"to": "id"
}
If the FCM payload has notification{} block like the above and the app is in the background, the system builds the notification for you with the title and body given in notification{}. When the user clicks on it, the activity mentioned in click_action opens, if nothing is given the default launcher activity opens and data inside the data{} block can be accessed from
intent.extras // of the launcher activity
If the app is in the foreground the function onMessageReceived() in FirebaseMessagingService() class gets triggered. We will have to build the notification by ourselves and we can access the data as following:
val value = message.data.getOrDefault("key", "")
If the FCM payload is without notification block{} like following;
{
"data": {
"title": "Notification Title",
"body": "Notification Body",
"key": "value "
},
"to" : "id"
}
The function onMessageReceived() in FirebaseMessagingService() class gets triggered regardless of app being in background or foreground and we will have to build notification by ourselves.
We can access the data as following:
override fun onMessageReceived(message: RemoteMessage) {
super.onMessageReceived(message)
val title = message.data.getOrDefault("title", "")
val body = message.data.getOrDefault("body", "")
}
Just call this in your MainActivity's onCreate Method :
if (getIntent().getExtras() != null) {
// Call your NotificationActivity here..
Intent intent = new Intent(MainActivity.this, NotificationActivity.class);
startActivity(intent);
}
Try this:
public void handleIntent(Intent intent) {
try {
if (intent.getExtras() != null) {
RemoteMessage.Builder builder = new RemoteMessage.Builder("MyFirebaseMessagingService");
for (String key : intent.getExtras().keySet()) {
builder.addData(key, intent.getExtras().get(key).toString());
}
onMessageReceived(builder.build());
} else {
super.handleIntent(intent);
}
} catch (Exception e) {
super.handleIntent(intent);
}
}
I had this issue(app doesn't want to open on notification click if app is in background or closed), and the problem was an invalid click_action in notification body, try removing or changing it to something valid.
The point which deserves highlighting is that you have to use data message - data key only - to get onMessageReceived handler called even when the app is in background. You shouldn't have any other notification message key in your payload, otherwise the handler won't get triggered if the app is in background.
It is mentioned (but not so emphasized in FCM documentation) here:
https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages
Use your app server and FCM server API: Set the data key only. Can be
either collapsible or non-collapsible.
The backend I'm working with is using Notification messages and not Data messages. So after reading all the answers I tried to retrieve the extras from the bundle of the intent that comes to the launched activity.
But no matter which keys I tried to retrieve from getIntent().getExtras();, the value was always null.
However, I finally found a way to send data using Notification messages and retrieve it from the intent.
The key here is to add the data payload to the Notification message.
Example:
{
"data": {
"message": "message_body",
"title": "message_title"
},
"notification": {
"body": "test body",
"title": "test title"
},
"to": "E4An.."
}
After you do this, you will be able to get your info in this way:
intent.getExtras().getString("title")
will be message_title
and
intent.getExtras().getString("message")
will be message_body
Reference
If your problem is related to showing Big Image i.e. if you are sending push notification with an image from firebase console and it displays the image only if the app in the foreground. The solution for this problem is to send a push message with only data field. Something like this:
{ "data": { "image": "https://static.pexels.com/photos/4825/red-love-romantic-flowers.jpg", "message": "Firebase Push Message Using API" "AnotherActivity": "True" }, "to" : "device id Or Device token" }
When message is received and your app is in background the notification is sent to the extras intent of the main activity.
You can check the extra value in the oncreate() or onresume() function of the main activity.
You can check for the fields like data, table etc ( the one specified in the notification)
for example I sent using data as the key
public void onResume(){
super.onResume();
if (getIntent().getStringExtra("data")!=null){
fromnotification=true;
Intent i = new Intent(MainActivity.this, Activity2.class);
i.putExtra("notification","notification");
startActivity(i);
}
}
I think the answers to tell you change message type to data are clear to you.
But sometimes, if you cannot decide your the message type you received and you have to handle it. I post my method here. You just implemented FirebaseMessagingService and handle your message in handlIntent() method. From there you could customize your own notification. You can implement your own method sendYourNotificatoin()
class FCMPushService : FirebaseMessagingService() {
companion object {
private val TAG = "FCMPush"
}
override fun handleIntent(intent: Intent?) {
Logger.t(TAG).i("handleIntent:${intent.toString()}")
val data = intent?.extras as Bundle
val remoteMessage = RemoteMessage(data)
if (remoteMessage.data.isNotEmpty()) {
val groupId: String = remoteMessage.data[MESSAGE_KEY_GROUP_ID] ?: ""
val title = remoteMessage.notification?.title ?: ""
val body = remoteMessage.notification?.body ?: ""
if (title.isNotEmpty() && body.isNotEmpty())
sendYourNotificatoin(this, title, body, groupId)
}
}
}
I was having the same issue and did some more digging on this. When the app is in the background, a notification message is sent to the system tray, BUT a data message is sent to onMessageReceived()
See https://firebase.google.com/docs/cloud-messaging/downstream#monitor-token-generation_3
and https://github.com/firebase/quickstart-android/blob/master/messaging/app/src/main/java/com/google/firebase/quickstart/fcm/MyFirebaseMessagingService.java
To ensure that the message you are sending, the docs say, "Use your app server and FCM server API: Set the data key only. Can be either collapsible or non-collapsible."
See https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages
There are two types of messages: notification messages and data messages.
If you only send data message, that is without notification object in your message string. It would be invoked when your app in background.
Check the answer of #Mahesh Kavathiya. For my case, in server code has only like this:
{
"notification": {
"body": "here is body",
"title": "Title",
},
"to": "sdfjsdfonsdofoiewj9230idsjkfmnkdsfm"
}
You need to change to:
{
"data": {
"body": "here is body",
"title": "Title",
"click_action": "YOUR_ACTION"
},
"notification": {
"body": "here is body",
"title": "Title"
},
"to": "sdfjsdfonsdofoiewj9230idsjkfmnkdsfm"
}
Then, in case app in Background, the default activity intent extra will get "data"
Good luck!
That is the intended behavior, you need to set click_action in firebase notification data set to be able to receive data from background.
See updated answer here:
https://stackoverflow.com/a/73724040/7904082
There are 2 types of Firebase push-notifications:
1- Notification message(Display message) ->
-- 1.1 If you choose this variant, the OS will create it self a notification if app is in Background and will pass the data in the intent. Then it's up to the client to handle this data.
-- 1.2 If the app is in Foreground then the notification it will be received via callback-function in the FirebaseMessagingService and it's up to the client to handle it.
2- Data messages(up to 4k data) -> These messages are used to send only data to the client(silently) and it's up to the client to handle it for both cases background/foreground via callback-function in FirebaseMessagingService
This is according official docs:https://firebase.google.com/docs/cloud-messaging/concept-options
Just override the OnCreate method of FirebaseMessagingService. It is called when your app is in background:
public override void OnCreate()
{
// your code
base.OnCreate();
}