1

When application in foreground onMessageReceived return the data but when application in background onMessageReceived don't return anything. FCM will generate auto notification while application in background or kill mode I want to stop auto generated notification.

This is my sample code:

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.e(TAG, "onMessageReceived: " + remoteMessage);
    Log.e(TAG, "onMessageReceived: " + remoteMessage.getFrom());
    Log.e(TAG, "onMessageReceived Message Body: " + remoteMessage.getNotification().getBody());
    handleNow(remoteMessage);
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
tech.mohit.garg
  • 631
  • 8
  • 18
  • Possible duplicate of [How to handle notification when app in background in Firebase](https://stackoverflow.com/questions/37711082/how-to-handle-notification-when-app-in-background-in-firebase) – Micer Dec 14 '17 at 13:18

2 Answers2

4

With FCM, you can send two types of messages to clients:

1.Notification messages - Sometimes thought of as "display messages." These are handled by the FCM SDK automatically.

2.Data messages-which are handled by the client app.

Notification messages are delivered to the notification tray when the app is in the background. For apps in the foreground, messages are handled by onMessageReceived():

So if you are using notification messages which are high priority messages you will not get callback in onMessageReceived() if your app is in background . Use Data message instead .

Follow the Documentation.

Your Data message should look like this.

{
 "message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data":{
  "Nick" : "Mario",
  "body" : "great match!",
  "Room" : "PortugalVSDenmark"
  }
 }
 }
ADM
  • 20,406
  • 11
  • 52
  • 83
2

Used Notification tray for it and it will call your onMessageReceived() method at that time.

Please check below link this helps to you.

https://firebase.google.com/docs/cloud-messaging/android/receive

Please add data tag into your json response like below:

  {
  "message":{
    "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "notification":{
      "title":"Portugal vs. Denmark",
      "body":"great match!"
    },
    "data" : {
      "Nick" : "Mario",
      "Room" : "PortugalVSDenmark"
    }
  }
}

Hope this helps you.

Jyubin Patel
  • 1,373
  • 7
  • 17