Integrating Firebase Cloud Messaging (FCM) for Push Notifications
FCM is the standard for Android push notifications. But "add Firebase" and "integrate FCM correctly" are different things. Typical problems: notifications arrive when app is open and disappear in background. Or arrive without custom sound and icon. Or token updates but server doesn't know.
FCM message types: notification vs data
This distinction is critical and often misunderstood.
Notification message (display message): FCM SDK shows notification automatically when app is in background/terminated. Customization is limited — only title, body, icon, color. onMessageReceived called in foreground, not in background.
Data message: payload contains only data without notification block. FCM doesn't show anything automatically. onMessageReceived called always — both foreground and background and terminated (via FirebaseMessagingService). Full control over display.
For most real applications the correct choice is data-only with manual notification building in onMessageReceived.
Service setup
class PushMessagingService : FirebaseMessagingService() {
override fun onNewToken(token: String) {
// Send token to server
ApiClient.registerFcmToken(token)
}
override fun onMessageReceived(message: RemoteMessage) {
val title = message.data["title"] ?: return
val body = message.data["body"] ?: return
showNotification(title, body, message.data)
}
private fun showNotification(title: String, body: String, data: Map<String, String>) {
val channelId = "default_channel"
val intent = Intent(this, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
putExtra("payload", data.toString())
}
val pendingIntent = PendingIntent.getActivity(
this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
val notification = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_notification) // Important: white icon on transparent background
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.build()
NotificationManagerCompat.from(this).notify(System.currentTimeMillis().toInt(), notification)
}
}
ic_notification — white monochrome icon 24dp. If you pass color — Android 5+ shows gray square instead of icon. This is the most common visual mistake.
Notification Channels (Android 8+)
Without a channel notification won't show on Android 8+. Channel created once on startup:
fun createNotificationChannel(context: Context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
"default_channel",
"Main notifications",
NotificationManager.IMPORTANCE_HIGH
).apply {
description = "Messages and updates"
enableLights(true)
lightColor = Color.BLUE
enableVibration(true)
}
context.getSystemService(NotificationManager::class.java)
?.createNotificationChannel(channel)
}
}
IMPORTANCE_HIGH — notification with sound and heads-up. IMPORTANCE_DEFAULT — without heads-up. Choice depends on notification type.
POST_NOTIFICATIONS permission (Android 13+)
// Android 13+ requires explicit permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
ActivityCompat.requestPermissions(
activity,
arrayOf(Manifest.permission.POST_NOTIFICATIONS),
REQUEST_CODE_NOTIFICATIONS
)
}
Request at appropriate context moment — not on first app launch, but when user enables notifications in settings.
Token lifecycle
onNewToken called on first registration and on token update (reinstall, clear data, Google Play Services update). Token must always be saved to server. On sending to outdated token FCM returns INVALID_REGISTRATION or NOT_REGISTERED — server must delete such tokens.
Get current token manually:
FirebaseMessaging.getInstance().token.addOnCompleteListener { task ->
if (task.isSuccessful) {
val token = task.result
// Send to server on every startup (for reliability)
}
}
Tags and topic subscriptions
For broadcast notifications (all users or group) — FCM Topics:
FirebaseMessaging.getInstance().subscribeToTopic("news")
.addOnCompleteListener { task ->
if (task.isSuccessful) Log.d("FCM", "Subscribed to news topic")
}
Send to topic on server: "to": "/topics/news". Delivery within minutes, not guaranteed once.
What's included
- Firebase SDK connection,
google-services.json -
FirebaseMessagingServicewith data-message handling - Notification Channels with correct parameters
- White notification icon
-
POST_NOTIFICATIONSpermission request on Android 13+ - Token lifecycle with server update
- Notification tap handling: navigation to correct screen
- Topics for group notifications
Timeline
Basic FCM integration with alert notifications: 1 day. With data-message handling, custom channels, payload-based navigation, and token lifecycle: 1.5–2 days.







