Firebase Cloud Messaging (FCM) allows us to send messages to Android, iOS, or web applications, also known as push notifications. This article will introduce how to set up Firebase console and how to implement an Android app to receive push notifications.
The complete code can be found in .
Table of Contents
Setup Firebase Console
Go to Firebase Console. If you do not have any Firebase project, please create a new Firebase project first. Then click on the project you just created. In the left column of the project, select Cloud Messaging, as shown in the figure below. Then click on the Android icon to create an app.
After clicking, the screen below will appear. Fill in the package name of your Android app, here we fill in com.waynestalk.fcmexample
, and then click the Register app button.
Download google-services.json. Later, we will add it to our Android app project.
Next, it shows how to set the build.gradle of the Android app project to introduce the Firebase SDK.
Finally, press Continue to console button to return to the Firebase console. The FCM setting is done.
Building an Android App to Receive FCM
Importing FCM SDK into Android Project
Create a new Android project and set the package name to the one you just set in the Firebase console. We just set it to com.waynestalk.fcmexample
. And add the downloaded google-services.json to the app folder in the project.
Open the project-level build.gradle, which is project-path/build.gradle. Add the classpath of google-services as follows.
// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { ext.kotlin_version = "1.3.72" repositories { google() jcenter() } dependencies { classpath "com.android.tools.build:gradle:4.1.3" classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath 'com.google.gms:google-services:4.3.5' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { google() jcenter() } } task clean(type: Delete) { delete rootProject.buildDir }
Open the app-level build.gradle, which is project-path/app/build.gradle. In the plugins block, add the google-services plugin. Then, in the dependencies block, add three Firebase-related SDKs.
plugins { id 'com.android.application' id 'kotlin-android' id 'com.google.gms.google-services' } android { compileSdkVersion 30 buildToolsVersion "30.0.3" defaultConfig { applicationId "com.waynestalk.fcmexample" minSdkVersion 16 targetSdkVersion 30 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } } dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" implementation 'androidx.core:core-ktx:1.3.2' implementation 'androidx.appcompat:appcompat:1.2.0' implementation 'com.google.android.material:material:1.3.0' implementation 'androidx.constraintlayout:constraintlayout:2.0.4' testImplementation 'junit:junit:4.+' androidTestImplementation 'androidx.test.ext:junit:1.1.2' androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' // FCM implementation platform('com.google.firebase:firebase-bom:27.0.0') implementation 'com.google.firebase:firebase-analytics-ktx' implementation 'com.google.firebase:firebase-messaging-ktx' }
The above settings have been mentioned when creating an app in the Firebase console.
Creating FirebaseMessagingService to Receive Push Notifications
Create FcmService and inherit FirebaseMessagingService, the code is as follows.
Whenever you install the app to a new device, or reinstall the app to a device, the Firebase SDK will obtain a new token and call onNewToken() to notify the app.
Whenever push notifications sent by Firebase server are received, onMessageReceived() will be called.
class FcmService : FirebaseMessagingService() { private val tag = FcmService::class.java.name override fun onMessageReceived(remoteMessage: RemoteMessage) { super.onMessageReceived(remoteMessage) Log.d(tag, "Received FCM from ${remoteMessage.notification?.body}") } override fun onNewToken(token: String) { super.onNewToken(token) Log.d(tag, "Received FCM token: $token") } }
Finally, add FcmService to AndroidManifest.xml, and add the two intents MESSAGING_EVENT and INSTANCE_ID_EVENT.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.waynestalk.fcmexample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.AndroidFCMExample" android:usesCleartextTraffic="true"> <service android:name=".FcmService" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> <action android:name="com.google.firebase.INSTANCE_ID_EVENT" /> </intent-filter> </service> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Finally, let us execute the project. After executing the project, we can see in logcat that onNewToken() is called. This means that our app has received an FCM token.
D/com.waynestalk.fcmexample.FcmService: Received FCM token: etQxjMkGTXih_zuFwgeGjO:APA91bEpCGCD5kZnmxYm540gVu5zSDXwu_ov_-vDffxfAULiy_C07TeQA0tEy1b7A5BHEjEACMq4aWXHgypjBP4s8p5bSUruCG_Rpmxqcu8ju_aC3aIe0d8I2ZRoKQQ2fAUTY8GH9_5G
Sending Push Notifications from Firebase Console
The Firebase console allows us to send push notifications online. Open the Cloud Messaging page of the Firebase console, and then click the Send your first message button.
Enter the title and text of the push notification, and then press the Send test message button.
It will pop up the following window. Add the FCM token just received in our Android app project.
After adding, select our FCM token and press the Test button, it will send a push notification to our Android app.
When our Android app receives push notification, onMessageReceived() will be called and the following log will be printed. That’s it!
D/com.waynestalk.fcmexample.FcmService: Received FCM from Hello Wayne's Talk!
Sending FCM from Spring Boot
If you need to send FCM from a back-end app, such as Spring Boot, you can refer the following article.
Conclusion
Firebase Cloud Messaging (FCM) not only allows us to send push notifications to Android, but also to iOS and web apps. It is a cross-platform solution, and the way to use it is quite simple.