With Firebase Notifications, you can target notifications to a single, specific device. You'll need access to the registration token for the app instance on that device, in order to provide the token when composing and sending the notification in the Notifications console.
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 2.3 (Gingerbread) or newer, and Google Play services 9.6.1 or newer
- The Google Repository from the Android SDK Manager
- Android Studio 1.5 or higher
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
To add Firebase to your app you'll need a Firebase project and a Firebase configuration file for your app.
- Create a Firebase project in the Firebase console, if you don't already have one. If you already have an existing Google project associated with your mobile app, click Import Google Project. Otherwise, click Create New Project.
- 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.
- 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.
- At the end, you'll download a
google-services.json
file. You can download this file again at any time. - If you haven't done so already, copy this into your project's module folder,
typically
app/
.
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:
buildscript {
// ...
dependencies {
// ...
classpath 'com.google.gms:google-services:3.0.0'
}
}
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 {
// ...
compile 'com.google.firebase:firebase-core:9.6.1'
// Getting a "Could not find" error? Make sure you have
// the latest Google Repository in the Android SDK manager
}
// 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 Firebase Analytics
functionality. See the list of available libraries.
Access the registration token
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
FirebaseInstanceIdService
.
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.getToken()
.
This method returns null if the token has not yet been generated.
Monitor token generation
The onTokenRefresh
callback fires whenever a new token is
generated, so calling
getToken
in its context ensures that you are accessing a current, available
registration token. Make sure you have added the service to your
manifest,
then call getToken
in the context of onTokenRefresh
, and log the value as shown:
@Override public void onTokenRefresh() { // Get updated InstanceID token. String refreshedToken = FirebaseInstanceId.getInstance().getToken(); Log.d(TAG, "Refreshed token: " + refreshedToken); // 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(refreshedToken); }
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.
Receive and handle messages
If you want to receive notifications when your app is in the foreground, you need to add some message handling logic.
To receive messages, use a service that extends
FirebaseMessagingService.
Your service should override the onMessageReceived
callback,
which is provided for most message types, with the following exceptions:
-
Notifications delivered when your app is in the background. In this case, the notification is delivered to the device’s system tray. A user tap on a notification opens the app launcher by default.
-
Messages with both notification and data payload, both background and foreground. In this case, the notification is delivered to the device’s system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.
In summary:
App state | Notification | Data | Both |
---|---|---|---|
Foreground | onMessageReceived |
onMessageReceived |
onMessageReceived |
Background | System tray | onMessageReceived |
Notification: system tray Data: in extras of the intent. |
Edit the app manifest
To use FirebaseMessagingService
, you need to add the following in your
app manifest:
<service android:name=".MyFirebaseMessagingService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT"/> </intent-filter> </service>
Override onMessageReceived
By overriding the method FirebaseMessagingService.onMessageReceived
,
you can perform actions based on the received
RemoteMessage
object and get the message data:
@Override public void onMessageReceived(RemoteMessage remoteMessage) { // ... // TODO(developer): Handle FCM messages here. // Not getting messages here? See why this may be: https://goo.gl/39bRNJ Log.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()); } // 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. }
Handle notification messages in a backgrounded app
When your app is in the background, Android directs notification messages to the system tray. A user tap on the notification opens the app launcher by default.
This includes messages that contain both notification and data payload (and all messages sent from the Notifications console). In these cases, the notification is delivered to the device's system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.
Send a message from the Notifications console
-
Install and run the app on the target device.
-
Make sure the app is in the background on the device.
-
Open the Notifications tab of the Firebase console and select New Message.
-
Enter the message text.
-
Select Single Device for the message target.
-
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 .
Console fields and the message payload
When you send a notification message from the Notifications console, Google uses the fields entered in the composer in two ways:
- Fields like User segment and Expires determine the message target and delivery options.
- Fields like Message text and Custom data are sent to the client in a payload comprised of key/value pairs.
Some of these latter keys are also available through the FCM server API. For example, key/value pairs entered in Custom data are handled as a data payload for the notification. Other fields map directly to keys in the FCM notification payload.
Note that some Notifications console fields are not available through
the FCM server API. For example, you can target user segments based
on app, app version, or language in ways that are not available
using the to
field in the server API.
The keys that the Notifications console sends to clients are:
Key | Console field label | Description |
---|---|---|
notification.title |
Message title | Indicates notification title. |
notification.body |
Message text | Indicates notification body text. |
data |
Custom data | Key/value pairs that you define. These are delivered as a data payload for the app to handle. |
Keys that determine message delivery include:
Key | Console field label | Description |
---|---|---|
priority |
Priority | Sets the priority of the message. For more information, see Setting the priority of a message. |
sound |
Sound |
Indicates a sound to play when the device receives a notification. |
time_to_live |
Expires | This parameter specifies how long (in seconds) the message should be kept in FCM storage if the device is offline. For more information, see Setting the lifespan of a message. |