DEV Community

myougaTheAxo
myougaTheAxo

Posted on

Firebase Cloud Messaging: Push Notifications and Topic Subscriptions

Firebase Cloud Messaging (FCM) enables server-sent push notifications. Learn setup, topic subscriptions, and custom message handling.

Add Firebase Messaging Dependency

implementation("com.google.firebase:firebase-messaging-ktx")
Enter fullscreen mode Exit fullscreen mode

Create Messaging Service

import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage

class MyMessagingService : FirebaseMessagingService() {
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        if (remoteMessage.notification != null) {
            val title = remoteMessage.notification!!.title
            val body = remoteMessage.notification!!.body
            showNotification(title, body)
        }

        if (remoteMessage.data.isNotEmpty()) {
            val customData = remoteMessage.data
            handleCustomPayload(customData)
        }
    }

    override fun onNewToken(token: String) {
        sendTokenToServer(token)
    }
}
Enter fullscreen mode Exit fullscreen mode

Subscribe to Topics

import com.google.firebase.messaging.ktx.messaging
import com.google.firebase.ktx.Firebase

Firebase.messaging.subscribeToTopic("news")
    .addOnCompleteListener { task ->
        if (task.isSuccessful) {
            Log.d("FCM", "Subscribed to news topic")
        }
    }
Enter fullscreen mode Exit fullscreen mode

Request Permission (Android 13+)

import android.Manifest
import androidx.activity.result.contract.ActivityResultContracts

private val requestNotificationPermission =
    registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
        if (isGranted) {
            enableFCMNotifications()
        }
    }

fun checkAndRequestPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        requestNotificationPermission.launch(Manifest.permission.POST_NOTIFICATIONS)
    }
}
Enter fullscreen mode Exit fullscreen mode

Send Test Message

Use Firebase Console → Messaging → Send Test Message with topic "news". FCM handles offline devices by queuing messages. Always include both notification and data payloads.


8 Android app templates (Habit Tracker, Budget Manager, Task Manager, and more) available on Gumroad

Top comments (0)