skip to content

In Firebase Cloud Messaging for Android, what is the difference between a notification message and a data message?

level: juniorimportance: must knowfreq 82%

answer

  1. who draws the tray entry
  2. notification block vs data block
  3. string keys, string values
  4. background: the SDK posts, no callback
  5. RemoteMessage.notification vs RemoteMessage.data

basics

~20 s

A notification message carries display fields (title, body, image) that the FCM SDK shows itself while the app is in the background; a data message carries only custom string pairs, handed to onMessageReceived for your code to act on.

solid answer

~40 s

An FCM message has a `notification` part, a `data` part, or both. A **notification message** carries display fields such as `title` and `body`; when the app is in the background the FCM SDK builds and posts the notification itself and never calls my code. In the foreground the SDK does not display it: it passes it to `onMessageReceived`, where `RemoteMessage.notification` holds the fields and the app decides what to show. A **data message** is a map of string keys to string values; it reaches `onMessageReceived` in the foreground and in the background, and nothing appears unless my code posts a notification. A message with both parts behaves like a notification in the background: the SDK shows the tray entry and the data rides in the extras of the intent the tap opens.

code

kotlin · 21 lines
kotlin
import android.util.Log
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage

class ParcelMessagingService : FirebaseMessagingService() {

    override fun onMessageReceived(message: RemoteMessage) {
        // Data pairs: present for data and combined messages, in any app state that calls us.
        if (message.data.isNotEmpty()) {
            Log.d(TAG, "data: ${message.data}")
        }
        // Notification fields: only seen here while the app is in the foreground.
        message.notification?.let { n ->
            Log.d(TAG, "notification: ${n.title} / ${n.body}")
        }
    }

    private companion object {
        const val TAG = "ParcelPush"
    }
}

go deeper

for a junior

Recall the two blocks and the table: a notification message is shown by the SDK in the background, a data message always goes to onMessageReceived, and data values are strings.

for a middle

Explain the foreground case too: the SDK does not draw a notification message then, it calls onMessageReceived, and a combined message's data lands in the tap intent's extras when backgrounded.

for a senior

Show you have debugged it: name the manifest defaults for icon, colour and channel, and why a team that only tests with the app open ships broken background alerts.

for a principal

Frame the payload type as a team contract: which messages the SDK may display unaided, which must run app code, and how the server and app agree on the data keys.

## Two payloads in one message format Every message an app server sends through **Firebase Cloud Messaging (FCM)** is a JSON object with exactly one target (a Firebase Installation ID, a legacy registration token, a topic or a topic condition) and up to two payloads: - **`notification`**: display fields that FCM defines, such as `title`, `body` and an image URL. The Android block of the message adds Android-only display fields such as `channel_id`, `icon`, `color` and `click_action`. - **`data`**: your own key-value pairs. Every key and every value is a **string**. The Firebase Admin SDK rejects a non-string value with "data must only contain string values", so numbers, booleans and nested objects have to be encoded as strings first, for example as JSON text inside one value. A message with only `notification` is a **notification message**, one with only `data` is a **data message**, and one with both is a **combined message**. The difference is not cosmetic: it decides **who runs code** when the message lands on the phone. ## Who handles each message on Android On the device, messages reach a class you write that extends `FirebaseMessagingService` and is declared in the manifest with the `com.google.firebase.MESSAGING_EVENT` intent filter. Its main callback is `onMessageReceived(message: RemoteMessage)`. Whether that callback runs depends on the payload and on the app's state: | App state | Notification message | Data message | Both payloads | |---|---|---|---| | Foreground | `onMessageReceived` | `onMessageReceived` | `onMessageReceived` | | Background | System tray, posted by the SDK | `onMessageReceived` | Tray entry; data in the tap intent's extras | Two consequences follow, and interviewers probe both: 1. In the **background**, the FCM SDK displays a notification message itself. Your service is not called, so logic you put in `onMessageReceived` does not run for that message. 2. In the **foreground**, the SDK does **not** display a notification message. It passes it to `onMessageReceived`, where `message.notification` exposes the title and body, and showing anything is up to your code. A data message never draws anything by itself. Whatever the app state, it arrives in `onMessageReceived` as `message.data`, and the user sees something only if your code posts a notification or updates the screen. ## What the SDK fills in for a notification message When the SDK displays a notification message for you, it completes what the payload leaves out: - **Icon and colour** come from the payload, or else from the manifest meta-data `com.google.firebase.messaging.default_notification_icon` and `com.google.firebase.messaging.default_notification_color`. With neither, Android shows the app icon rendered in white. - **Channel**: from Android 8.0 every notification belongs to a channel. The payload's `channel_id` wins; otherwise the SDK uses the manifest's `com.google.firebase.messaging.default_notification_channel_id`, and failing that a fallback channel it creates. - **Image**: if the payload names an image, the SDK downloads it with a short timeout and shows the notification without the picture when the download does not finish in time. - **Tap**: by default a tap opens the app's launcher activity. Messages composed in the Firebase console's Notifications composer are notification messages, so they follow the same background-tray rule. There is one variation on who draws the entry. On Android 10 and later, some high-priority notification messages sent through the HTTP v1 API are **proxied**: Google Play services displays them on the app's behalf without starting the app. For the question in this lesson nothing changes, because your `onMessageReceived` is still not called for a notification message in the background. ## Reading the payloads in code In `onMessageReceived`, check both parts, because a combined message delivered in the foreground carries both: - `message.data` is a `Map<String, String>`, empty for a pure notification message. - `message.notification` is null for a pure data message; otherwise it exposes `title`, `body`, `imageUrl`, `channelId` and `clickAction`. The service needs no main-thread care for this: the SDK calls `onMessageReceived` on a worker thread. ## Mistakes interviewers listen for - Saying `onMessageReceived` fires for every message. It does not fire for a notification message, or for a combined message, while the app is in the background. - Expecting a notification message to pop up while the user is inside the app. The SDK hands it to your code instead, and nothing appears unless you post it. - Putting numbers or nested objects in `data`. The Admin SDK refuses them; send strings. - Assuming a data message shows something on its own. It only runs your service. - Testing only with the app open. That path never exercises the SDK's own display, which is the one most users see.

  • Where does the data of a combined notification-and-data message go when the app is in the background?
    The FCM SDK posts the notification to the system tray and copies the data pairs into the extras of the intent the notification opens, by default the launcher activity. Your code reads them from that intent when the user taps. `onMessageReceived` is not called for that message.
  • How do you control the icon, colour and channel of notifications the SDK displays for you?
    Per message, set them in the Android notification options (`icon`, `color`, `channel_id`). App-wide, add manifest meta-data `com.google.firebase.messaging.default_notification_icon`, `default_notification_color` and `default_notification_channel_id`. Without an icon, Android shows the app icon rendered in white; without a channel, the SDK falls back to a channel of its own.

  • onMessageReceived is called for every message, whatever the app state
  • A notification message pops up on its own while the app is in the foreground
  • Data payload values can be numbers, booleans or nested JSON objects
  • A data message displays a notification without any app code
  • Testing with the app open proves that background notifications work