How to show a push-notification when the application is open(foreground), when OnMessage is triggered? - firebase

Im use Flutter and Firebase Messaging.
I im configure Firebase like in example: firebaseMessaging.configure(
onMessage: ...
onLaunch: ...
onResume: ...
)
But i wanna see push-notification even when app is open.
Roughly speaking onMessage should work like onResume. How can i do this?

onMessage: (Map<String, dynamic> message) async {
showNotification(message);
print('on message $message');
}
showNotification(Map<String, dynamic> msg) async {
var android = new AndroidNotificationDetails(
'your channel id',//channel id
"your channel name",//channel name
"your channel description",//channel desc todo set all this right
icon: 'mipmap/launcher_icon'//add your icon here
);
var iOS = new IOSNotificationDetails();
var platform = new NotificationDetails(android, iOS);
await flutterLocalNotificationsPlugin
.show(0, msg['notification']['title'], msg['notification']['body'], platform);
}
I used flutter_local_notifications: ^1.2.2 to show local notification foreground.
Additionally, if you are implementing for IOS don't forget to ask for notification permission.

Related

How to open my app from background and navigate to a page on receiving a notification message in flutter?

I need to open the app automatically on receiving a notification message. Is it possible in flutter?
Below is the code for handling the background messages and it works.
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp();
print('Handling a background message ${message.messageId}');
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
......
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
home: MyApp()
)
);
What I need is I have a separate page that needs to popup when that particular function is executed (When the app is in background). Can anyone help me out with this! Thanks in advance
await _firebaseMessaging.subscribeToTopic('topic name');
_firebaseMessaging.configure
(
// The onMessage function triggers when the notification is
received while we are running the app.
onMessage: (message) async
{
setState(()
{
messageTitle = message["notification"]["title"];
messageDescription = message["notification"]["description"];
notificationAlert = "New Notification Alert";
});
},
// The onResume function triggers when we receive the notification alert in the device notification bar and opens the app through the push notification itself. In this case, the app can be running in the background or not running at all.
onResume: (message) async
{
print("ON RESUME");
setState(()
{
messageTitle = message["data"]["title"];
messageDescription = message["notification"]["description"];
notificationAlert = "Application opened from Notification";
});
},
onLaunch: (Map<String, dynamic> message) async // Called when app is terminated
{
print("onLaunch: $message");
var data = message["data"];
print(data);
// Navigator.pushNamed(context, "details");
}
);
In this code the onResume function will help you run the app from background so you can code inside onResume and navigate to your specified screen.

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!

In Flutter, how do we use Firebase Messaging onBackgroundMessage to create a notification, using flutter_local_notifications?

We are working on an encrypted chat application where we use Firebase Messaging for data notifications. Some client-side logic needs to be done upon receiving a data notification, before showing an actual notification to the user. For example, a phone number will have to be translated to a local contact name. This translation is done by lookup with a map that is already available globally.
The data notifications are received just fine and the onBackgroundMessage callback is called as well. However, it seems impossible to access any kind of state from the onBackgroundMessage function. For example, printing the phone number of the logged in user returns null.
Printing this same global variable from the onMessage callback works just fine.
Running flutter_local_notifications from onMessage works fine, but again, does not work at all from onBackgroundMessage as 'no implementation could be found for the method .show()'. At the moment, it claims that flutterLocalNotificationsPlugin is null, which it isn't really.
It seems to us that onBackgroundMessage has no access to anything the app provides, as soon as the app is backgrounded. Something has to be done to make some of the scope/context available to the background process. For now, that would mainly be the flutter_local_notifications plugin in its entirety, as well as the local contacts list to translate phone number to name.
Has anyone got any idea how to do this?
Here is some of the code:
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
final _chatRepository = ChatRepository();
Future<dynamic> backgroundMessageHandler(Map<String, dynamic> message) async {
if(message.containsKey('data')) {
await _showNotification(message);
return Future<void>.value();
}
}
Future _showNotification(message) async {
List<String> numbers = [];
numbers.add(message['data']['sender']);
var name = await _chatRepository.translatePhoneNumbersToChatName(numbers);
var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
'channel id', 'channel name', 'channel description',
importance: Importance.Max, priority: Priority.High);
var iOSPlatformChannelSpecifics = new IOSNotificationDetails();
var platformChannelSpecifics = new NotificationDetails(
androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
0,
name,
message['data']['body'],
platformChannelSpecifics,
payload: message['data']['body'],
);
}
class NotificationHandler {
final FirebaseMessaging fcm = FirebaseMessaging();
StreamSubscription iosSubscription;
String deviceToken = "";
Future<void> initialize() async {
flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
var initializationSettingsAndroid =
new AndroidInitializationSettings('#mipmap/ic_launcher');
var initializationSettingsIOS = new IOSInitializationSettings(onDidReceiveLocalNotification: onDidReceiveLocalNotification);
var initializationSettings = new InitializationSettings(initializationSettingsAndroid, initializationSettingsIOS);
flutterLocalNotificationsPlugin.initialize(initializationSettings, onSelectNotification: onClickNotification);
fcm.configure(
onMessage: (Map<String, dynamic> message) async {
if(message.containsKey('data')) {
print(message);
_showNotification(message);
}
},
onBackgroundMessage: Platform.isIOS
? null
: backgroundMessageHandler,
onLaunch: (Map<String, dynamic> message) async {
if(message.containsKey('data')) {
print(message);
_showNotification(message);
}
},
onResume: (Map<String, dynamic> message) async {
if(message.containsKey('data')) {
print(message);
_showNotification(message);
}
},
);
_updateDeviceToken();
}
.
.
.
Of course, the initialize above is called early on in the application lifecycle.
class NotificationHandler {
static final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); // make it a static field of the class
// ...
}
Future _showNotification(message) async {
// ...
await NotificationHandler.flutterLocalNotificationsPlugin.show( // access it
// ...
);
}
Hope this works for you.
This plugin explains it all better than I could, but it just so happens that the background is a completely different isolate/context and thus it has no access to any plugins if they use an old (pre Flutter 12) API.
https://pub.dev/packages/android_alarm_manager#flutter-android-embedding-v1
Embedding v1 requires you to register any plugins that you want to access from the background. Doing this makes it flutter_local_notifications work properly.
Unfortunately, FCM docs are heavily lacking.

How to open a link when user clicks on Firebase notification in a Flutter App?

I am using Firebase in a Flutter app. To send notifications, I am using Firebase Messaging plugin. Whenever I send a notification using Firebase website, the notification just opens the app when user clicks on it. I want to send a notification which opens a URL instead of the app.
I don't know if this information is useful: while composing a notification on Firestore, I always put click_action as FLUTTER_NOTIFICATION_CLICK in "Custom data" section in Additional Options.
You can use onLaunch() and onResume() methods to handle notification's opening action.
for more information of notification's reaction on different platforms please see below link:
https://pub.dev/packages/firebase_messaging#receiving-messages
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print("onMessage: $message");
},
onBackgroundMessage: myBackgroundMessageHandler,
onLaunch: (Map<String, dynamic> message) async {
print("onLaunch: $message");
},
onResume: (Map<String, dynamic> message) async {
print("onResume: $message");
},
);
And you can use url_launcher to open URLs:
https://pub.dev/packages/url_launcher

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