Firebase Push Notifications – Send and Receive Notifications with FCM - Textnotes

Firebase Push Notifications – Send and Receive Notifications with FCM


Learn how to send push notifications using Firebase Cloud Messaging (FCM) in your Android app. This tutorial covers setting up FCM, sending notifications, and receiving them in your app.

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that allows you to send notifications and messages to users on Android, iOS, and the web. FCM helps you engage users with notifications and notifications-triggered actions (such as opening the app, navigating to a specific screen, etc.).

i) Setting Up Firebase Cloud Messaging (FCM) in Your Android App

To get started with FCM, you need to set up Firebase and integrate FCM into your Android project.

Step 1: Add Firebase to Your Android Project

  1. Go to the Firebase Console: Firebase Console.
  2. Create a new project or select an existing one.
  3. Add your Android app to the Firebase project and download the google-services.json file.
  4. Place the google-services.json file in the app/ directory of your Android project.
  5. In your app-level build.gradle file, add the following dependencies:

implementation 'com.google.firebase:firebase-messaging:23.1.0' // FCM Dependency

Then sync the project with Gradle.

Step 2: Enable Firebase Cloud Messaging

  1. In the Firebase Console, go to the Cloud Messaging section.
  2. Firebase will automatically generate a Sender ID and Server Key that you’ll use to send notifications.

ii) Handling FCM Notifications in Android

Now that Firebase Cloud Messaging is integrated, let’s set up background and foreground notification handling.

Step 1: Create a Service to Handle FCM Messages

Firebase allows you to send both notification messages (displayed automatically by FCM) and data messages (handled manually by your app).

  1. Create a custom FirebaseMessagingService to handle incoming messages.

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

class MyFirebaseMessagingService : FirebaseMessagingService() {

override fun onMessageReceived(remoteMessage: RemoteMessage) {
// Check if the message contains a notification
if (remoteMessage.data.isNotEmpty()) {
// Handle data message
Log.d("FCM", "Message data payload: ${remoteMessage.data}")
}

if (remoteMessage.notification != null) {
// Handle notification message
Log.d("FCM", "Message Notification Body: ${remoteMessage.notification?.body}")
}
}

// Optional: Handle new token (to subscribe/unsubscribe users)
override fun onNewToken(token: String) {
Log.d("FCM", "New token: $token")
// Save the token or send it to your server for future notifications
}
}
  1. Register this service in your AndroidManifest.xml:

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

This service will receive both data and notification messages. The onMessageReceived() method will be called when a message is received, either in the foreground or background.

iii) Sending Push Notifications from Firebase Console

Firebase Cloud Messaging allows you to send notifications directly from the Firebase Console.

  1. Go to the Firebase Console.
  2. Navigate to Cloud Messaging under the Firebase Cloud Messaging section.
  3. Click on Send your first message.
  4. Enter a title and message body for the notification.
  5. You can send the message to specific devices, topics, or user segments. For testing, you can send it to your app instance by using the device’s token.
  6. Click Send Message.

This sends a simple notification to your device, and the message will be displayed in the notification drawer (if the app is in the background).

iv) Sending Push Notifications Programmatically

You can also send notifications programmatically from your server using Firebase's REST API. Here’s an example of how to send a data message (without a notification) to a device.

Step 1: Get the Device Token

The device token can be retrieved when your app registers with Firebase:


FirebaseMessaging.getInstance().token
.addOnCompleteListener { task ->
if (!task.isSuccessful) {
Log.w("FCM", "Fetching FCM registration token failed", task.exception)
return@addOnCompleteListener
}
val token = task.result
Log.d("FCM", "Device token: $token")
// Send this token to your backend server for future notifications
}

Step 2: Send Notification Using FCM Server API

To send a notification via Firebase Cloud Messaging API, you can use a POST request to the Firebase Cloud Messaging endpoint with the device token:

  1. Endpoint: https://fcm.googleapis.com/fcm/send
  2. Headers:
  3. Authorization: key=YOUR_SERVER_KEY
  4. Content-Type: application/json
  5. Body (Example for data message):

{
"to": "DEVICE_REGISTRATION_TOKEN",
"data": {
"title": "Hello",
"body": "This is a test message"
}
}

In Java/Kotlin (using Retrofit or OkHttp):


val url = "https://fcm.googleapis.com/fcm/send"
val client = OkHttpClient()

val requestBody = """
{
"to": "DEVICE_REGISTRATION_TOKEN",
"data": {
"title": "Hello",
"body": "This is a test message"
}
}
""".toRequestBody("application/json".toMediaType())

val request = Request.Builder()
.url(url)
.post(requestBody)
.addHeader("Authorization", "key=YOUR_SERVER_KEY")
.build()

val response = client.newCall(request).execute()

This will send a data message to the device with the given token.

v) Handling Notifications in the App

When the app is in the foreground, the notification message will not appear automatically. Instead, you can handle it and show it using the NotificationManager.

Foreground Notification Handling

In the onMessageReceived() method of FirebaseMessagingService, you can create a notification:


fun sendNotification(messageBody: String) {
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val notificationChannelId = "default_channel"
val notificationId = 1

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(notificationChannelId, "Default", NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(channel)
}

val notificationBuilder = NotificationCompat.Builder(this, notificationChannelId)
.setContentTitle("New Push Notification")
.setContentText(messageBody)
.setSmallIcon(R.drawable.ic_notification)
.setAutoCancel(true)

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

This method will create and display a notification when the app is in the foreground.

vi) Firebase Push Notifications – Benefits

  1. Cross-Platform Support: FCM supports Android, iOS, and the Web, enabling you to send notifications across all platforms.
  2. Real-time Delivery: Push notifications are delivered in real-time, providing an engaging experience for users.
  3. Automatic Background Handling: Notifications are automatically handled when the app is in the background or closed, ensuring seamless integration.
  4. Custom Data Messages: You can send custom data along with notifications to trigger specific actions in your app.
  5. Segmentation: Firebase allows you to target specific devices or groups of users based on topics, interests, and behavior.

vii) Conclusion

In this tutorial, we have learned how to integrate Firebase Push Notifications (FCM) into an Android app. We’ve covered the steps to set up Firebase Cloud Messaging, handle notifications when the app is in the foreground and background, and send notifications programmatically from your server.

By using FCM, you can easily send real-time notifications to your app users, engage them, and trigger specific actions based on the data you send with the notification.