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")
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)
}
}
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")
}
}
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)
}
}
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)