Display Notification In Flutter When App is Closed - flutter

I Have try to display notification in flutter app I already used FlutterLocalNotificationPlugin
When app is open the notification is display but
When flutter app is Closed but it is not working or notification is not display ,I`am new in flutter please help me
//This is Function Initialization
FlutterLocalNotificationsPlugin localNotificationsPlugin;
Future showNotification() async {
var androidDetails = new AndroidNotificationDetails(
"channelId",
"channelName",
"channelDescription",
importance: Importance.max,
priority: Priority.high,
playSound: true,
largeIcon: DrawableResourceAndroidBitmap('tele_marketing'),
);
var iosDetails = new IOSNotificationDetails(
//sound: 'bells.mp3',
presentAlert: true,
presentBadge: true,
presentSound: true);
var generalNotification =
new NotificationDetails(android: androidDetails, iOS: iosDetails);
await localNotificationsPlugin.show(
0, "Total Leads", totalLeads.toString(), generalNotification);
}
// This is function Call
#override
void initState() {
super.initState();
//Build Notification in IOS and Android
var androidNotification =
new AndroidInitializationSettings('tele_marketing');
var iosNotification = new IOSInitializationSettings(
requestAlertPermission: true,
requestBadgePermission: true,
requestSoundPermission: true,
);
var notification = new InitializationSettings(
android: androidNotification, iOS: iosNotification);
localNotificationsPlugin = new FlutterLocalNotificationsPlugin();
localNotificationsPlugin.initialize(notification);
}
//When API is call display the function app is open or closed
if (snapshot.hasData) {
if (totalLeads > totLeads) {
playSound();
showNotification();
totLeads = totalLeads;
} else {}

Related

Flutter_local_notifications notificationResponse.payload is always empty string,

I'm trying to setup my mobile app, so that when a user gets a FCM message, when they click on it, I can use data within the message to route them to appropriate screen.
My FCM message looks like this:
const fcmMessage = {
notification: {
title: title,
body: message
},
data:{
type:'Chat',
Name: 'Mike',
body:'test'
},
android: {
notification: {
title:title,
body: message,
channel_id:'high_importance_channel'
}
},
token: msgToken,
};
then within my main() method, I am initializing the Flutter_Local_notifications as per the code snippet below.
The issue is when I click on the notification, the payload is always an empty string?
These are the code lines that perform this. Why is the NotificationResponse.payload empty string?
ultimately, I need access the "data" object in the FCM message.
void onDidReceiveNotificationResponse(NotificationResponse notificationResponse) async {
print(notificationResponse.payload);
}
Here is the full main() method.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
// Set the background messaging handler early on, as a named top-level function
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
if (!kIsWeb) {
channel = const AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title/
importance: Importance.high,
);
}
flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
var initializationSettingsAndroid =
AndroidInitializationSettings('#mipmap/ic_launcher');
var initializationSettingsIOs = DarwinInitializationSettings();
var initSettings = InitializationSettings(
android: initializationSettingsAndroid, iOS: initializationSettingsIOs);
void onDidReceiveNotificationResponse(NotificationResponse notificationResponse) async {
print(notificationResponse.payload);
}
await flutterLocalNotificationsPlugin.initialize(initSettings,onDidReceiveNotificationResponse: onDidReceiveNotificationResponse,);
/// 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);
await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print('Got a message whilst in the foreground!');
print('Message data: ${message.data}');
if (message.notification != null) {
RemoteNotification? notification = message.notification;
AndroidNotification? android = message.notification?.android;
FlutterLocalNotificationsPlugin s = FlutterLocalNotificationsPlugin();
s.show(
notification.hashCode,
notification?.title,
notification?.body,
NotificationDetails(
android: AndroidNotificationDetails(channel.id, channel.name,
icon: 'launch_background',
channelDescription: channel.description,
importance: Importance.max,
priority: Priority.high,
ongoing: true,
styleInformation: BigTextStyleInformation('')),
),
);
}
});
runApp(MyApp());
}
UPDATE, found what I needed. In the LocalNotification show method, we can add the payload attribute and set it to whatever part of the message.
For my use case, I encode the message.data , and then in the didReceive method, I can decode back to JSON object and use as needed.
s.show(
payload: jsonEncode(message.data),
notification.hashCode,
notification?.title,
notification?.body,
NotificationDetails(
android: AndroidNotificationDetails(channel.id, channel.name,
icon: 'launch_background',
channelDescription: channel.description,
importance: Importance.max,
priority: Priority.high,
ongoing: true,
styleInformation: BigTextStyleInformation('')),
),
);

how to get notification if app is terminated or closed

I want to show notification based on a condition. I tried with flutter local notification package but I was only getting the foreground and background notification. if I close the app i was not having any notification from app.
example:
app is fetching the data from real-time-database firebase and data base is getting the frequency value from hardware, if frequency is greater than 50 then show notification.
if there is any another way to implement, you can also suggest me that
part of the code:
NotificationService notificationsServices = NotificationService();
void initState(){
super.initState();
notificationsServices.intializeNotification();
}
if(_displayTemp>135 || _displayVib>135)
{
notificationsServices.sendN("Alert", _displayMsg);
}
class NotificationService {
final FlutterLocalNotificationsPlugin flutterNotificationsPlugin = FlutterLocalNotificationsPlugin();
final AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings('shield');
void intializeNotification() async {
InitializationSettings initializationSettings= InitializationSettings(
android: initializationSettingsAndroid
);
await flutterNotificationsPlugin.initialize(initializationSettings);
}
void sendN(String title,String body) async {
AndroidNotificationDetails androidNotificationDetails = AndroidNotificationDetails(
'channelId 2',
'channelName',
importance: Importance.max,
priority: Priority.high,
playSound: true,
//ongoing: true
);
NotificationDetails notificationDetails = NotificationDetails(
android: androidNotificationDetails,
);
await flutterNotificationsPlugin.show(
0,
title,
body,
notificationDetails
);
}
}

add multiple scheduled notifications using flutter

I've been working on an adhan app using flutter and I'm working on the scheduled notification using flutter_local_notifications package. Using the .zonedSchedule I can only display notification once.
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
AndroidInitializationSettings androidInitializationSettings = AndroidInitializationSettings("icon");
IOSInitializationSettings iosInitializationSettings = IOSInitializationSettings();
final InitializationSettings initializationSettings = InitializationSettings(
android: androidInitializationSettings,
iOS: iosInitializationSettings);
await flutterLocalNotificationsPlugin.initialize(initializationSettings);
and for the Notification detail
var android = AndroidNotificationDetails(
"$id", channel,
importance: Importance.max,
sound: RawResourceAndroidNotificationSound('adhan'),
playSound: true,
);
var ios = IOSNotificationDetails();
var platform = NotificationDetails(android: android, iOS: ios);
final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
and used it as
_flutterLocalNotificationsPlugin.zonedSchedule(
1,
"title",
"dhuhr",
tz.TZDateTime.from(prayerTimes.dhuhr!, location),
platform,
uiLocalNotificationDateInterpretation: UILocalNotificationDateInterpretation
.absoluteTime,
androidAllowWhileIdle: true,
matchDateTimeComponents: DateTimeComponents.time
);
_flutterLocalNotificationsPlugin.zonedSchedule(
2,
"title",
"Asr",
tz.TZDateTime.from(prayerTimes.asr!, location),
platform,
uiLocalNotificationDateInterpretation: UILocalNotificationDateInterpretation
.absoluteTime,
androidAllowWhileIdle: true,
matchDateTimeComponents: DateTimeComponents.time
);
the problem I'm facing is that if the time matches with the current prayer time it works fine. but when it's time for the next schedule it doesn't display anything.
So how can I display notification multiple times in a day?

Sound and pop-up notifications do not work in flutter

I am using local_notifications plugin in my android flutter app. I do everything according to the documentation and the notifications work but without sound and pop-up windows. Importance and priority set to max. Maybe the reason is in some settings of my phone or its OS (MIUI Global 11.0.3, Android 9 PKQ1)?
Notification code:
FlutterLocalNotificationsPlugin notificationsPlugin =
FlutterLocalNotificationsPlugin();
Future<void> initNotificationPlugin() async {
const AndroidInitializationSettings androidSettings =
AndroidInitializationSettings('ic_launcher');
final IOSInitializationSettings iosSettings =
IOSInitializationSettings();
final initSettings =
InitializationSettings(android: androidSettings, iOS:
iosSettings);
await notificationsPlugin.initialize(initSettings);
}
void showNotification(String title, String body,
DateTime dateTime, int id) async {
var androidDetails = AndroidNotificationDetails(
'notificationChannel', 'channel', 'description',
importance: Importance.max,
priority: Priority.max,
playSound: true,
showWhen: false,
enableVibration: true);
var iosDetails = IOSNotificationDetails();
var details = NotificationDetails(android: androidDetails, iOS:
iosDetails);
await notificationsPlugin.zonedSchedule(
id,
title,
body,
timezone.TZDateTime.from(
dateTime, timezone.getLocation('Europe/Moscow')),
details,
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime);
}

run dart code in the background even when my app is closed

In flutter i'm using adhara_socket_io to open a socket and receive data from my server to push a notification using flutter_local_notifications and it works when the app is running, now i need to make this run in the background so when my app is not running it still receives data from my server and pushes notifications, is there anyway for doing that in flutter ?
void initSocket() async {
final deviceInfo = await Constants.getDeviceDetails();
final String deviceId = deviceInfo[2];
Uuid uuid = Uuid();
print(deviceInfo);
final id = uuid.v5(Uuid.NAMESPACE_URL, deviceId);
print('id ' + id);
SocketIOManager manager = SocketIOManager();
SocketIO socket = await manager.createInstance(
SocketOptions(URI,
enableLogging: false,
transports: [Transports.WEB_SOCKET /*, Transports.POLLING*/]),
);
socket.onConnect((data) {
print("connected...");
print(data);
socket.emit('settings', [
{'device_id': id}
]);
});
socket.onConnectError((_) => print('connect error'));
socket.onConnectTimeout((_) => print('timeout'));
socket.onError((_) => print('error'));
socket.onDisconnect((_) => print('disconnect'));
socket.on('notif', (data) {
print('notif');
_showNotificationWithDefaultSound(data['heading'],data['content']);
});
socket.connect();
}
initNotifications() {
var initializationSettingsAndroid = AndroidInitializationSettings('#mipmap/ic_launcher');
var initializationSettingsIOS = IOSInitializationSettings();
var initializationSettings = InitializationSettings(initializationSettingsAndroid,initializationSettingsIOS);
flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
flutterLocalNotificationsPlugin.initialize(initializationSettings,onSelectNotification: onSelectNotification);
}
Future onSelectNotification(String payload)async{
print('payload');
}
Future _showNotificationWithDefaultSound(heading,content) async {
var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
'your channel id', 'your channel name', 'your channel description',
importance: Importance.Max, priority: Priority.High);
var iOSPlatformChannelSpecifics = new IOSNotificationDetails();
var platformChannelSpecifics = new NotificationDetails(
androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
0,
heading,
content,
platformChannelSpecifics,
payload: 'Default_Sound',
);
}
https://medium.com/vrt-digital-studio/flutter-workmanager-81e0cfbd6f6e
hope this will help or u can use fcm https://fireship.io/lessons/flutter-push-notifications-fcm-guide/
however i am begginer .i dont know about this too much ..sorry if this doesnt help you.