Silmarilos Silmarilos - 1 month ago 45
Android Question

Firebase onMessageReceived not called when app is in the background

I am using Firebase for our messaging service in our Android app. I have researched Firebase quite a bit and I understand that whether the app if running in the foreground or now will change the type of data received in the onMessageReceived method.

What I am trying to accomplish is to parse the incoming data from the Remotemessage and do something different with it depending on custom tag. IE, if the Data Map contains a field called, "My_Custom_Tag", I want to completely override the standard firebase message that pops up and write a custom one.

The problem is, when the app is running in the background, any code I put into the onMessageReceived never gets triggered. It works just fine when the app is running in the foreground, but will not detect/ receive anything if the app is in the background.

Here is some sample code below:

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);

Map<String, String> aMap = remoteMessage.getData();
//Custom object here for easier parsing
PushNotificationsPojo pojo = this.convertResponseToPojo(aMap);

if(pojo == null){
passToFirebase(remoteMessage);
return;
}

if(pojo.getData().getCustomTag().equals(PushNotificationsPojo.ID_TAG_CHAT_MESSAGE)) {
createCustomNotification1(pojo);

} else if (pojo.getData().getCustomTag().equals(PushNotificationsPojo.ID_TAG_SOME_OTHER_MESSAGE)){
createCustomNotification2(pojo);

} else if (pojo.getData().getCustomTag().equals(PushNotificationsPojo.ID_TAG_STUFF_AND_WHATNOT)) {
createCustomNotification3(pojo);

} else {
passToFirebase(remoteMessage);
}
}


My question is, how do I go about editing MyFirebaseMessagingService so that I can check the incoming data, determine tag info, and decide to either pass it on to firebase for so it can use the standard handling or not pass it to firebase and write my own custom display notification all while my app is running in the background?

Thanks all!

PS, any chance the Firebase-Dungeon-Master Frank van Puffelen has a thought?

kws kws
Answer

Remove the notification payload from your FCM messages in order to have the data payload delivered to the onMessageReceived method.

Read this and this carefully.

When your app is in the background, data payload delivered to the onMessageReceived method only if there is no notification payload.

In case both payloads exist then system automatically handles the notification part (system tray) and your app gets the data payload in the extras of the intent of launcher Activity (after the user tap on the notification).

In order to be able to serve both platforms successfully, Android and iOS, you may have to send different FCM messages according to client's OS.