Sending Push Notifications in Android using Firebase Cloud Messaging

📖 Introduction

Push notifications play a vital role in user engagement. Whether it’s alerting users about a new message, reminding them of an event, or updating content, push notifications keep your users informed in real time.

Firebase Cloud Messaging (FCM) is Google’s service that provides reliable, scalable, and cross-platform push notifications. In this post, we’ll walk through setting up FCM in an Android app, implementing token handling, and displaying notifications — all with clean, maintainable Kotlin code.


🔥 What is Firebase Cloud Messaging (FCM)?

Firebase Cloud Messaging is a cross-platform messaging solution that allows developers to deliver messages and notifications to Android, iOS, and web apps. It supports:

  • Notification messages: Automatically handled by the OS if the app is in the background.
  • Data messages: Custom data payloads processed by the app.
  • Topic messages: Broadcast messages to multiple users.
  • Device messages: Targeted messages to specific device tokens.

Why FCM?

  • Free to use
  • Integrates easily with Firebase Authentication, Analytics
  • Robust delivery with battery optimization
  • Scalable to millions of users
Diagram showing Firebase Auth and Realtime Database flow with Kotlin code blocks and app UI flow

⚙️ Step-by-Step Integration

1️⃣ Create a Firebase Project

  1. Go to Firebase Console
  2. Click “Add Project”
  3. Follow the wizard — no need to enable Google Analytics for this tutorial
  4. Once created, navigate to Project Settings → Cloud Messaging tab to get your Server Key (used for sending messages programmatically)

2️⃣ Connect Your Android App to Firebase

  1. Register your Android app with your package name
  2. Download google-services.json
  3. Add it to your project at /app/google-services.json

3️⃣ Add Firebase Dependencies

In your root build.gradle file:

classpath 'com.google.gms:google-services:4.4.0'

In your app-level build.gradle:

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

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

Sync the project after adding these.


🔐 Registering for Push Notifications

Retrieve Device Token

Tokens are needed to uniquely identify each device:

FirebaseMessaging.getInstance().token
.addOnCompleteListener { task ->
if (task.isSuccessful) {
val token = task.result
Log.d("FCM Token", token)
// You may want to send this token to your server
}
}

You can also handle token refresh by overriding onNewToken:

override fun onNewToken(token: String) {
Log.d("NEW_TOKEN", token)
// Update your server with the new token
}

📲 Receiving Messages

Create a service to handle incoming messages:

class MyFirebaseMessagingService : FirebaseMessagingService() {

override fun onMessageReceived(remoteMessage: RemoteMessage) {
remoteMessage.notification?.let {
showNotification(it.title, it.body)
}

remoteMessage.data.isNotEmpty().let {
val data = remoteMessage.data
val customValue = data["key_name"]
// Handle custom data here
}
}

private fun showNotification(title: String?, message: String?) {
val builder = NotificationCompat.Builder(this, "fcm_channel")
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true)

val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.notify(100, builder.build())
}
}

AndroidManifest.xml Configuration

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

Notification Channel (Android 8+)

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
"fcm_channel",
"FCM Notifications",
NotificationManager.IMPORTANCE_HIGH
)
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.createNotificationChannel(channel)
}

Infographic showing steps to integrate Firebase Authentication and Realtime Database in Android apps

💬 Sending Test Push from Firebase Console

  1. Go to Firebase Console → Cloud Messaging
  2. Click “Send your first message”
  3. Enter title/message
  4. Under “Target”, select your app
  5. Click “Send Message”

Within seconds, your app will receive the push if it’s running on a device or emulator with Play Services enabled.


🧠 Real-World Use Cases

  • Messaging apps: Show new message alerts
  • News apps: Breaking news notifications
  • E-commerce: Cart reminders, delivery tracking
  • Reminder apps: Scheduled alerts and updates

🔒 Securing FCM

  • Never expose your Server Key in the client
  • Always send FCM messages from your backend or using Firebase Functions
  • Use device groups or topics for better targeting

✅ Best Practices

  • Minimize unnecessary push messages to reduce opt-outs
  • Use rich notifications with images and action buttons
  • Track open rates with Firebase Analytics
  • Monitor delivery using Firebase Cloud Messaging reports
  • Use FCM Topics for segmented targeting (e.g., news, updates)
Firebase Cloud Messaging Key Point in Android

🔑 Key Points – Push Notifications in Android with FCM

  1. What is FCM?
    Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you send messages and notifications to Android, iOS, and web apps.
  2. FCM vs Legacy GCM
    FCM is the modern alternative to the deprecated Google Cloud Messaging (GCM). It provides enhanced features like topic messaging, device groups, and analytics.
  3. Firebase Console Integration
    Projects must be linked via the Firebase Console with your Android app’s package name and google-services.json configured properly.
  4. FCM SDK Setup in Android
    Use Firebase BoM in build.gradle, initialize Firebase in Application class, and implement Firebase Messaging Service.
  5. Device Token Generation
    Each app installation gets a unique device token used for identifying message recipients.
  6. Handling Notifications
    Use FirebaseMessagingService to handle messages when the app is in the foreground. For background messages, FCM automatically handles display.
  7. Sending Test Notifications
    Use Firebase Console or server API (HTTP v1 or legacy API) to send push notifications for testing and production use.
  8. Topic Messaging
    Send targeted notifications by subscribing users to topics like “news”, “offers”, or “updates”.
  9. Data vs Notification Payload
    • Notification Payload: Automatically handled by system tray (in background).
    • Data Payload: Custom payload your app handles explicitly.
  10. Handling App Launch from Notification
    Implement intent filters to handle deep links or navigate to specific screens when users tap the notification.
  11. Security & Best Practices
  • Never expose server keys in the client.
  • Use App Check and Authentication for secure message delivery.
  1. Analytics & Delivery Reports
    Integrate Firebase Analytics to track notification opens, delivery rates, and user engagement.

🔗 Internal Links


❓ FAQ (Copy-Paste for WordPress FAQ Block)

Q1: What is Firebase Cloud Messaging (FCM)?
A: FCM is a service from Firebase that allows developers to send notifications and messages to Android, iOS, and web apps — completely free.

Q2: Do I need a server to send FCM messages?
A: For sending messages to multiple users or using custom payloads, yes. You can use your own backend or Firebase Functions.

Q3: Can FCM handle both notifications and custom data?
A: Yes. Notification payloads are shown by the system UI, while data payloads are handled by your app in the background.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top