Ultimate Guide to Firebase Push Notifications in Android – 2024

Push notifications have become an essential part of mobile applications, enhancing user engagement and providing timely updates. Firebase Cloud Messaging (FCM) is a powerful tool that allows developers to send notifications to their users easily. In this blog, we will walk through the steps to set up push notifications in an Android application using Kotlin and Firebase Cloud Messaging.

What is Firebase Push Notification?

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably send messages at no cost. Using FCM, you can notify a client app that new email or other data is available to sync. You can send notification messages to drive user re-engagement and retention.

firebase push notification

Prerequisites

Before we start, make sure you have the following:

  • A Firebase account
  • Android Studio installed
  • Basic knowledge of Kotlin

Setting Up Firebase Project

  • Go to the Firebase Console.
  • Click on “Add project” and follow the setup steps.
  • Once your project is created, navigate to the “Project settings” and click on “Add app” to add an Android app.
  • Register your app with your app’s package name.
  • Download the google-services.json file and place it in the app directory of your Android project.

Integrating Firebase in Android Project

  1. Open your build.gradle file at the project level and add the following classpath to the dependencies section:
buildscript {
    dependencies {
        // Add this line
        classpath 'com.google.gms:google-services:4.3.3'
    }
}

2. Open your build.gradle file at the app level and add the following dependencies:

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

dependencies {
    implementation 'com.google.firebase:firebase-messaging:22.0.0'
}

3. Sync your project with Gradle files.

Configuring FCM in Android

  1. Create a service class to handle FCM messages by extending FirebaseMessagingService:
package com.example.myapp

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

class MyFirebaseMessagingService : FirebaseMessagingService() {

    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        super.onMessageReceived(remoteMessage)
        // Handle FCM messages here.
        Log.d(TAG, "From: ${remoteMessage.from}")
        Log.d(TAG, "Notification Message Body: ${remoteMessage.notification?.body}")
    }

    override fun onNewToken(token: String) {
        super.onNewToken(token)
        Log.d(TAG, "Refreshed token: $token")
        // If you want to send messages to this application instance
        // or manage this apps subscriptions on the server side,
        // send the token to your app server.
    }

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

2. Update the AndroidManifest.xml to register the service:

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

Sending a Test Notification

To send a test notification, follow these steps:

  1. Go to the Firebase Console and select your project.
  2. Navigate to the “Cloud Messaging” section.
  3. Click on “Send your first message”.
  4. Enter the notification title and text.
  5. In the “Target” section, select “Single device” and enter the device token.
  6. Click on “Send message”.

Handling Notifications

When a notification is received, you can handle it in the onMessageReceived method of MyFirebaseMessagingService. Here’s an example of how you can display the notification:

override fun onMessageReceived(remoteMessage: RemoteMessage) {
    super.onMessageReceived(remoteMessage)

    remoteMessage.notification?.let {
        val notificationBuilder = NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle(it.title)
            .setContentText(it.body)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setAutoCancel(true)

        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        // Create the notification channel (required for Android O and above)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(CHANNEL_ID, "Channel human readable title", NotificationManager.IMPORTANCE_HIGH)
            notificationManager.createNotificationChannel(channel)
        }

        notificationManager.notify(0, notificationBuilder.build())
    }
}

companion object {
    private const val CHANNEL_ID = "my_channel_id"
}

Advanced Features and Customizations

Beyond the basic setup, Firebase Cloud Messaging offers advanced features and customizations to enhance your push notification strategy. You can segment your user base to send personalized messages, schedule notifications to be sent at specific times, and use rich media such as images, videos, and action buttons to make your notifications more engaging. Additionally, integrating analytics allows you to track the effectiveness of your notifications, enabling data-driven decisions to improve user engagement and retention further. By leveraging these advanced features, you can create a more dynamic and interactive experience for your users, ensuring your messages are timely, relevant, and impactful.

Conclusion

Integrating Firebase Cloud Messaging into your Android application using Kotlin is a straightforward process that can significantly enhance your app’s user experience by providing timely and relevant notifications. By following the steps outlined in this blog, you can set up and handle push notifications in your Android app efficiently.

With this setup, you can now send targeted notifications to your users, increasing engagement and retention. Happy coding!