Reputation: 2026
I am trying to display messages sent to an android device via FCM.
Just to be clear, I do not want to use the notification property in the fcm message. I prefer the data property to give the mobile developers the ability to customize the notifications.
We currently have the following setup
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
log('Got a message whilst in the Background!');
log('Message data: ${message.data}');
displayNotification();
}
Future<void> _firebaseMessagingForegroundHandler() async {
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
log('Got a message whilst in the foreground!');
log('Message data: ${message.data}');
displayNotification();
});
}
And the following:
Future<void> initFirebase() async {
await Firebase.initializeApp();
initFirebaseComponents();
}
void initFirebaseComponents() {
_firebaseTokenRefreshHandler();
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
_firebaseMessagingForegroundHandler();
}
When the Android Device is in the foreground the notifications are perfectly displayed, when the app is minimized the notifications are also perfectly displayed in the background but the moment we kill the app, the notifications are no longer displayed in the background.
I have searched and found no solution, any insight would be really appreciated.
Upvotes: 5
Views: 3725
Reputation: 7686
Since your payloads are data messages, it appears that your messages are ignored by the devices since data messages are considered low priority.
Here's a quote from the documentation:
Data-only messages are considered low priority by devices when your application is in the background or terminated, and will be ignored. You can however explicitly increase the priority by sending additional properties on the FCM payload:
On Android, set the priority field to high. On Apple (iOS & macOS), set the content-available field to true.
The solution here is to set additional properties on the payload. Below is a sample payload from the documentation that shows how the additional properties are sent.
{
token: "device token",
data: {
hello: "world",
},
// Set Android priority to "high"
android: {
priority: "high",
},
// Add APNS (Apple) config
apns: {
payload: {
aps: {
contentAvailable: true,
},
},
headers: {
"apns-push-type": "background",
"apns-priority": "5", // Must be `5` when `contentAvailable` is set to true.
"apns-topic": "io.flutter.plugins.firebase.messaging", // bundle identifier
},
},
}
Note: This only bumps the priority of the messages but it does not guarantee delivery.
Upvotes: 4