![Koda School](/_next/image?url=%2Fimages%2Flogo.png&w=96&q=75)
KodaSchool
Learn To Code
Implementing notifications in Android using Firebase
This tutorial provides a clear blueprint how to implement notifications using Firebase Cloud Messaging(FCM) in an Android application.
topics
Introduction
Integrating Firebase Cloud Messaging (FCM) into your application to send and receive messages is the first step in implementing notifications in Android using Firebase. FCM is a feature-rich service that lets you freely deliver messages and notifications to your users on the web, iOS, Android, and other platforms. Because of its exceptional scalability and dependability, this service is a great option for developers that want to send out timely notifications to their users to keep them interested.
In order to use FCM, you must first create a Firebase project in the Firebase console and include your Android app in it. This entails downloading and adding the google-services.json file to your Android project's application directory. The Firebase Messaging library is one of the Firebase dependencies that you must include in your build.gradle file. You can begin creating code to handle receiving notifications as soon as the setup is finished.
To manage notifications in your Android application, you must configure the FirebaseMessagingService class. You can specify how your application should handle incoming messages by overriding methods like onMessageReceived using this class. Display notifications and data messages are the two categories into which notifications fall. While data messages need special handling in the onMessageReceived function, display notifications are handled automatically by the FCM SDK. This gives you more flexibility and control over the notification's behavior and content.
The Firebase console, a server program, or third party services that connect with FCM can all be used to send notifications via FCM. Sending test messages and notifications to particular devices, topics, or user groups is made simple using the Firebase console's user-friendly interface. You can programmatically send messages using the Firebase Admin SDK or REST API for more complex scenarios, such delivering customized messages or initiating notifications based on server events. With this all-encompassing strategy, you can be confident that your application can provide users with rich, captivating alerts that will keep them informed and engaged.
This tutorial provides clear steps that you can follow to implement notifications using Firebase Cloud Messaging (FCM) in your android application:
Step 1:Create a Firebase Project
- Go to the Firebase Console:
- Open your web browser and navigate to Firebase Console.
- If you are not already logged in, sign in with your Google account.
![Image](/_next/image?url=https%3A%2F%2Fcdn.sanity.io%2Fimages%2Fbu96b58t%2Fproduction%2Fc3595ee3cbe271ba3de2e074deb5f33b0edec956-1316x570.png%3Fw%3D1316%26auto%3Dformat&w=3840&q=75)
Step 2:Create a New Project:
- Click on the "Add Project" button.
- Enter your project name and click "Continue."
- Follow the on-screen instructions to complete the project setup,enabling Google Analytics if needed.
Assign project name
![Image](/_next/image?url=https%3A%2F%2Fcdn.sanity.io%2Fimages%2Fbu96b58t%2Fproduction%2F93ff94bea7896fde50da589605897f08ac4bf00b-1076x575.png%3Fw%3D1076%26auto%3Dformat&w=3840&q=75)
Google Analytics
![Image](/_next/image?url=https%3A%2F%2Fcdn.sanity.io%2Fimages%2Fbu96b58t%2Fproduction%2Fe08c6da1c782d97cad8a05cb273f6e67461a5cec-1003x507.png%3Fw%3D1003%26auto%3Dformat&w=3840&q=75)
Create Project
![Image](/_next/image?url=https%3A%2F%2Fcdn.sanity.io%2Fimages%2Fbu96b58t%2Fproduction%2F003bc66612a519d04358617d333fa5c81697d58f-881x530.png%3Fw%3D881%26auto%3Dformat&w=3840&q=75)
Step 3: Add Your Android App to the Project
- Register Your App:
- In the Firebase project overview, click on the Android icon to add an Android app.
- Enter your app's package name (this must match the package name in your Android application).
Package name
![Image](/_next/image?url=https%3A%2F%2Fcdn.sanity.io%2Fimages%2Fbu96b58t%2Fproduction%2F118743b8cde79a9ae6af04074919a1550943e4ca-849x430.png%3Fw%3D849%26auto%3Dformat&w=3840&q=75)
- Optionally, enter the app nickname and the debug signing certificate SHA-1.
- Download the google-services.json File:
- Click "Register App."
- Place this file in the app directory of your Android project.
![Image](/_next/image?url=https%3A%2F%2Fcdn.sanity.io%2Fimages%2Fbu96b58t%2Fproduction%2Fb783ef6a8619e4e14209d51404e6c40f70a3eeaf-801x580.png%3Fw%3D801%26auto%3Dformat&w=3840&q=75)
Step 4:Add Firebase SDK Dependencies
- Modify Project-level build.gradle:
- Open your project-level build.gradle file and add the following classpath to the dependencies section:
![Image](/_next/image?url=https%3A%2F%2Fcdn.sanity.io%2Fimages%2Fbu96b58t%2Fproduction%2Fe0dfebeef51cdc52303685f23405c4a07e3ef7b6-896x322.png%3Fw%3D896%26auto%3Dformat&w=3840&q=75)
- Modify App-level build.gradle:
![Image](/_next/image?url=https%3A%2F%2Fcdn.sanity.io%2Fimages%2Fbu96b58t%2Fproduction%2Fbedcf5d8c159a451a3a9a3a369b66f9076fccc29-955x140.png%3Fw%3D955%26auto%3Dformat&w=3840&q=75)
![Image](/_next/image?url=https%3A%2F%2Fcdn.sanity.io%2Fimages%2Fbu96b58t%2Fproduction%2Fe22a19a51438b6d6d36f6b78685d5787d00da018-934x576.png%3Fw%3D934%26auto%3Dformat&w=3840&q=75)
Step 5 : Configure Firebase Messaging Service
- Create a Service to Handle Messages:
- Create a new Kotlin class MyFirebaseMessagingService that extends FirebaseMessagingService in FireBase.
package com.example.notificationssender
import android.content.ContentValues.TAG
import android.util.Log
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onNewToken(token: String) {
super.onNewToken(token)
Log.d(TAG, "Refreshed token: $token")
// Send the token to your server or handle it as needed
}
override fun onMessageReceived(remoteMessage: RemoteMessage) {
// Handle FCM messages here.
Log.d(TAG, "From: ${remoteMessage.from}")
// Check if message contains a data payload.
if (remoteMessage.data.isNotEmpty()) {
Log.d(TAG, "Message data payload: ${remoteMessage.data}")
handleNow()
}
// Check if message contains a notification payload.
remoteMessage.notification?.let {
Log.d(TAG, "Message Notification Body: ${it.body}")
// Show notification as needed
}
}
private fun handleNow() {
Log.d(TAG, "Short lived task is done.")
}
companion object {
private const val TAG = "MyFirebaseMsgService"
}
}
- Create a function retrieveFCMToken to enable retrieval of FCM token that will be needed in the cloud messaging section in the Firebase console.
![Image](/_next/image?url=https%3A%2F%2Fcdn.sanity.io%2Fimages%2Fbu96b58t%2Fproduction%2F027fbc5e43b19bdbe6fa744a23532b33c1528938-944x545.png%3Fw%3D944%26auto%3Dformat&w=3840&q=75)
package com.example.notificationssender
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.notificationssender.ui.theme.NotificationsSenderTheme
import com.google.firebase.messaging.FirebaseMessaging
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
NotificationsSenderTheme {
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
Greeting(
name = "Android",
modifier = Modifier.padding(innerPadding)
)
}
}
}
// Retrieve FCM token
retrieveFCMToken()
}
private fun retrieveFCMToken() {
FirebaseMessaging.getInstance().token
.addOnCompleteListener { task ->
if (task.isSuccessful) {
val token = task.result
Log.d("FCM Token", "FCM Token: $token")
// Here, you can handle the token as needed (e.g., send it to your server)
} else {
Log.e("FCM Token", "Fetching FCM token failed", task.exception)
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
NotificationsSenderTheme {
Greeting("Android")
}
}
Retrieve Token
![Image](/_next/image?url=https%3A%2F%2Fcdn.sanity.io%2Fimages%2Fbu96b58t%2Fproduction%2F2226943e67b99909651128374f2cad14eb10c63e-1231x62.png%3Fw%3D1231%26auto%3Dformat&w=3840&q=75)
fV1ghvJHQViUlesik5--ks:APA91bEPS2gCtWL1QXtHc42G71CZvlkyEONn6mmrLFFmUiSaB6rKr_BtE-XOxSDnqOPaHA4nC1QO_isZSfINImu5BGEepP0RBoMyVcAn2vcvCvoB9zMcx-9Wfxftacnp2awILMuxzh9G
- Register the Service in AndroidManifest.xml:
![Image](/_next/image?url=https%3A%2F%2Fcdn.sanity.io%2Fimages%2Fbu96b58t%2Fproduction%2F6105d044e26904792b8d50acd5d534f883e5ce4d-1258x548.png%3Fw%3D1258%26auto%3Dformat&w=3840&q=75)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.NotificationsSender"
tools:targetApi="31">
<!-- Declare Firebase Messaging Service -->
<service
android:name=".MyFirebaseMessagingService"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<activity
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.NotificationsSender">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Step 6 :Testing FCM Integration
- Send a Test Message from Firebase Console:
- Go to the Firebase Console.
- Select your project and navigate to the "Cloud Messaging" section.
![Image](/_next/image?url=https%3A%2F%2Fcdn.sanity.io%2Fimages%2Fbu96b58t%2Fproduction%2F60a6af0eb5c48fa7dcfd8226408108e0602226ff-616x523.png%3Fw%3D616%26auto%3Dformat&w=3840&q=75)
- Click “ create your first campaign”.
![Image](/_next/image?url=https%3A%2F%2Fcdn.sanity.io%2Fimages%2Fbu96b58t%2Fproduction%2F8330712dc1233426bf575ee11aee94adb9a94b55-1114x526.png%3Fw%3D1114%26auto%3Dformat&w=3840&q=75)
- Select an option of your choice between "Firebase Notification messages" or " Firebase In-App messages"
![Image](/_next/image?url=https%3A%2F%2Fcdn.sanity.io%2Fimages%2Fbu96b58t%2Fproduction%2F2aba87972d4428785071180be96b837939c10f2c-750x576.png%3Fw%3D750%26auto%3Dformat&w=3840&q=75)
- Enter a notification title and text, select your app, and click "Send test message."
![Image](/_next/image?url=https%3A%2F%2Fcdn.sanity.io%2Fimages%2Fbu96b58t%2Fproduction%2F97e3eb9302085a82c2aabd6459c19a779f65f157-1028x584.png%3Fw%3D1028%26auto%3Dformat&w=3840&q=75)
Step 7: Run Your App:
- Ensure your Android device or emulator is running and has Google Play services installed.
- Run your app and check the logcat for incoming FCM messages.
Logcat displays the message from cloud messaging service platform
![Image](/_next/image?url=https%3A%2F%2Fcdn.sanity.io%2Fimages%2Fbu96b58t%2Fproduction%2Fefe74eea40dc846c98e72a4d11524fc274b6ca7f-948x68.png%3Fw%3D948%26auto%3Dformat&w=3840&q=75)
From: 87502705632
Message Notification Body: Test Notification
Conclusion
You can successfully set up Firebase Cloud Messaging in your Android app and begin sending and receiving notifications by following these instructions. With this configuration, you can be sure that your app can manage messages both in the foreground and background, giving your users a smooth experience.
share
Android Expert developing mobile applications with 4+ Years of Experience.