Sub topic 9
Receiving messages in the background and when terminated
This chapter covers what happens when a push message arrives and your app is not in the foreground. It assumes you have already added firebase_core and firebase_messaging to a Flutter project, set up Android and iOS, requested permission, and obtained an FCM token. It also assumes you can tell notification messages from data messages.
The three app states
FCM treats your app differently depending on its state:
- Foreground: the app is open and visible.
- Background: the app is running but not visible. The user pressed Home or switched to another app, and the process is still alive.
- Terminated: the process is not running. The user swiped the app away or the system killed it.
Chapter 8 covered the foreground. Here we cover the other two. The same message can behave differently in each state, so you need to know which code path runs.
| Message type | Background | Terminated |
|---|---|---|
| Notification message (has `notification` block) | The system tray shows it. The Dart handler is not called to display it. | The system tray shows it. |
| Data-only message | The background handler runs, subject to platform limits. | Android may start a background isolate. iOS usually does not deliver it. |
| Notification plus data | The system tray shows it. The data arrives when the user taps. | Same. The data arrives when the user taps. |
Who displays the notification
With a notification message, your Dart code does not draw anything. The operating system, through the FCM SDK on Android or APNs on iOS, shows the notification in the system tray. Your code only learns about it afterwards, usually through a tap. This is why a notification message arrives even when your app has crashed or was force-stopped on some devices.
With a data-only message, nothing is shown unless your code shows it. The background handler is where you would do that, for example by calling a local notifications plugin.
Registering the background handler
The background handler must be a top-level function, or a static method. It cannot be a closure or an instance method. It runs in its own isolate, which is a separate Dart execution context with its own memory. Nothing from your main isolate is available in it: no widget state, no providers, no singletons you created in main.
For that reason, the handler must initialize Firebase itself. Annotate it with @pragma('vm:entry-point') so release builds do not tree-shake it away.
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'firebase_options.dart';
// Must be a top-level function so it can run in its own isolate.
@pragma('vm:entry-point')
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
debugPrint('Background message: ${message.messageId}');
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
runApp(const MaterialApp(home: Scaffold(body: Center(child: Text('FCM demo')))));
}Register the handler in main, before runApp. If you register it later, a message arriving during startup can be missed.
What you can do inside the handler
Because the isolate is separate, keep the work small and independent:
- Write to local storage that is safe to open from two isolates, such as a database that handles concurrent access, or
shared_preferencesafter callingreload()in the main isolate. - Call a REST endpoint to mark a message as delivered.
- Show a local notification for a data-only message.
Keep it short. Android gives a data message handler a limited time window, roughly 20 seconds, before the system may stop the process. Long downloads belong in a proper background task mechanism, not in this handler.
Because the handler is a separate isolate, any state it saves is not seen live by the running app. When the user returns to the app, read the stored data again. In a plugin like shared_preferences, that means refreshing the cache before you read.
Reacting when the user taps
A tap on a system-tray notification brings the app to the foreground, and your code is told about it in one of two ways, depending on the state before the tap.
void listenForMessages() {
// App is open and visible.
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
debugPrint('Foreground: ${message.notification?.title}');
debugPrint('Data: ${message.data}');
});
// User tapped a notification while the app was in the background.
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
debugPrint('Opened from background: ${message.data['route']}');
});
}
Future<void> checkInitialMessage() async {
// User tapped a notification that launched the app from the terminated state.
final message = await FirebaseMessaging.instance.getInitialMessage();
if (message != null) {
debugPrint('Launched from notification: ${message.data['route']}');
}
}The two entry points are separate:
onMessageOpenedAppis a stream. It fires when the app was in the background and the user tapped a notification.getInitialMessage()is a one-time future. It returns the message that launched the app from the terminated state, ornullif the app was started some other way, such as the launcher icon.
Call checkInitialMessage once, early in startup, for example from the initState of your root widget. getInitialMessage() returns the message only once for a given launch, so do not rely on calling it repeatedly. Subscribe to onMessageOpenedApp in the same place so you cover both cases. Navigation from the payload is the subject of a later chapter.
Platform differences
Background delivery is where Android and iOS differ the most.
Android
- Notification messages are shown by the system whenever the app is not in the foreground.
- Data-only messages start your handler even from the terminated state, unless the user force-stopped the app from Settings. After a force stop, Android blocks all background delivery until the user opens the app again.
- Manufacturers such as Xiaomi, Huawei, and Oppo add aggressive battery optimizations that can kill apps and block delivery. This is a device policy you cannot override from code.
- Message priority matters. A
highpriority message wakes a device in Doze mode. Anormalpriority message may be delayed until the device wakes.
iOS
- A data-only message reaches your handler only as a silent push. You must send
content-available: 1in the APNs payload, which FCM exposes ascontentAvailablein theapnsconfiguration. - iOS treats silent pushes as low priority and throttles them. They are not guaranteed.
- If the user force-quits the app by swiping it away from the app switcher, iOS does not launch it for silent pushes at all. Visible notification messages still appear.
- Enable the Background Modes capability in Xcode, with Remote notifications checked. Without it the handler never runs.
- Test on a real device. The iOS simulator can receive pushes only in limited setups and does not reflect real APNs behavior.
A request body that targets iOS silent delivery looks like this:
{
"message": {
"token": "DEVICE_REGISTRATION_TOKEN",
"data": {
"route": "/orders/42"
},
"apns": {
"headers": {
"apns-push-type": "background",
"apns-priority": "5"
},
"payload": {
"aps": {
"content-available": 1
}
}
}
}
}The apns-priority of 5 is required for background pushes. Priority 10 with content-available can be rejected.
Common mistakes
- The handler is a closure or a method. The plugin throws or the handler never runs. Make it top-level and add
@pragma('vm:entry-point'). - Firebase is not initialized inside the handler. Calls to Firebase services in the handler fail because the new isolate has no initialized app.
- UI work in the handler. Move it to the main isolate and react in
onMessageOpenedAppor at startup. - Sending a notification message and expecting the handler to run. For notification messages that arrive while the app is not in the foreground, the system tray handles them. Send a data-only message if you need your code to run.
- Testing only in debug mode. Debug builds on Android can behave differently from release builds. Verify with a release or profile build.
- Expecting guaranteed delivery. Treat a silent push as a hint, and fetch authoritative data from your server when the app opens.
Choosing a message design
Pick the design from the behavior you need:
- Show something to the user reliably: send a notification message, optionally with a
datablock for the tap. - Update local data quietly: send a data-only message with high priority on Android and a silent push on iOS, and accept that iOS may drop it.
- Show a custom notification: send a data-only message, then display it with a local notifications plugin from the handler.
Exercise
A user force-stops your Android app from Settings. You then send a data-only message to their token. Does the background handler run, and what do you need to do for it to run again?
Show answer
No. After a force stop, Android blocks background delivery to the app, so the handler does not run. Delivery resumes only after the user opens the app again, because that clears the stopped state.
Exercise
Your app launches from the terminated state when the user taps a notification. Which API do you call to read the message that caused the launch, and what does it return if the app was opened from the launcher icon?
Show answer
Call FirebaseMessaging.instance.getInitialMessage(). It returns a Future<RemoteMessage?>, and the result is null when the app was not launched by a notification tap.