DEV Community

myougaTheAxo
myougaTheAxo

Posted on

FCM Push Notifications + Jetpack Compose

Firebase Cloud Messaging (FCM) enables push notifications with Jetpack Compose.

FirebaseMessagingService Implementation

class MyFirebaseMessagingService : FirebaseMessagingService() {
    override fun onNewToken(token: String) {
        sendTokenToServer(token)
        Log.d("FCM", "Token: $token")
    }

    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        val title = remoteMessage.notification?.title
        val body = remoteMessage.notification?.body
        showNotification(title, body)
    }
}
Enter fullscreen mode Exit fullscreen mode

Topic Subscriptions

FirebaseMessaging.getInstance().subscribeToTopic("promotions")
FirebaseMessaging.getInstance().unsubscribeFromTopic("promotions")
Enter fullscreen mode Exit fullscreen mode
  • Server-side: Send to topic via Firebase Console or Admin SDK
  • Automatic device grouping

Notification Channel Setup (Android 8+)

fun createNotificationChannel(context: Context) {
    val channel = NotificationCompat.Builder(context, "default")
        .setChannelId("default")
        .setName("Notifications")
        .setImportance(NotificationManager.IMPORTANCE_HIGH)
        .build()

    context.getSystemService(NotificationManager::class.java)?.createNotificationChannel(channel)
}
Enter fullscreen mode Exit fullscreen mode

Compose Settings Screen

@Composable
fun NotificationSettingsScreen(viewModel: NotificationViewModel) {
    var promotionsEnabled by remember { mutableStateOf(true) }
    var updatesEnabled by remember { mutableStateOf(true) }

    Column(Modifier.padding(16.dp)) {
        SwitchPreference(
            title = "Promotions",
            checked = promotionsEnabled,
            onCheckedChange = {
                promotionsEnabled = it
                if (it) viewModel.subscribe("promotions")
                else viewModel.unsubscribe("promotions")
            }
        )
        SwitchPreference(
            title = "Updates",
            checked = updatesEnabled,
            onCheckedChange = {
                updatesEnabled = it
                if (it) viewModel.subscribe("updates")
                else viewModel.unsubscribe("updates")
            }
        )
    }
}
Enter fullscreen mode Exit fullscreen mode

Combine with NotificationCompat for rich notifications, actions, and large images.


8 production-ready Android app templates on Gumroad.
Browse templatesGumroad

Top comments (0)