How to Handle Notifications in Background with Firebase
Firebase Cloud Messaging (FCM), use data messages instead of notification messages. Implement a FirebaseMessagingService in your app to process these messages when the app is backgrounded.Why This Happens
Firebase sends two types of messages: notification messages and data messages. Notification messages are automatically handled by the system when the app is in the background, showing a notification without invoking your app code. This means your app's code does not run to process the message in the background.
If you rely only on notification messages, your app cannot handle custom logic when in the background.
FirebaseMessaging.getInstance().send(new RemoteMessage.Builder("SENDER_ID@fcm.googleapis.com") .setMessageId("msgid_123") .addData("title", "Hello") .addData("body", "World") .build());
The Fix
Use data messages only, which always deliver the message to your app's FirebaseMessagingService, even when the app is in the background. Override onMessageReceived to handle the message and show a notification manually.
public class MyFirebaseMessagingService extends FirebaseMessagingService { @Override public void onMessageReceived(RemoteMessage remoteMessage) { if (remoteMessage.getData().size() > 0) { String title = remoteMessage.getData().get("title"); String body = remoteMessage.getData().get("body"); showNotification(title, body); } } private void showNotification(String title, String body) { NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "channel_id") .setSmallIcon(R.drawable.ic_notification) .setContentTitle(title) .setContentText(body) .setPriority(NotificationCompat.PRIORITY_HIGH); NotificationManagerCompat manager = NotificationManagerCompat.from(this); manager.notify(1001, builder.build()); } }
Prevention
Always send data-only messages from your server to ensure your app can handle notifications in all states. Avoid mixing notification and data payloads if you want full control. Test your app in background and killed states to confirm behavior.
Use notification channels on Android for better user control and compliance with system requirements.
Related Errors
- Notification not received in background: Usually caused by sending notification messages with no data payload.
- onMessageReceived not called: Happens if message is a notification message and app is backgrounded.
- Missing notification channel: On Android 8+, notifications won't show without a channel.