Android Receive Messages


Example

To receive messages, use a service that extends FirebaseMessagingService and override the onMessageReceived method.

public class MyFcmListenerService extends FirebaseMessagingService {
    
    /**
     * Called when message is received.
     *
     * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
     */
    @Override
    public void onMessageReceived(RemoteMessage message) {
        String from = message.getFrom();

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
            Map<String, String> data = message.getData();
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

        //.....
    }

When the app is in the background, Android directs notification messages to the system tray. A user tap on the notification opens the app launcher by default.

This includes messages that contain both notification and data payload (and all messages sent from the Notifications console). In these cases, the notification is delivered to the device's system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.

Here a short recap:

App stateNotificationDataBoth
ForegroundonMessageReceivedonMessageReceivedonMessageReceived
BackgroundSystem trayonMessageReceivedNotification: system tray
Data: in extras of the intent.