In recent years, the development of mobile apps has significantly changed the way we communicate with users. In particular,
Push Notifications have established themselves as an effective means of communication with users.
Firebase Cloud Messaging (FCM) is a push notification service provided by Google, which is easy to integrate into applications, making it popular among many developers.
In this article, we will explain how to set up and use FCM during the development process of Android apps using Kotlin.
1. Introduction to Firebase Cloud Messaging (FCM)
FCM is a service for sending messages between the application server and the client app. This allows developers to send notifications to users in real-time and push notifications in response to specific events within the application.
For example, users can receive notifications when a friend comments on a post in a social media app, or when they receive rewards in a gaming app.
2. Installing and Setting Up FCM
2.1 Creating a Firebase Project
-
Login to the Firebase console (https://console.firebase.google.com/).
-
Create a new project, enter the project name, and click ‘Continue’.
-
You can enable Google Analytics if desired, or disable it and click the ‘Create’ button.
-
In the project dashboard, click the Android icon to add an Android app.
-
Enter the package name, app nickname, etc., and click ‘Register App’.
-
Download the google-services.json file and add it to the ‘app’ directory of your app.
2.2 Gradle Setup
Add the Google Services plugin and Firebase dependencies to the project’s build.gradle file.
// Project level build.gradle
buildscript {
dependencies {
// Add this line
classpath 'com.google.gms:google-services:4.3.10'
}
}
// App level build.gradle
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
dependencies {
// Add this line
implementation 'com.google.firebase:firebase-messaging-ktx:23.0.0'
}
3. Creating a Service for Receiving Messages
To receive messages from FCM, you need to create a service that extends FirebaseMessagingService. The service you create will
receive messages from the FCM server and handle them appropriately.
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
// Called when a message is received.
remoteMessage.notification?.let {
showNotification(it.title, it.body)
}
}
private fun showNotification(title: String?, message: String?) {
// Code to create and display the notification
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val notificationBuilder = NotificationCompat.Builder(this, "YOUR_CHANNEL_ID")
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_HIGH)
notificationManager.notify(0, notificationBuilder.build())
}
}
4. Managing FCM Tokens
The client app receives a unique token from FCM to receive messages. This token can be registered on the server to
send notifications to specific clients. Write code to manage and receive updates for the token.
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onNewToken(token: String) {
super.onNewToken(token)
// Logic to register the new token with the server
sendTokenToServer(token)
}
private fun sendTokenToServer(token: String) {
// Code to send the token to the server
}
}
5. Sending FCM Messages
On the server side, messages are sent using the issued FCM token. This is done by generating messages on a web server rather than a smartphone,
and sending them to the FCM server. For instance, you can write code to send messages using Express.js on a Node.js server.
const admin = require("firebase-admin");
admin.initializeApp();
function sendNotification(token, title, body) {
const message = {
notification: { title: title, body: body },
token: token
};
admin.messaging().send(message)
.then((response) => {
console.log("Successfully sent message:", response);
})
.catch((error) => {
console.log("Error sending message:", error);
});
}
6. Testing and Verification
Now the FCM setup is complete. Run the app to test if it can receive push notifications.
Send a message using the token from the FCM server and verify that the message received in the client app is displayed correctly.
7. Conclusion
With Firebase Cloud Messaging (FCM), developers can send notifications to users in various ways.
You have learned how to integrate FCM into an Android app through the processes described above.
Push notifications can greatly enhance the user experience and increase app engagement, so make sure to take advantage of them.
8. Additional Resources
Firebase Official Documentation: https://firebase.google.com/docs/cloud-messaging
Android Developer Documentation: https://developer.android.com/training/notify-user/group