To write your Firebase Cloud Messaging Android client app, use the
FirebaseMessaging
API and
Android Studio 1.4 or higher with Gradle. The instructions in this page
assume that you have completed the steps for
adding Firebase to your Android project.
FCM clients require devices running Android 4.1 or higher that also have the Google Play Store app installed, or an emulator running Android 4.1 with Google APIs. Note that you are not limited to deploying your Android apps through Google Play Store.
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:
- Targets API level 16 (Jelly Bean) or later
- Uses Gradle 4.1 or later
- Uses
Jetpack (AndroidX),
which includes meeting these version requirements:
com.android.tools.build:gradle
v3.2.1 or latercompileSdkVersion
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.
Go to the Firebase console.
In the center of the project overview page, click the Android icon (
) or Add app to launch the setup workflow.Enter your app's package name in the Android package name field.
A package name uniquely identifies your app on the device and in the Google Play Store.
A package name is often referred to as an application ID.
Find your app's package name in your module (app-level) Gradle file, usually
app/build.gradle
(example package name:com.yourcompany.yourproject
).Be aware that the package name value is case-sensitive, and it cannot be changed for this Firebase Android app after it's registered with your Firebase project.
(Optional) Enter other app information: App nickname and Debug signing certificate SHA-1.
App nickname: An internal, convenience identifier that is only visible to you in the Firebase console
Debug signing certificate SHA-1: A SHA-1 hash is required by Firebase Authentication (when using Google Sign In or phone number sign in) and Firebase Dynamic Links.
Click Register app.
Add a Firebase configuration file
Add the Firebase Android configuration file to your app:
Click Download google-services.json to obtain your Firebase Android config file (
).google-services.json Move your config file into the module (app-level) directory of your app.
The Firebase config file contains unique, but non-secret identifiers for your project. To learn more about this config file, visit Understand Firebase Projects.
You can download your Firebase config file again at any time.
Make sure the config file name is not appended with additional characters, like
(2)
.
To enable Firebase products in your app, add the google-services plugin to your Gradle files.
In your root-level (project-level) Gradle file (
build.gradle
), add rules to include the Google Services Gradle plugin. Check that you have Google's Maven repository, as well.buildscript { repositories { // Check that you have the following line (if not, add it): google() // Google's Maven repository } dependencies { // ... // Add the following line: classpath 'com.google.gms:google-services:4.3.5' // Google Services plugin } } allprojects { // ... repositories { // Check that you have the following line (if not, add it): google() // Google's Maven repository // ... } }
In your module (app-level) Gradle file (usually
app/build.gradle
), apply the Google Services Gradle plugin:apply plugin: 'com.android.application' // Add the following line: apply plugin: 'com.google.gms.google-services' // Google Services plugin android { // ... }
Add Firebase SDKs to your app
Using the Firebase Android BoM, declare the dependency for the Firebase Cloud Messaging Android library in your module (app-level) Gradle file (usually
app/build.gradle
).For an optimal experience with Firebase Cloud Messaging, we recommend enabling Google Analytics in your project. Also, as part of setting up Analytics, you need to add the Firebase SDK for Google Analytics to your app.
Java
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:26.5.0') // Declare 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 the Firebase Android libraries.
(Alternative) Declare 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 highly recommend using the BoM to manage library versions, which ensures that all versions are compatible.
dependencies { // Declare 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:21.0.1' implementation 'com.google.firebase:firebase-analytics:18.0.2' }
Kotlin+KTX
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:26.5.0') // Declare 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-ktx' implementation 'com.google.firebase:firebase-analytics-ktx' }
By using the Firebase Android BoM, your app will always use compatible versions of the Firebase Android libraries.
(Alternative) Declare 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 highly recommend using the BoM to manage library versions, which ensures that all versions are compatible.
dependencies { // Declare 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-ktx:21.0.1' implementation 'com.google.firebase:firebase-analytics-ktx:18.0.2' }
Sync your app to ensure that all dependencies have the necessary versions.
Edit your app manifest
Add the following to your app's manifest:
- A service that extends
FirebaseMessagingService
. This is required if you want to do any message handling beyond receiving notifications on apps in the background. To receive notifications in foregrounded apps, to receive data payload, to send upstream messages, and so on, you must extend this service.
<service android:name=".java.MyFirebaseMessagingService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service>
<!-- Set custom default icon. This is used when no icon is set for incoming notification messages. See README(https://goo.gl/l4GJaQ) for more. --> <meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/ic_stat_ic_notification" /> <!-- Set color used with incoming notification messages. This is used when no color is set for the incoming notification message. See README(https://goo.gl/6BKBk7) for more. --> <meta-data android:name="com.google.firebase.messaging.default_notification_color" android:resource="@color/colorAccent" />
default_notification_channel_id
to the ID of your notification channel object
as shown; FCM will use this
value whenever incoming messages do not explicitly set a notification
channel. To learn more, see
Manage notification channels.
<meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="@string/default_notification_channel_id" />
Access the device 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
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()
:
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(); } });
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() })
Monitor token generation
The onNewToken
callback fires whenever a new token is generated.
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(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); }
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) }
After you've obtained the token, you can send it to your app server and store it using your preferred method.
Check for Google Play services
Apps that rely on the Play Services SDK
should always check the device for a compatible Google Play services APK before
accessing Google Play services features. It is recommended to do this in
two places: in the main activity's onCreate()
method, and in its
onResume()
method. The check in onCreate()
ensures that the app
can't be used without a successful check. The check in onResume()
ensures
that if the user returns to the running app through some other means, such as
through the back button, the check is still performed.
If the device doesn't have a compatible version of Google Play services, your app can call
GoogleApiAvailability.makeGooglePlayServicesAvailable()
to allow users to download Google Play services from the Play Store.
Prevent auto initialization
When an FCM registration token is generated, the library uploads
the identifier and configuration data to
Firebase. If you prefer to prevent token autogeneration, disable Analytics collection and
FCM auto initialization (you must disable both) by adding these metadata values to your
AndroidManifest.xml
:
<meta-data android:name="firebase_messaging_auto_init_enabled" android:value="false" /> <meta-data android:name="firebase_analytics_collection_enabled" android:value="false" />
To re-enable FCM auto-init, make a runtime call:
Java
FirebaseMessaging.getInstance().setAutoInitEnabled(true);
Kotlin+KTX
Firebase.messaging.isAutoInitEnabled = true
To re-enable Analytics collection, call the
setAnalyticsCollectionEnabled()
method of the FirebaseAnalytics
class. For example:
setAnalyticsCollectionEnabled(true);
These values persist across app restarts once set.
Next steps
After the client app is set up, you are ready to start sending downstream messages with the Notifications composer. This functionality is demonstrated in the quickstart sample, which you can download, run, and review.
To add other, more advanced behavior to your app, you can declare an intent filter and implement an activity to respond to incoming messages. For details, see the guides for sending messages from an app server:
Keep in mind that, to take advantage of these features, you'll need a server implementation and the server procotols (HTTP or XMPP), or an implementation of the Admin SDK.