Firebase Cloud Messaging (FCM) in an Android app using Kotlin

Vahid D
2 min readNov 17, 2023

--

To implement Firebase Cloud Messaging (FCM) in an Android app using Kotlin, you need to perform several steps. Make sure you have Firebase configured in your project. If not, follow the official Firebase setup guide for Android: Add Firebase to your Android project.

Step 1: Add Dependencies

Add the Firebase Cloud Messaging dependency to your app’s build.gradle file:

implementation 'com.google.firebase:firebase-messaging:24.0.0' // Use the latest version

Step 2: Create a Firebase Project

Create a new project on the Firebase Console and follow the setup instructions.

Step 3: Obtain the google-services.json file

Download the google-services.json file from the Firebase Console and place it in the app directory of your Android project.

Step 4: Initialize Firebase in your Application

In your Application class or the onCreate method of your main activity, initialize Firebase:

class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
FirebaseApp.initializeApp(this)
}
}

Make sure to register this application class in your manifest.

Step 5: Create a Firebase Messaging Service

Create a class that extends FirebaseMessagingService to handle incoming messages:

import android.util.Log
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage

class MyFirebaseMessagingService : FirebaseMessagingService() {

override fun onMessageReceived(remoteMessage: RemoteMessage) {
// Handle FCM messages here
Log.d(TAG, "From: ${remoteMessage.from}")

// Check if the message contains data
remoteMessage.data.isNotEmpty().let {
Log.d(TAG, "Message data payload: " + remoteMessage.data)
}

// Check if the message contains a notification payload
remoteMessage.notification?.let {
Log.d(TAG, "Message Notification Body: ${it.body}")
}
}

override fun onNewToken(token: String) {
// Handle new or refreshed FCM registration token
Log.d(TAG, "Refreshed token: $token")
// You may want to send this token to your server for further use
}

companion object {
private const val TAG = "MyFirebaseMsgService"
}
}

Step 6: Register the Service in the Manifest

Add the following to your AndroidManifest.xml:

<service
android:name=".MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>

Step 7: Test the FCM Integration

Run your app on a device or emulator. You can send test messages using the Firebase Console or programmatically from your server.

Remember to handle the received FCM messages according to your app’s requirements in the onMessageReceived method of MyFirebaseMessagingService.

This is a basic setup, and you may want to customize it based on your specific needs. Additionally, handle security considerations and ensure that your server is configured to send FCM messages to your app.

--

--