I'm working on a flutter delivery app and I want to integrate chat functionality and I found out that the StreamChat SDK is the best solution for that !
I already integrated the SDK and it's working , so to receive a notification when there is a new message I set up push notifications according to the docs in my flutter applications, when I test it up using stream CLI ,
I receive the notification and it also works when the app on the background but I don't receive anything when the app is closed and also nothing shows on the dashboard logs !
=====My code ========
await client.connectUser(
User(
id: sharedPreferences.getString('username'),
),
token,
);
var fcm = await FirebaseMessaging.instance.getToken();
await client.addDevice(fcm, PushProvider.firebase);
final channel = client.channel(
'messaging',
id: deliveryData['deliveryNumber'],
extraData: {
"name": deliveryData['title'],
},
);
final currentUserId = client.state.user.id;
client
.on(
EventType.messageNew,
EventType.notificationMessageNew,
)
.listen((event) async {
if (event.message?.user?.id == currentUserId) {
return;
}
final flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
final initializationSettingsAndroid =
AndroidInitializationSettings('launch_background');
final initializationSettings = InitializationSettings(
android: initializationSettingsAndroid,
);
await flutterLocalNotificationsPlugin
.initialize(initializationSettings);
await flutterLocalNotificationsPlugin.show(
event.message.id.hashCode,
'New message from : ' + event.message.user.name,
event.message.text,
NotificationDetails(
android: AndroidNotificationDetails(
'message channel',
'Message channel',
'Channel used for showing messages',
icon: '#drawable/notification',
priority: Priority.high,
importance: Importance.high,
),
),
);
});
I found the solution for that , the problem was that I used channel.watch(); instead, I should also add the user to the channel
channel.addMembers(["thierry", "josh"]); in order to receive push notifications as it is mentioned in the docs
Watchers vs Members
The concepts of watchers vs members can require a bit of clarification:
members: a permanent association between a user and a channel. If the
user is online and not watching the channel they will receive a
notification event, if they are offline they will receive a push
notification.
watchers: the list of watchers is temporary. It's anyone who is
currently watching the channel.
Being able to send messages, and otherwise engage with a channel as a non-member requires certain permissions. For example, we have pre-configured permissions on our livestream channel type to allow non-members to interact, but in the messaging channel type, only members of the channel can interact.
Related
In my flutter project, I already have notifications set up using firebase_messaging for Android and iOS. I am trying to add the same for Web. I had tried it before (mostly changing index.html with firebase-configs and initializing), but it had not worked then and I had left it. Now their document asks to use the new way, which asks only to configure it in the dart-files, and talks nothing about doing anything on index or other js files. So I have removed imports, and initialization from index.html, and not added any other file ( I have tried adding empty firebase-messaging-sw.js and removing it). This is the error I am getting:
[firebase_messaging/failed-service-worker-registration] Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('http://localhost:44055/firebase-cloud-messaging-push-scope') with script ('http://localhost:44055/firebase-messaging-sw.js'): A bad HTTP response code (404) was received when fetching the script. .
What am I missing? Are those steps incomplete? I also tried the steps in this article , but still have the same issues.
Edit
These are all the code-parts related to firebase-messaging.
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
firebaseAnalytics = FirebaseAnalytics.instance;
firebaseMessaging = FirebaseMessaging.instance; //
final notificationSettings = await firebaseMessaging.requestPermission();
debugPrint('User granted permission: ${notificationSettings.authorizationStatus}');
if (!kIsWeb) {
FirebaseMessaging.onBackgroundMessage(
_firebaseMessagingBackgroundHandler);
channel = const AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
description: 'This channel is used for important notifications.',
// description
importance: Importance.max,
);
flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
/// Create an Android Notification Channel.
///
/// We use this channel in the `AndroidManifest.xml` file to override the
/// default FCM channel to enable heads up notifications.
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
/// Update the iOS foreground notification presentation options to allow
/// heads up notifications.
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
}
.
.
.
.
.
.
.
.
if (kIsWeb) {
// this is where the code throws error:
token = (await firebaseMessaging.getToken(
vapidKey: "BLn....pH8",
))!;
} else {
token = (await firebaseMessaging.getToken())!;
}
I saw different question regarding this topic like this one:
Flutter send local notification when app is closed (alarm)
Some of them with accepted answers but nothing seems to work with latest version. Notification package has changed and all of these examples are deprecated.
I tried actual version (flutter_local_notifications: ^12.0.0) and as soon as I close the app I don't receive any notification at all.
const AndroidNotificationChannel channel = AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
importance: Importance.high,
);
var detroit = tz.getLocation('America/Detroit');
var now = tz.TZDateTime.now(detroit);
await _flutterLocalNotificationsPlugin.zonedSchedule(
0,
'scheduled title',
'scheduled body',
tz.TZDateTime.now(now.location).add(const Duration(seconds: 5)),
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
),
),
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
);
The only notifications that I implemented in the background are the ones coming from firebase cloud functions, but I don't want to rely on this for simple notifications (specially because of the plan).
Is there anything working out there?
This was already working. The trick was to not test on debug:
flutter run --release
I want to open the application automatically when a firebase notification is received, without user interaction. means when my application is killed or in the background and when the user receives a firebase notification the application should open automatic without user interaction or clicking on the notification is this possible in the flutter
I want to add this feature in the video calling application that when I receive a notification the call screen with accept reject button should render and I also want to add the autoanswer feature in it.
You can achieve this in Android but Its not possible in iOS for now, For android its Full-screen intent notifications and for iOS most you can do is set an custom ringtone when notification is received, You can use the below mentioned library for most of your notification needs:-pub.dev/packages/flutter_local_notifications
yes, obviously it's possible
u can do like this
demo video link : click here for watch video
Future<void> _showNotification() async {
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails(
'your channel id',
'your channel name',
channelDescription: 'your channel description',
importance: Importance.max,
priority: Priority.high,
icon: '#mipmap/ic_launcher',
// playSound: false,
);
const NotificationDetails platformChannelSpecifics = NotificationDetails(
android: androidPlatformChannelSpecifics,
);
await flutterLocalNotificationsPlugin.show(
0,
'plain title',
'plain body',
platformChannelSpecifics,
payload: 'item x',
);
}
Hello I need to make local notification on mobile whenever a button is pressed. And i don't want to make the notification instantly but after one hour when the user hit that button does anyone have any idea?
I tried this plugin flutter_local_notifications: ^8.2.0
But can some help me how to do the trigger after one hour
Thanks
Use this function to call notifications every hour
shownotifications() async {
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails('repeating channel id',
'repeating channel name', 'repeating description');
const NotificationDetails platformChannelSpecifics =
NotificationDetails(android: androidPlatformChannelSpecifics);
await FlutterLocalNotificationsPlugin().periodicallyShow(0, 'Test title',
'test body', RepeatInterval.hourly, platformChannelSpecifics,
androidAllowWhileIdle: true);
}
and follow this article step by step to to setup the package you are using
I am using "Firebase Cloud Messaging" for receiving notifications and "flutter_local_notifications" plugin to configure and display them on my device. So my current scenario is when my app is running (in foreground), I am receiving proper notification as expected (a pop-up plus it gets stored in system-tray) like this :
It also gets stored in the system tray as expected.
But when I keep the app in background and post a notification request ........ It just stores the notification in the tray but doesnt show a pop-up notification. Like this :
As seen in the image above .... it just stores the notification in the image tray but doesn't show pop-up notification like when the app is running in foreground.
I thought I was an issue in the "backgroundMessage" Callback but what I observed was whenever I posted a notification when the app is in background, instead of executing the "backgroundMessage" callback it always gave this exception :
W/FirebaseMessaging(22744): Missing Default Notification Channel metadata in AndroidManifest. Default value will be used.
Below is the code where I configured the FirebaseMessaging instance :
_firebaseMessaging.configure(
onMessage: notification,
onBackgroundMessage: notificationBack,
);
'notification' Callback :
Future<dynamic> notification(Map<String,dynamic> message) async {
AndroidNotificationDetails androidNotificationDetails =
AndroidNotificationDetails(
'Channel ID', 'Channel title', 'channel body',
priority: Priority.High,
importance: Importance.Max,
ticker: 'test');
IOSNotificationDetails iosNotificationDetails = IOSNotificationDetails();
NotificationDetails notificationDetails =
NotificationDetails(androidNotificationDetails, iosNotificationDetails);
await _flutterLocalNotificationsPlugin.show(
0, 'Notification', 'New Notification', notificationDetails);
}
'notificationBack' callback :
static Future<dynamic> notificationBack(Map<String,dynamic> message) async {
AndroidNotificationDetails androidNotificationDetails =
AndroidNotificationDetails(
'Channel ID', 'Channel title', 'channel body',
priority: Priority.High,
importance: Importance.Max,
visibility: NotificationVisibility.Public,
ticker: 'test');
IOSNotificationDetails iosNotificationDetails = IOSNotificationDetails();
NotificationDetails notificationDetails =
NotificationDetails(androidNotificationDetails, iosNotificationDetails);
await _flutterLocalNotificationsPluginBack.show(
0, 'Hello there', 'please subscribe my channel', notificationDetails);
}
AndroidManifest.xml :
Sorry for the screenshot instead of text format .... but I dont know why all these terms were highlighted in red saying "Cant resolve symbol ...." and "Unresolved package 'flutterlocalnotifications'" in case of reciever of flutterlocalnotification.
My main goal is to get the game pop-up notification and one in the system tray even when the app is in background. (Just how it displayed when it was in foreground).
I know the question is a bit long but I had to provide all my observation about the issue so please bare with it :)
Thankyou in advance for the help.