How do I get Firebase notifications received in the background?

1

I installed the notification service in my app, it works, it even receives notification in the background, but I wanted to save the notification message, I researched a bit and created a service (code below) works, but only when the app is open in foreground), background does not work.

public class FirebaseNotificationService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.i("PVL", "Mensagem Recebida");
        if (remoteMessage.getNotification().getBody() != null) {
            Log.i("PVL", "Mensagem recebida: " + remoteMessage.getNotification().getBody());
        } else {
            Log.i("PVL", "Mensagem recebida: " + remoteMessage.getData().get("message"));
        }

    }

}
    
asked by anonymous 02.07.2017 / 18:15

1 answer

1

The fact that you are not receiving the message when the application is in the background is why the push object is being sent as Notification . The correct one for receiving in the background is with Data name.

For example:

{
"data": {
    "title": "Push",
    "text": "Nova mensagem",
},
"priority": "Normal",
"to": "/topics/general"
}

So, in class service that mounts the notification, you will do the following to capture the text of the message:

 if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        String mensagem = remoteMessage.getData().get("text");    
    }
    
03.07.2017 / 19:12