Sub topic 15
Testing and debugging notification delivery
This chapter shows how to test pushes on purpose and find the reason when one does not show up. It assumes you have finished the earlier chapters: Firebase is connected, platform setup is done, you can get a token, and you know the difference between notification and data messages. You should be comfortable running curl and reading adb or Xcode console output.
Think in stages
A push passes through several hops: your sender, FCM, APNs (iOS only), the device's operating system, and your app code. A failure at any hop looks the same to the user: nothing appears. Debugging is the work of finding which hop dropped the message.
Check the device before you send
Most "FCM is broken" reports are local setup problems. Add a diagnostic function and call it once at startup in debug builds.
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
Future<void> printDeliveryDiagnostics() async {
final messaging = FirebaseMessaging.instance;
final settings = await messaging.getNotificationSettings();
debugPrint('Permission: ${settings.authorizationStatus}');
if (defaultTargetPlatform == TargetPlatform.iOS) {
final apnsToken = await messaging.getAPNSToken();
debugPrint('APNs token: ${apnsToken ?? "MISSING"}');
}
final token = await messaging.getToken();
debugPrint('FCM token: $token');
}Read the output this way:
deniedornotDeterminedmeans the system will not display notifications. Fix this before anything else.- A missing APNs token on iOS means FCM cannot reach the device through Apple. Check that the APNs authentication key is uploaded in the Firebase console, that Push Notifications and Background Modes (Remote notifications) are enabled in Xcode, and that you are on a physical device. Simulators are unreliable for real APNs delivery.
- A null FCM token usually means Firebase is not initialized correctly or Google Play services is unavailable on the Android emulator image. Use an image that includes Google Play.
Log every entry point
Attach a logger to every stream so you can see which path a message takes.
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
void logMessage(String source, RemoteMessage m) {
debugPrint('[$source] id=${m.messageId} from=${m.from} '
'title=${m.notification?.title} data=${m.data} sent=${m.sentTime}');
}
Future<void> attachMessageLoggers() async {
FirebaseMessaging.onMessage.listen((m) => logMessage('onMessage', m));
FirebaseMessaging.onMessageOpenedApp
.listen((m) => logMessage('opened', m));
final initial = await FirebaseMessaging.instance.getInitialMessage();
if (initial != null) logMessage('initial', initial);
}If a message shows up in the system tray but none of your logs fire, the system displayed it on your app's behalf. That is normal for notification messages in the background. If nothing appears anywhere, the message never reached the device, or your handler crashed.
Send test messages from the console
The Firebase console's Cloud Messaging composer is the fastest way to test. Choose Send test message, paste a registration token, and send. This isolates your app from your server code. If the console message arrives and your server's message does not, the bug is in your request.
The console can only send notification messages with optional custom data. To test a data-only message, use the HTTP v1 API.
Send from the command line
Calling the API yourself shows the exact error response. Use a short-lived access token from the Google Cloud CLI.
ACCESS_TOKEN=$(gcloud auth print-access-token)
curl -X POST \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
https://fcm.googleapis.com/v1/projects/YOUR_PROJECT_ID/messages:send \
-d '{
"message": {
"token": "DEVICE_REGISTRATION_TOKEN",
"data": { "route": "/orders/42" },
"android": { "priority": "high" },
"apns": {
"headers": {
"apns-push-type": "background",
"apns-priority": "5"
},
"payload": { "aps": { "content-available": 1 } }
}
}
}'This is a data-only message that is allowed to wake an iOS app in the background. A successful response contains a name field such as projects/your-project/messages/0:1700000000000000%abc. That value means FCM accepted the message. It does not mean the device displayed it.
Add "validate_only": true next to "message" in the request body to check your payload and token format without delivering anything.
The access token expires after about an hour. A 401 response usually means the token has expired or belongs to the wrong account.
Read the error codes
FCM returns an error.status that points to the failing hop.
| Status | HTTP | Typical cause |
|---|---|---|
| `INVALID_ARGUMENT` | 400 | Malformed token, non-string value in `data`, or reserved key names |
| `UNREGISTERED` | 404 | App uninstalled, data cleared, or token expired. Delete it from your server |
| `SENDER_ID_MISMATCH` | 403 | Token belongs to a different Firebase project than the one you are sending to |
| `THIRD_PARTY_AUTH_ERROR` | 401 | APNs key or certificate is missing, wrong, or expired |
| `QUOTA_EXCEEDED` | 429 | Sending too fast to one device, topic or project |
| `UNAVAILABLE` | 503 | Temporary FCM outage. Retry with exponential backoff |
Test each app state separately
Behavior differs by state, so run the same message through all three. Between runs, check how you left the app.
- Foreground: keep the app open. Only
onMessagefires, and no system notification appears unless you show one with a local notifications plugin. - Background: press Home, do not swipe the app away. Send the message. A notification message appears in the system tray, and a data message runs your background handler.
- Terminated: swipe the app away (Android) and send again. Tap the notification and confirm
getInitialMessagereturns it.
On Android, Force stop in system settings blocks FCM delivery to the app until it is launched again. A swipe from recent apps does not do this on most devices, but some manufacturers' battery managers behave as if it did.
Use platform logs
Flutter logs only show what Dart sees. For lower-level evidence, use the native tools.
On Android, filter logcat for FCM and your package:
adb logcat | grep -iE "FirebaseMessaging|GCM|FCM|com.example.yourapp"You can also check whether battery optimization is delaying delivery:
adb shell dumpsys deviceidle whitelist | grep com.example.yourappOn iOS, run the app from Xcode and watch the console. Use Window > Devices and Simulators > Open Console to see system messages from apsd, the daemon that handles APNs, when the app is not attached to a debugger. Release builds on a device are the final check, because debug and release builds use different APNs environments and can fail differently.
Common symptoms and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| API succeeds, nothing on iOS | APNs key missing or no push capability | Upload the key, enable capabilities, test on a device |
| Works in foreground only | Data-only message, no handler in the background | Register the top-level background handler and set `content-available` |
| Background handler never runs | Handler is not top-level or lacks the `vm:entry-point` pragma | Move it to top level and add `@pragma('vm:entry-point')` |
| Works on debug, fails on release | Release build strips code, or Android 13 permission is missing | Add `POST_NOTIFICATIONS`, and test a release build |
| Delayed by minutes | Normal priority and Doze mode | Set Android priority to `high` for time-sensitive messages |
| Duplicate notifications | Both a notification payload and a local notification are shown | Show a local notification only for foreground data messages |
A short debugging routine
- Run
printDeliveryDiagnosticsand fix anything denied or missing. - Send a console test message to the token.
- If that works, replay your server's request with
curland compare the payload. - Test foreground, background and terminated states in that order.
- Check logcat or the Xcode console.
- Repeat on a release build and a second device.
Change one thing between attempts. Several simultaneous changes hide the cause.
Exercise
Your server's FCM request returns a message ID, but an iPhone shows no notification. List three checks, in order, before you change any Dart code.
Show answer
First, confirm the app has notification permission with getNotificationSettings, since a denied status blocks display. Second, confirm getAPNSToken returns a value on a physical device, which proves APNs registration works. Third, confirm the APNs authentication key is uploaded in the Firebase console and the Push Notifications capability is enabled in Xcode. A message ID only shows that FCM accepted the request, so the failure is downstream of it.
Exercise
A data-only message reaches your Android app in the background but not an iOS app that was force-quit from the app switcher. Is this a bug in your handler? Explain.
Show answer
No. iOS does not launch a force-quit app to process background data messages. The user must open the app again before background delivery resumes. To reach such users, send a notification message, which the system displays without running your code.