The problem is that When the App is running then notification is working fine (notification goes to targeted screen ) However tha app state is onPause or closwd then notification on click not open the targeted screen How i can solve it here is my code --->
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public static final String NOTIFICATION_CHANNEL_ID = "Sesame" ;
private static final String NOTIFICATION_NAME= "Sesame";
private static int count = 0;
private static final String TAG = MyFirebaseMessagingService.class.getName();
#Override
public void onMessageReceived(RemoteMessage message) {
super.onMessageReceived(message);
Map<String, String> data = message.getData();
String title = data.get("title");
String msg = data.get("message");
String deepLink = data.get("deepLink");
String slug = data.get("slug");
sendMyNotification(title,msg,deepLink,message);
}
private void sendMyNotification(String message, String body, String deeplink, RemoteMessage remoteMessage) {
Intent intent = new Intent(this,MainActivity.class);
if (remoteMessage.getData().size() >0){
if (deeplink.equals("deepLink")){
intent = new Intent(this, TermsConditionsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Log.i(TAG, "sendMyNotification: Terms ");
}}
intent.setPackage(null);
intent.addFlags(Intent.FLAG_FROM_BACKGROUND | Intent.FLAG_RECEIVER_NO_ABORT);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT |
PendingIntent.FLAG_ONE_SHOT |
PendingIntent.FLAG_IMMUTABLE);
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_HIGH;
NotificationChannel mChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,NOTIFICATION_NAME, importance);
mChannel.setDescription(message);
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mNotifyManager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, NOTIFICATION_NAME);
mBuilder.setContentTitle(message)
.setContentText(body)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setColor(Color.parseColor("#FFD600"))
.setContentIntent(pendingIntent)
.setChannelId(NOTIFICATION_CHANNEL_ID)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
.setPriority(NotificationCompat.PRIORITY_HIGH);
mNotifyManager.notify(count, mBuilder.build());
count++;}}
In my Manifest.xml file -->
<service android:name=".notifications.MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorAccent" />
</service>
And Target Activity as ->
<activity android:name=".activities.TermsConditionsActivity" >
<intent-filter>
<action android:name="deepLink"></action>
<category android:name="android.intent.category.DEFAULT"></category>
</intent-filter>
</activity>
And in my Target Activity i subscribe the topic
FirebaseMessaging.getInstance().subscribeToTopic("topic");
Please help me..
Why you activity not getting open only when app is in BG :
Reference :
Firebase onMessageReceived not called when app in background
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 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.
2: How to get call in onMessageReceived if app in BG
Refrence : Firebase onMessageReceived not called. (read this complete answer)
Your messages, that are sent from somewhere, need to have a data payload and no notification payload, or they won't arrive consistently inside of "onMessageReceived" in your MessagingService.
Related
In my android app, I have implemented firebase push notifications. I am facing a problem when I open the app through firebase push notification.
I am explaining the question with example activity names to understand the problem easily.
Let's say I have 3 activities,
Activity_A - Launcher
Activity_B - Basic information
Activity_C - Detailed information
The regular flow of my app is, to open the Activity_A --> Activity_B --> Activity_C
The regular back navigation flow is, Activity_C --> Activity_B --> Activity_A --> Exit the app
When I receive a push notification to the app and if I click it, open the Activity_B --> Activity_C.
Back navigation flow for this is similar to the regular flow. But the problem is if I exit the app when I am on Activity_A and reopen the app, Activity_B opens instead of Activity_A (Launcher).
Please can someone help me to understand this problem and fix it?
Below I have attached my manifest for the activities and the push notification creation part.
Thanks in advance.
AndroidManifest.xml
<activity
android:name=".Activity_A"
android:exported="false"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Activity_B"
android:exported="false"
android:screenOrientation="portrait" />
<activity
android:name=".Activity_C"
android:exported="false"
android:screenOrientation="portrait" />
MyFirebaseMessagingService.java
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static int count = 0;
int notiType = 0;
#Override
public void onMessageReceived(#NotNull RemoteMessage message) {
if (message.getData().size() > 0) {
JSONObject job = new JSONObject(message.getData());
notiType = job.getInt("type");
String image = job.getInt("image");
String title = job.getString("title");
String body = job.getString("body");
sendNotificationNote(title, body, image);
}
}
private void sendNotificationNote(String messageTitle, final String messageBody, String image) {
Intent intent = new Intent(this, Activity_B.class);
intent.putExtra("notiType", notiType);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_IMMUTABLE);
final String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
final NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setAutoCancel(true)
.setStyle(new NotificationCompat.BigTextStyle().bigText(messageBody))
.setPriority(Notification.PRIORITY_HIGH)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
.setOnlyAlertOnce(true)
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.setWhen(System.currentTimeMillis());
notificationBuilder.setContentTitle(messageTitle);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
notificationBuilder.setSmallIcon(R.drawable.icon_push_white);
} else {
notificationBuilder.setSmallIcon(R.drawable.app_icon_new);
}
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId, "Quirk Channel", NotificationManager.IMPORTANCE_DEFAULT);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
if (notificationManager != null) {
notificationManager.notify((int) System.currentTimeMillis() /* ID of notification */, notificationBuilder.build());
}
}
}
On tapping the push notifications user is usually redirected to the app, but some users do not get redirected to the app on tapping the push notifications.
For them the notification is simply dismissed and the app is not launched.
It might be a case, where these users have not opened the app for a long time, but would that affect the redirection to app behavior? I have also tried to reproduce this by forcing the device in doze mode, but I still get redirected to the app.
Can someone please help me solve this issue, where the user sometimes is not redirected to the app on tapping of the push notification.
This is my AndroidManifest.xml
<service
android:name=".screens.fcm.MyFirebaseMessagingService"
android:stopWithTask="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
and this is my FirebaseMessagingService
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Intent intent = new Intent(this, HomeActivity.class);
String notificationType = (remoteMessage.getData().get("notification_type") != null) ?
messageBody.getData().get("notification_type") : "";
if ((notificationType.equalsIgnoreCase("main")))
intent.putExtra("type", "main");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
RemoteMessage.Notification notification = remoteMessage.getNotification();
String notificationTitle = notification != null ? notification.getTitle() : "";
String notificationMessage = notification != null ? notification.getBody() : "";
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, "")
.setSmallIcon(R.drawable.notification)
.setContentTitle(notificationTitle)
.setContentText(notificationMessage)
.setAutoCancel(true)
.setGroup(GROUP_KEY_HOME_NOTIFICATIONS)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_HIGH);
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("",
"Channel1",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
I have integrated Firebase Cloud Messaging with my application.
When I sent a notification from the Firebase console, if the app is in background or not opened I receive successfully the notification,
otherwise if the app is in foreground or opened, I did not receive it.
All suggestions are appreciated.
When app is in foreground, notifications are not generated themselves. You need to write some additional code. When message is received onMessageReceived() method is called where you can generate the notification. Here is the code:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d("msg", "onMessageReceived: " + remoteMessage.getData().get("message"));
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
String channelId = "Default";
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(remoteMessage.getNotification().getTitle())
.setContentText(remoteMessage.getNotification().getBody()).setAutoCancel(true).setContentIntent(pendingIntent);;
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId, "Default channel", NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
}
manager.notify(0, builder.build());
}
}
FirebaseMessagingService never work when the app is in foreground. In this case if you want to receive the message from FCM then WakefulBroadcastReceiver will work for you
public class FirebaseDataReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("BroadcastReceiver::", "BroadcastReceiver");
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(intent.getExtras().getString("title"))
.setContentText(intent.getExtras().getString("message"));
NotificationManager manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
}
Link firebase with GCM in play store and write the below code in manifest
<receiver
android:name=".firebase.FirebaseDataReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</receiver>
I have an Chat app in which a user is subscribed to an topic and each group is a topic. Whenever an message is sent in the group. An notification is sent to that topic.
There are two problems that I am facing.
When the sender sends the message in the group, a notification message is sent to the topic. But before the user gets the notification from firebase, He closes the application or the app goes in the background. So According to the firebase documentations, the notification is sent to the notification tray and not the onMessageReceived callback.
The notification that is received from the firebase is added to the tray. How can the users other than the sender get the notification Id so that i can be cancelled when it required. How can this notification be customised?
Is there a way to keep an active listener for receiving the notification when the app is in the background or terminated.
Please help
You might wan to take a look this.At first I always have problem reading the doc due to english not my primary language. It very confuse but just follow the step you will get more understading.
For your first question you do not need to use both notification and data message. If you use so it will prevent onMessageReceived() get call if the app is in foreground or force close. Trust me just remove the notification{notification:"data"} but keep {data:"something"} while sending to firebase. It will always trigger onMessageReceived().
For you second question after you follow the step above you won't get any notification display on your status bar. Here you can check wether this user is the sender, if it wasn't the sender then you can just show your custom notification inside onMessageReceived().
You can push notification to your app for user engaging with fire base by sending notification,when your app is closed,on basis of some parameters go to fire base .
Make sure Your Project is Added in Fire base first before doing this at all:otherwise add your project in fire base with package name,fingerprint and google_services.json file in app folder of your project .
Fire base Cloud Messaging
it will push notification to your app, if its closed then it let the user to open the app via notification pressed, and if you wants to show notification to the user to direct to another apps of the same account , when the app will be in use both will happened with this code:
Create you first class MyFirebaseMessagingService
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String NOTIFICATION_ID_EXTRA = "notificationId";
private static final String IMAGE_URL_EXTRA = "imageUrl";
private static final String ADMIN_CHANNEL_ID ="admin_channel";
private NotificationManager notificationManager;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData().size()>0){
Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
notificationIntent.setData(Uri.parse(remoteMessage.getData().get("applink")));
PendingIntent pi = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
final PendingIntent pendingIntent = PendingIntent.getActivity(this,
0 /* Request code */, notificationIntent,
PendingIntent.FLAG_ONE_SHOT);
int notificationId = new Random().nextInt(60000);
Bitmap bitmap = getBitmapfromUrl(remoteMessage.getData().get("imageurl"));
Intent likeIntent = new Intent(this,LikeService.class);
likeIntent.putExtra(NOTIFICATION_ID_EXTRA,notificationId);
likeIntent.putExtra(IMAGE_URL_EXTRA,remoteMessage.getData().get("message"));
PendingIntent likePendingIntent = PendingIntent.getService(this,
notificationId+1,likeIntent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
setupChannels();
}
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, ADMIN_CHANNEL_ID)
.setLargeIcon(bitmap)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(remoteMessage.getData().get("title"))
.setStyle(new NotificationCompat.BigPictureStyle()
.setSummaryText(remoteMessage.getData().get("message"))
.bigPicture(bitmap))/*Notification with Image*/
.setContentText(remoteMessage.getData().get("message"))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.addAction(R.drawable.icon,
getString(R.string.notification_add_to_cart_button),likePendingIntent)
.setContentIntent(pendingIntent);
notificationManager.notify(notificationId, notificationBuilder.build());
}
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void setupChannels(){
CharSequence adminChannelName = getString(R.string.notifications_admin_channel_name);
String adminChannelDescription = getString(R.string.notifications_admin_channel_description);
NotificationChannel adminChannel;
adminChannel = new NotificationChannel(ADMIN_CHANNEL_ID, adminChannelName, NotificationManager.IMPORTANCE_LOW);
adminChannel.setDescription(adminChannelDescription);
adminChannel.enableLights(true);
adminChannel.setLightColor(Color.RED);
adminChannel.enableVibration(true);
if (notificationManager != null) {
notificationManager.createNotificationChannel(adminChannel);
}
}
public Bitmap getBitmapfromUrl(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
Create another class FirebaseIDService to get instance id service of fire base
public class FirebaseIDService extends FirebaseInstanceIdService {
public static final String FIREBASE_TOKEN = "firebase token";
#Override
public void onTokenRefresh() {
super.onTokenRefresh();
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
preferences.edit().putString(FIREBASE_TOKEN, refreshedToken).apply();
}
Make class Name LikeService
public class LikeService extends Service {
private static final String NOTIFICATION_ID_EXTRA = "notificationId";
private static final String IMAGE_URL_EXTRA = "imageUrl";
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
To Support Notification at Oreo with firebase dont forget to create Channels and this channels initialize in your First Launcher Activity.
in oncreate of your project first launcher activity include these channels;
String channelId = "1";
String channel2 = "2";
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(channelId,
"Channel 1", NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription("This is BNT");
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setShowBadge(true);
notificationManager.createNotificationChannel(notificationChannel);
NotificationChannel notificationChannel2 = new NotificationChannel(channel2,
"Channel 2",NotificationManager.IMPORTANCE_MIN);
notificationChannel.setDescription("This is bTV");
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setShowBadge(true);
notificationManager.createNotificationChannel(notificationChannel2);
}
Now you have to put your Firebase service class in Mainfest under application tag:
<service android:name=".activities.services.MyFirebaseMessagingService"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
<action android:name="com.google.android.c2dm.intent.RECEIVE"/>
</intent-filter>
</service>
<service android:name=".activities.services.FirebaseIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
Now run your app on your device before push notification with fire base make sure your code is integrated correctly then run app: and go to fire base cloud messaging:
put data as in photo according to your app: when its closed:
if your app is in use then your data written in advance option will show, its data about your promotional app of the same account, don use another account app here,
make sure your key should be like in above class as onMessagede Recieved in MyFirebaseMessagingService class
like
title ,message,applink,imageurl
I want to receive notification when the app is in background with the data-payload only. I don't want to send any notification parameters like "notification" : {"sound": "default"}
Here is my code to receive the message and build notification.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String URL_KEY = "url";
private static final String TITLE_KEY = "title";
private static final String BODY_KEY = "body";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (remoteMessage.getNotification() != null) { //Here I made the dumb mistake
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
// Notification Data initialization
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// String notificationTitle = remoteMessage.getNotification().getTitle();
String notificationTitle = remoteMessage.getData().get(TITLE_KEY);
// String notificationBody = remoteMessage.getNotification().getBody();
String notificationBody = remoteMessage.getData().get(BODY_KEY);
String receivedUrl = remoteMessage.getData().get(URL_KEY);
// BuildNotificaiton
Intent internetIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse(receivedUrl))
.setComponent(new ComponentName("com.example.suvajit.webview", "com.example.suvajit.webview.MainActivity"))
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
Random generator = new Random();
PendingIntent btn1Intent = PendingIntent.getActivity(this, generator.nextInt(), internetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle(notificationTitle)
.setContentText(notificationBody)
.setSmallIcon(R.mipmap.ic_launcher)
.setSound(defaultSoundUri)
.setAutoCancel(true)
.addAction(R.mipmap.ic_launcher, "Previous", btn1Intent) // #0
.addAction(R.mipmap.ic_launcher, "Pause", null) // #1
.addAction(R.mipmap.ic_launcher, "Next", null) // #2
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
}
This is my manifest:
<service android:name="com.example.suvajit.webview.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name="com.example.suvajit.webview.MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
And I'm sending notification using ARC
But when I'm sending only data payload notification is not received even if the app is in foreground.
{ "data": {
"url": "https://www.google.com",
"body" : "This is your message",
"title": "v-comply",
}
"to" : "dOa...hXIWnms"
}
When I'm sending sound or any thing else as notification parameter and the app is in foreground the notification is working as it should but when its in background its showing only my project name , the data part is not received I guess.
{ "data": {
"url": "https://www.google.com",
"body" : "This is your message",
"title": "v-comply",
},
"notification" : {
"sound": "default"
},
"to" : "dOa...hXIWnms"
}
Below there are two screenshots of notification when app in background and in foreground respectively.
How can I make it work to get notifications when my app is in background with only data-payload? Or am I doing something wrong? Someone please give a solution or guide me.
This was a very dumb and silly mistake which I have made. I was only sending data payload , but I was checking remoteMessage.getNotification() != null which means it doesen't run my code if there is nothing in my notification data. The condition should be like this
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (remoteMessage.getData().size() > 0) {
//Do stuffs to show notification with data payload only
}
}
After all my notification is working as expected.
This is for other users.
If someone wants to have both notification and data payload check separately they can include both conditions like this.
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (remoteMessage.getData().size() > 0) {
//Do stuffs with data payload only
}
if (remoteMessage.getNotification() != null) {
//Do stuffs with notificaiton data
}
}