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.

· 6 min read
Wilson Ochieng

Wilson Ochieng

Android Expert developing mobile applications with 4+ Years of Experience.

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

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

Google Analytics

Image

Create Project

Image

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

- 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

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
  • Modify App-level build.gradle:

Image

Image

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


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
fV1ghvJHQViUlesik5--ks:APA91bEPS2gCtWL1QXtHc42G71CZvlkyEONn6mmrLFFmUiSaB6rKr_BtE-XOxSDnqOPaHA4nC1QO_isZSfINImu5BGEepP0RBoMyVcAn2vcvCvoB9zMcx-9Wfxftacnp2awILMuxzh9G

- Register the Service in AndroidManifest.xml:

Image

<?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
  • Click “ create your first campaign”.
Image
  • Select an option of your choice between "Firebase Notification messages" or " Firebase In-App messages"

Image
  • Enter a notification title and text, select your app, and click "Send test message."
Image

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

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

Wilson Ochieng

Android Expert developing mobile applications with 4+ Years of Experience.