Send your First Message to a Backgrounded App

To get started with FCM, build out the simplest use case: sending a notification message from the Notifications composer to a specific user's 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.

Prerequisites

  • A device running Android 4.0 (Ice Cream Sandwich) or newer, and Google Play services 15.0.0 or higher.
  • The latest version of Android Studio

If you don't have an Android Studio project already, you can download one of our quickstart samples if you just want to try a Firebase feature. If you're using a quickstart, remember to get the application ID from the build.gradle file in your project's module folder (typically app/), as you'll need this package name for the next step.

Add Firebase to your app

It's time to add Firebase to your app. To do this you'll need a Firebase project and a Firebase configuration file for your app.

To create a Firebase project:

  1. Create a Firebase project in the Firebase console, if you don't already have one. Click Add project. If you already have an existing Google project associated with your mobile app, select it from the Project name drop down menu. Otherwise, enter a project name to create a new project.
  2. Optional: Edit your Project ID. Your project is given a unique ID automatically, and it's used in publicly visible Firebase features such as database URLs and your Firebase Hosting subdomain. You can change it now if you want to use a specific subdomain.
  3. Follow the remaining setup steps and click Create project (or Add Firebase if you're using an existing project) to begin provisioning resources for your project. This typically takes a few minutes. When the process completes, you'll be taken to the project overview.

Now that you have a project, you can add your Android app to it:

  1. Click Add Firebase to your Android app and follow the setup steps. If you're importing an existing Google project, this may happen automatically and you can just download the config file.
  2. When prompted, enter your app's package name. It's important to enter the package name your app is using; this can only be set when you add an app to your Firebase project.
  3. During the process, you'll download a google-services.json file. You can download this file again at any time.
  4. After you add the initialization code, run your app to send verification to the Firebase console that you've successfully installed Firebase.

Add the SDK

If you would like to integrate the Firebase libraries into one of your own projects, you need to perform a few basic tasks to prepare your Android Studio project. You may have already done this as part of adding Firebase to your app.

First, add rules to your root-level build.gradle file, to include the google-services plugin and the Google's Maven repository:

buildscript {
    // ...
    dependencies {
        // ...
        classpath 'com.google.gms:google-services:4.1.0' // google-services plugin
    }
}

allprojects {
    // ...
    repositories {
        // ...
        google() // Google's Maven repository
    }
}

Then, in your module Gradle file (usually the app/build.gradle), add the apply plugin line at the bottom of the file to enable the Gradle plugin:

apply plugin: 'com.android.application'

android {
  // ...
}

dependencies {
  // ...
  implementation 'com.google.firebase:firebase-core:16.0.3'
  implementation 'com.google.firebase:firebase-messaging:17.3.2'
  // Getting a "Could not find" error? Make sure you have
  // added the Google maven respository to your root build.gradle
}

// ADD THIS AT THE BOTTOM
apply plugin: 'com.google.gms.google-services'

You should also add the dependencies for the Firebase SDKs you want to use. We recommend starting with com.google.firebase:firebase-core, which provides Google Analytics for Firebase functionality. See the list of available libraries.

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 deletes Instance ID
  • 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 FirebaseInstanceId.getInstance().getInstanceId() as shown here.

Monitor token generation

The onNewToken callback fires whenever a new token is generated.


/**
 * Called if InstanceID token is updated. This may occur if the security of
 * the previous token had been compromised. Note that this is called when the InstanceID token
 * is initially generated so this is where you would retrieve the token.
 */
@Override
public void onNewToken(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
    // Instance ID 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. See the Instance ID API reference for full detail on the API.

Send a notification message

  1. Install and run the app on the target device.

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

  3. Open the Notifications composer and select New Message.

  4. Enter the message text.

  5. Select Single Device for the message target.

  6. In the field labeled FCM Registration Token, enter the registration token you obtained in a previous section of this guide.

After you click Send Message, targeted client devices that have the app in the background receive the notification in the system notifications tray .

For insight into message delivery to your app, see the FCM reporting dashboard, which records the number of messages sent and opened on iOS 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:

傳送您對下列選項的寶貴意見...

這個網頁
需要協助嗎?請前往我們的支援網頁