Receive messages in Android apps

Select platform:iOS+AndroidWebFlutterUnityC++


To receive messages, you can use a service that extendsFirebaseMessagingService.Your service should override theonMessageReceived andonDeletedMessagescallbacks. For a complete example, see theFirebase Cloud Messaging quickstartsample.

onMessageReceived is provided for most message types, with the followingexceptions:

  • Notification messages delivered when your app is in the background. In thiscase, the notification is delivered to the device's system tray. A user tapon a notification opens the app launcher by default.

  • Messages with both notification and data payload, when received in thebackground. In this case, the notification is delivered to the device'ssystem tray, and the data payload is delivered in the extras of the intentof your launcher Activity.

In summary:

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

For more information about message types, seeNotifications and datamessages.

TheonMessageReceived callback has a short execution window. Many factors canaffect how long this window is, including OS delays, app startup time, the mainthread being blocked by other operations, or previousonMessageReceived callstaking too long.

Caution: If processing of the message payload takes longer than a few seconds,you should make sure that the processing continues in a validprocesslifecycle.If you don't make sure this occurs,background executionlimits may causeprocessing to be paused or terminated before the task completes, which can result indelayed or missing user notifications.

For this reason, you should avoid long-running tasks (such as fetching imagesfrom a server to display in a notification) inonMessageReceived and insteadschedule a task usingWorkManager to handle any tasks that might take morethan a couple of seconds to complete. For more information on message priority and howit impacts processing, seeMessage processing for high and normal prioritymessages.

Edit the app manifest

To useFirebaseMessagingService, you need to add the following in your appmanifest:

<serviceandroid:name=".java.MyFirebaseMessagingService"android:exported="false"><intent-filter><actionandroid:name="com.google.firebase.MESSAGING_EVENT"/></intent-filter></service>

It's recommended to set default values to customize the appearance ofnotifications. You can specify a custom default icon and a custom default colorthat are applied whenever equivalent values aren't set in the notificationpayload.

Add these lines inside theapplication tag to set the custom default icon andcustom color:

<!--Setcustomdefaulticon.Thisisusedwhennoiconissetforincomingnotificationmessages.SeeREADME(https://goo.gl/l4GJaQ)formore.--><meta-dataandroid:name="com.google.firebase.messaging.default_notification_icon"android:resource="@drawable/ic_stat_ic_notification"/><!--Setcolorusedwithincomingnotificationmessages.Thisisusedwhennocolorissetfortheincomingnotificationmessage.SeeREADME(https://goo.gl/6BKBk7)formore.--><meta-dataandroid:name="com.google.firebase.messaging.default_notification_color"android:resource="@color/colorAccent"/>

Android displays and uses the custom default icon for

  • All notification messages sent from theNotificationscomposer.
  • Any notification message that doesn't explicitly set the icon in thenotification payload.

If a custom default icon isn't set and an icon isn't set in the notification payload,Android displays the application icon rendered in white.

OverrideonMessageReceived

By overriding the methodFirebaseMessagingService.onMessageReceived, you canperform actions based on the receivedRemoteMessageobject and get the message data:

Kotlin

overridefunonMessageReceived(remoteMessage:RemoteMessage){// TODO(developer): Handle FCM messages here.// Not getting messages here? See why this may be: https://goo.gl/39bRNJLog.d(TAG,"From:${remoteMessage.from}")// Check if message contains a data payload.if(remoteMessage.data.isNotEmpty()){Log.d(TAG,"Message data payload:${remoteMessage.data}")// Check if data needs to be processed by long running jobif(needsToBeScheduled()){// For long-running tasks (10 seconds or more) use WorkManager.scheduleJob()}else{// Handle message within 10 secondshandleNow()}}// Check if message contains a notification payload.remoteMessage.notification?.let{Log.d(TAG,"Message Notification Body:${it.body}")}// Also if you intend on generating your own notifications as a result of a received FCM// message, here is where that should be initiated. See sendNotification method below.}

Java

@OverridepublicvoidonMessageReceived(RemoteMessageremoteMessage){// TODO(developer): Handle FCM messages here.// Not getting messages here? See why this may be: https://goo.gl/39bRNJLog.d(TAG,"From: "+remoteMessage.getFrom());// Check if message contains a data payload.if(remoteMessage.getData().size() >0){Log.d(TAG,"Message data payload: "+remoteMessage.getData());if(/* Check if data needs to be processed by long running job */true){// For long-running tasks (10 seconds or more) use WorkManager.scheduleJob();}else{// Handle message within 10 secondshandleNow();}}// Check if message contains a notification payload.if(remoteMessage.getNotification()!=null){Log.d(TAG,"Message Notification Body: "+remoteMessage.getNotification().getBody());}// Also if you intend on generating your own notifications as a result of a received FCM// message, here is where that should be initiated. See sendNotification method below.}

OverrideonDeletedMessages

In some situations,FCM may not deliver a message. This happens whenthere are too many messages (>100) pending for your app on a particular deviceat the time it connects or if the device hasn't connected toFCM inmore than one month. In these cases, you may receive a callback toFirebaseMessagingService.onDeletedMessages(). When the app instance receivesthis callback, it should perform a full sync with your app server. If youhaven't sent a message to the app on that device within the last 4 weeks,FCM won't callonDeletedMessages().

Handle notification messages in a backgrounded app

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

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

For more information into message delivery to your app, seetheFCM reporting dashboard, which records the number of messages sent and opened on Apple and Android devices, along with data for "impressions" (notifications seen by users) for Android apps.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-17 UTC.