androidfirebasekotlinnotificationsfirebase-cloud-messaging

Firebase: Parsing JSON Body and Adding Image in Background Notifications


I'm using Firebase Cloud Messaging (FCM) to send notifications, where the title is a string and the body is in JSON format. When the app is in the foreground, I successfully receive the notification in onMessageReceived() and can parse the JSON.

However, when the app is in the background or killed, onMessageReceived() is not triggered, and Firebase automatically displays the notification, but I can't parse the JSON body or display a custom image.

parse body is in JSON format


Solution

  • From the Firebase documentation on message types:

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

    • Notification messages, sometimes thought of as "display messages." These are handled by the FCM SDK automatically.
    • Data messages, which are handled by the client app.

    Use notification messages when you want the FCM SDK to handle displaying a notification automatically when your app is running in the background. Use data messages when you want to process the messages with your own client app code.

    FCM can send a notification message including an optional data payload. In such cases, FCM handles displaying the notification payload, and the client app handles the data payload.

    So when the app is backgrounded, notification messages are handled by the system automatically.

    If you want to always handle the message in your own code, make sure that it contains a data property.