Send a test message to a backgrounded app

To get started with FCM, build out the simplest use case: sending a test notification message from the Notifications composer to a development device when the app is in the background on the device. This page lists all the steps to achieve this, from setup to verification — it may cover steps you already completed if you have set up an Android client app for FCM.

Set up the SDK

This section covers tasks you may have completed if you have already enabled other Firebase features for your app.

Before you begin

  • Install or update Android Studio to its latest version.

  • Make sure that your project meets these requirements (note that some products might have stricter requirements):

    • Targets API level 21 (Lollipop) or higher
    • Uses Android 5.0 or higher
    • Uses Jetpack (AndroidX), which includes meeting these version requirements:
      • com.android.tools.build:gradle v7.3.0 or later
      • compileSdkVersion 28 or later
  • Set up a physical device or use an emulator to run your app.
    Note that Firebase SDKs with a dependency on Google Play services require the device or emulator to have Google Play services installed.

  • Sign into Firebase using your Google account.

If you don't already have an Android project and just want to try out a Firebase product, you can download one of our quickstart samples.

Create a Firebase project

Before you can add Firebase to your Android app, you need to create a Firebase project to connect to your Android app. Visit Understand Firebase Projects to learn more about Firebase projects.

Register your app with Firebase

To use Firebase in your Android app, you need to register your app with your Firebase project. Registering your app is often called "adding" your app to your project.

  1. Go to the Firebase console.

  2. In the center of the project overview page, click the Android icon () or Add app to launch the setup workflow.

  3. Enter your app's package name in the Android package name field.

  4. (Optional) Enter other app information: App nickname and Debug signing certificate SHA-1.

  5. Click Register app.

Add a Firebase configuration file

  1. Download and then add the Firebase Android configuration file (google-services.json) to your app:

    1. Click Download google-services.json to obtain your Firebase Android config file.

    2. Move your config file into the module (app-level) root directory of your app.

  2. To make the values in your google-services.json config file accessible to Firebase SDKs, you need the Google services Gradle plugin (google-services).

    1. In your root-level (project-level) Gradle file (<project>/build.gradle.kts or <project>/build.gradle), add the Google services plugin as a dependency:

      Kotlin

      plugins {
        id("com.android.application") version "7.3.0" apply false
        // ...
      
        // Add the dependency for the Google services Gradle plugin
        id("com.google.gms.google-services") version "4.4.2" apply false
      }

      Groovy

      plugins {
        id 'com.android.application' version '7.3.0' apply false
        // ...
      
        // Add the dependency for the Google services Gradle plugin
        id 'com.google.gms.google-services' version '4.4.2' apply false
      }
    2. In your module (app-level) Gradle file (usually <project>/<app-module>/build.gradle.kts or <project>/<app-module>/build.gradle), add the Google services plugin:

      Kotlin

      plugins {
        id("com.android.application")
      
        // Add the Google services Gradle plugin
        id("com.google.gms.google-services")
        // ...
      }

      Groovy

      plugins {
        id 'com.android.application'
      
        // Add the Google services Gradle plugin
        id 'com.google.gms.google-services'
        // ...
      }

Add Firebase SDKs to your app

  1. In your module (app-level) Gradle file (usually <project>/<app-module>/build.gradle.kts or <project>/<app-module>/build.gradle), add the dependency for the Firebase Cloud Messaging library for Android. We recommend using the Firebase Android BoM to control library versioning.

    For an optimal experience with Firebase Cloud Messaging, we recommend enabling Google Analytics in your Firebase project and adding the Firebase SDK for Google Analytics to your app.

    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:33.6.0"))
    
        // Add the dependencies for the Firebase Cloud Messaging and Analytics libraries
        // When using the BoM, you don't specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-messaging")
        implementation("com.google.firebase:firebase-analytics")
    }

    By using the Firebase Android BoM, your app will always use compatible versions of Firebase Android libraries.

    (Alternative)  Add Firebase library dependencies without using the BoM

    If you choose not to use the Firebase BoM, you must specify each Firebase library version in its dependency line.

    Note that if you use multiple Firebase libraries in your app, we strongly recommend using the BoM to manage library versions, which ensures that all versions are compatible.

    dependencies {
        // Add the dependencies for the Firebase Cloud Messaging and Analytics libraries
        // When NOT using the BoM, you must specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-messaging:24.1.0")
        implementation("com.google.firebase:firebase-analytics:22.1.2")
    }
    Looking for a Kotlin-specific library module? Starting in October 2023 (Firebase BoM 32.5.0), both Kotlin and Java developers can depend on the main library module (for details, see the FAQ about this initiative).

  2. Sync your Android project with Gradle files.

Access the registration token

To send a message to a specific device, you need to know that device's registration token. Because you'll need to enter the token in a field in the Notifications console to complete this tutorial, make sure to copy the token or securely store it after you retrieve it.

On initial startup of your app, the FCM SDK generates a registration token for the client app instance. If you want to target single devices or create device groups, you'll need to access this token by extending FirebaseMessagingService and overriding onNewToken.

This section describes how to retrieve the token and how to monitor changes to the token. Because the token could be rotated after initial startup, you are strongly recommended to retrieve the latest updated registration token.

The registration token may change when:

  • The app is restored on a new device
  • The user uninstalls/reinstall the app
  • The user clears app data.

Retrieve the current registration token

When you need to retrieve the current token, call FirebaseMessaging.getInstance().getToken():

Kotlin+KTX

FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
    if (!task.isSuccessful) {
        Log.w(TAG, "Fetching FCM registration token failed", task.exception)
        return@OnCompleteListener
    }

    // Get new FCM registration token
    val token = task.result

    // Log and toast
    val msg = getString(R.string.msg_token_fmt, token)
    Log.d(TAG, msg)
    Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
})

Java

FirebaseMessaging.getInstance().getToken()
    .addOnCompleteListener(new OnCompleteListener<String>() {
        @Override
        public void onComplete(@NonNull Task<String> task) {
          if (!task.isSuccessful()) {
            Log.w(TAG, "Fetching FCM registration token failed", task.getException());
            return;
          }

          // Get new FCM registration token
          String token = task.getResult();

          // Log and toast
          String msg = getString(R.string.msg_token_fmt, token);
          Log.d(TAG, msg);
          Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
        }
    });

Monitor token generation

The onNewToken callback fires whenever a new token is generated.

Kotlin+KTX

/**
 * Called if the FCM registration token is updated. This may occur if the security of
 * the previous token had been compromised. Note that this is called when the
 * FCM registration token is initially generated so this is where you would retrieve the token.
 */
override fun onNewToken(token: String) {
    Log.d(TAG, "Refreshed token: $token")

    // If you want to send messages to this application instance or
    // manage this apps subscriptions on the server side, send the
    // FCM registration token to your app server.
    sendRegistrationToServer(token)
}

Java

/**
 * There are two scenarios when onNewToken is called:
 * 1) When a new token is generated on initial app startup
 * 2) Whenever an existing token is changed
 * Under #2, there are three scenarios when the existing token is changed:
 * A) App is restored to a new device
 * B) User uninstalls/reinstalls the app
 * C) User clears app data
 */
@Override
public void onNewToken(@NonNull String token) {
    Log.d(TAG, "Refreshed token: " + token);

    // If you want to send messages to this application instance or
    // manage this apps subscriptions on the server side, send the
    // FCM registration token to your app server.
    sendRegistrationToServer(token);
}

After you've obtained the token, you can send it to your app server and store it using your preferred method.

Send a test notification message

  1. Install and run the app on the target device. On Apple devices, you'll need to accept the request for permission to receive remote notifications.

  2. Make sure the app is in the background on the device.

  3. In the Firebase console, open the Messaging page.

  4. If this is your first message, select Create your first campaign.

    1. Select Firebase Notification messages and select Create.
  5. Otherwise, on the Campaigns tab, select New campaign and then Notifications.

  6. Enter the message text. All other fields are optional.

  7. Select Send test message from the right pane.

  8. In the field labeled Add an FCM registration token, enter the registration token you obtained in a previous section of this guide.

  9. Select Test.

After you select Test, the targeted client device (with the app in the background) should receive the notification.

For insight into message delivery to your app, see the FCM 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.

Next steps

Send messages to foregrounded apps

Once you have successfully sent notification messages while your app is in the background, see Receive Messages in an Android App to get started sending to foregrounded apps.

Go beyond notification messages

To go beyond notification messages and add other, more advanced behavior to your app, see: