Firebase
Notifications
App Development
Background Processing
Mobile App Development

How to handle notification when app in background in Firebase

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In mobile app development, handling notifications when an app is in the background can be a crucial task to ensure optimal user engagement. Firebase Cloud Messaging (FCM) provides a robust and flexible messaging solution to deliver notifications across platforms, and understanding how it works when an app is in the background is key to leveraging its full potential.

Firebase Cloud Messaging Components

  1. Notifications vs Data Messages:
    • Notification Messages: Automatically displayed by the system.
    • Data Messages: Not automatically displayed; handled in the app's code.
  2. Message Structure:
    • A typical message payload for FCM can include both notification and data keys:
json
1     {
2       "to": "device_token",
3       "notification": {
4         "title": "Notification Title",
5         "body": "Notification Body"
6       },
7       "data": {
8         "key1": "value1",
9         "key2": "value2"
10       }
11     }

Handling Notifications in Background

When the app is in the background, the FCM behaves differently based on the type of message sent:

Android

  • Notification Messages:
    • Automatically displayed in the system tray.
    • If the app is in the background, the onMessageReceived() method is not called.
    • Custom handling logic can become challenging because the system handles the display.
  • Data Messages:
    • Always delivered to the client app regardless of the app state.
    • Triggers onMessageReceived() even when the app is not in the foreground, allowing custom processing.

Example onMessageReceived() method in Android:

java
1@Override
2public void onMessageReceived(RemoteMessage remoteMessage) {
3    if (remoteMessage.getData().size() > 0) {
4        // Handle data message here
5        Map<String, String> data = remoteMessage.getData();
6        // process data
7    }
8
9    if (remoteMessage.getNotification() != null) {
10        // Handle notification message here.
11        // It's a good practice to create a Notification Builder for custom handling.
12        sendNotification(remoteMessage.getNotification().getBody());
13    }
14}
15
16private void sendNotification(String messageBody) {
17    // Implementation to build and display a notification
18}

iOS

  • Notification:
    • Handled by the Apple Push Notification Service (APNs).
    • The default behavior is to display notifications in the notification center.
  • Silent Notifications (Data Messages):
    • Requires extra setup such as enabling "Remote Notifications" and adding "content-available": 1 in the message payload.
    • Custom handling in application(_:didReceiveRemoteNotification:fetchCompletionHandler:).

Example implementation in iOS:

swift
1func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
2
3    if let messageData = userInfo["data"] as? [String: String] {
4        // Handle data here
5    }
6
7    completionHandler(.newData)
8}

Clearing Doubts with Message Configuration

Table: Message Types and Handling

| Platform | Message Type | Automatically Displayed | Custom Handling Capability | Method |
|-----------|--------------|-------------------------|----------------------------|--------|
| Android | Notification | Yes | Limited (System Handled) | - |
| Android | Data | No | Full | onMessageReceived() |
| iOS | Notification | Yes | Limited (APNs Handled) | - |
| iOS | Data | No | Full | didReceiveRemoteNotification |

Tips for Effective Notification Handling

  1. Decouple Logic:
    • Separate the logic of notification presentation from data handling. Use services or utilities for processing and notification managers for display.
  2. Synchronize Background Process:
    • For iOS, use content-available: 1 and consider silent notifications for updating content.
  3. Data-Driven Approach:
    • Use data notifications primarily and design your app logic to decide if and when to prompt the user with a notification.
  4. Testing scenarios:
    • Thoroughly test both foreground and background states on physical devices to capture realistic behaviors, as emulators can sometimes handle notifications differently.
  5. User Preferences:
    • Implement user preferences for notification types and timings to enhance user experience and minimize notification fatigue.

Handling notifications effectively when the app is in the background involves understanding FCM's nuances across different platforms and settings. By leveraging data messages and designing custom handling logic, developers can create a more engaging and seamless user experience.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.