Flutter: access SharedPreferences from onBackgroundMessage method of FirebaseMessaging - firebase

In my Flutter app I want to save data received from a Firebase Data Message to SharedPreferences.
I have the FirebaseMessaging object configured like this:
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) {
// this works fine
print("onMessage: ");
},
onLaunch: (Map<String, dynamic> data) {
print("onLaunch: ");
},
onResume: (Map<String, dynamic> data) {
print("onResume: ");
},
onBackgroundMessage: myBackgroundMessageHandler,
);
And this is the top-level myBackgroundMessageHandler method:
Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) {
// This doesn't work
print("background message"); // this isn't even printed!
SharedPreferences.getInstance().then(...) // here I have to save some data
}
The problem is that myBackgroundMessageHandler seems not to be called at all.
However, the notification is received on the phone.
I also tryed to remove the notification field from the message and in that case myBackgroundMessageHandler is called but the notification doesn't arrive. Is there a way to both receive the notification and trigger the method?

Related

Device didn't get message from FCM

I try to use FCM to send notification to my device but when i send it my device got nothing and i don't know did i do anything wrong ?
Plz tell me did i miss something ?
pubspec.yaml :
AndroidManifest.xml :
/android/build.gradle
/android/app/build.gradle
First of all, I think you mixed up screenshots.. but I'll give it a try:
build.gradle (App):
Add
dependencies {
implementation 'com.google.firebase:firebase-messaging:20.2.4'}
to the bottom.
on iOS devices:
You need to add the "Push Notification" Service to your Runnter Signing & Capabilities.
In your Code:
You need to initialise FCM
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print("onMessage: $message");
_showItemDialog(message);
},
onBackgroundMessage: myBackgroundMessageHandler,
onLaunch: (Map<String, dynamic> message) async {
print("onLaunch: $message");
_navigateToItemDetail(message);
},
onResume: (Map<String, dynamic> message) async {
print("onResume: $message");
_navigateToItemDetail(message);
},
);
For more information you can visit firebase_messaging installation walkthrough

Flutter fcm redirect issue

Hi in one of my flutter project, I am using firebase messaging. First a splash screen and second, the main page of the application. In second page, I implemented the firebase.configure method in the init state as follows. The _navigateToItemDetail method leads to an another page
#override
void initState() {
super.initState();
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print("onMessage: $message");
setState(() {
_newNotification = true;
});
},
onLaunch: (Map<String, dynamic> message) async {
print("onLaunch: $message");
_navigateToItemDetail(message);
},
onResume: (Map<String, dynamic> message) async {
print("onResume: $message");
_navigateToItemDetail(message);
},
);
and I cam calling the web service for this page after this. But the above method will launch after the webservice calls. So that will cause error in the page redirection. I just put a delay of 4 seconds in web service call, then it will works fine. Is there is any method to solve the issue ? async method available for firebase config ?
I think you need 'onBackgroundMessage'
firebaseMessaging.configure(
//...
onBackgroundMessage: Platform.isIOS ? null : myBackgroundMessageHandler
//...
)
//...
static Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) async {
//Do here something
}
as you can see, it only work on android

How Should I access the data elements of the notification payload in flutter?

Below is the notification payload in cloud function for FCM notification in flutter application, I am not able figure out how to access the elements of the data:{} when the notification is received in flutter application
PAYLOAD
const payload = {
notification: {
title: `NOTIFICATION2 `,
body: contentMessage,
badge: '1',
sound: 'default'
},
data: {
click_action: 'FLUTTER_NOTIFICATION_CLICK',
notification2: notificationid2,
detail: detail,
senderAvatarURL: messageRecieverSenderAvatar,
category: 'default'
}
}
NOTIFICATION CODE
firebaseMessaging.configure(onMessage: (Map<String, dynamic> message) {
print('onMessage: $message');
Platform.isAndroid ? showNotification(message['notification']) : showNotification(message['aps']['alert']);
return;
}, onResume: (Map<String, dynamic> message) {
print('onResume: $message');
return;
}, onLaunch: (Map<String, dynamic> message) {
print('onLaunch: $message');
return;
});
you can use the below code to access data :
if (message.containsKey('data')) {
// Handle data message
final dynamic data = message['data'];
}
once you got the data map, you can parse it.
the package https://pub.dev/packages/firebase_messaging shows an example of handling data messages, check part with title
Define a TOP-LEVEL or STATIC function to handle background messages

Flutter Show Notification when app is open with Firebase Messaging

the app receives all the notification that I have sent in the background or closed mode, but I also want to show the notification when the app is opened while user playing with the app.
onMessage: (Map<String, dynamic> message) async {
print("onMessage: $message");
FlutterRingtonePlayer.playNotification();
},
onLaunch: (Map<String, dynamic> message) async {
print("onLaunch: $message");
},
onResume: (Map<String, dynamic> message) async {
print("onResume: $message");
// TODO optional
},
If you want to show the notification in the System tray, as it does when the app is in the background, you can use the package flutter_local_notifications.
This way, when you receive a notification via onMessage, you can use something like this:
AndroidNotificationDetails notificationAndroidSpecifics =
AndroidNotificationDetails(
groupChannelId, groupChannelName, groupChannelDescription,
importance: Importance.Max,
priority: Priority.High,
groupKey: groupKey);
NotificationDetails notificationPlatformSpecifics =
NotificationDetails(notificationAndroidSpecifics, null);
await flutterLocalNotificationsPlugin.show(
1,
'Jeff Chang',
'Please join us to celebrate the...',
notificationPlatformSpecifics);
Check their documentation for more examples!

How to disable cloud messaging in flutter app?

I am making an app with push notifications. These are already implemented with FirebaseMessaging.
This is the code for it:
_firebaseMessaging = new FirebaseMessaging();
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) {
print("Message: " + message.toString());
},
onResume: (Map<String, dynamic> message) {
print("Message: " + message.toString());
},
onLaunch: (Map<String, dynamic> message) {
print("Message: " + message.toString());
},
);
_firebaseMessaging.getToken().then((token) {
print(token);
});
I also have a settings page in the app. There it is possible for the user to uncheck the property for receiving notifications. Under the hood, it's just a variable that is set to false at the moment.
My question is: How is it possible to disable the push notifications for those users?
You can use Firebase topics to only send notifications to devices which subscribed to a topic.
The firebase_messaging also supports topics.

Resources