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.
Related
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
);
}
}
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);
}
I'm using flutterlocalnotifications package and FCM to send notifications to my users. Everything working perfectly. I can show notifications to my users when my app is in the background, foreground, or closed. I can reach payload value in foreground and background, but when the app is killed I can't reach payload anymore. I test in catlog but there isn't any print in the onSelectNotification.
How can reach this payload?
This is my notification handler class
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
AndroidNotificationChannel channel = AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
'This channel is used for important notifications.', // description
importance: Importance.high,
);
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// await Firebase.initializeApp();
//Bildirim geldiği anda datayı elde ettiğimiz alan
final dynamic data = message.data;
print('Data in background : ${data.toString()}');
NotificationHandler.showNotification(data);
}
class NotificationHandler {
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
static final NotificationHandler _singleton = NotificationHandler._internal();
factory NotificationHandler() {
return _singleton;
}
NotificationHandler._internal();
BuildContext myContext;
initializeFCMNotifications(BuildContext context) async {
await _firebaseMessaging.setForegroundNotificationPresentationOptions(
alert: true, badge: true, sound: true);
var initializationSettingsAndroid =
AndroidInitializationSettings('app_icon');
var initializationSettingsIOS = IOSInitializationSettings(
onDidReceiveLocalNotification: onDidReceiveLocalNotification);
var initializationSettings = InitializationSettings(
android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
await flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: onSelectNotification);
await _firebaseMessaging.subscribeToTopic("all");
await FirebaseMessaging.instance
.getInitialMessage()
.then((RemoteMessage message) {
if (message != null) {
print('initialmessage tetiklendi : ' + message.data.toString());
}
});
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
var notification = message.notification;
var android = message.notification?.android;
print('ONMESSAGE ÇALIŞTI');
print('onmessage tetiklendi data : ' +
message.data['message'] +
' title ' +
message.data['title']);
showNotification(message.data);
});
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
print('Onmessageopened : ' + message.data.toString());
});
}
static void showNotification(Map<String, dynamic> data) async {
const androidPlatformChannelSpecifics = AndroidNotificationDetails(
'1234', 'Yeni Mesaj', 'your channel description',
importance: Importance.max, priority: Priority.high, ticker: 'ticker');
const IOSPlatformChannelSpecifics = IOSNotificationDetails();
const platformChannelSpecifics = NotificationDetails(
android: androidPlatformChannelSpecifics,
iOS: IOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
0, data['title'], data['message'], platformChannelSpecifics,
payload: 'The value when notification tapped');
}
Future onSelectNotification(String payload) async {
if (payload != null) {
debugPrint('notification payload : $payload');
}
}
Future onDidReceiveLocalNotification(
int id, String title, String body, String payload) {}
}
and these are the versions of the packages I use
firebase_messaging: ^9.1.1
flutter_local_notifications: ^5.0.0+1
I am trying to set a scheduled alarm notification from the user selected date and time which i used showDatePicker for code below
DateTime _selectedDateAndTime;
Future _selectDayAndTimeL(BuildContext context) async {
DateTime _selectedDay = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2021),
lastDate: DateTime(2030),
builder: (BuildContext context, Widget child) => child);
TimeOfDay _selectedTime = await showTimePicker(
context: context,
initialTime: TimeOfDay.now(),
);
if (_selectedDay != null && _selectedTime != null) {
//a little check
}
setState(() {
_selectedDateAndTime = DateTime(
_selectedDay.year,
_selectedDay.month,
_selectedDay.day,
_selectedTime.hour,
_selectedTime.minute,
);
// _selectedDate = _selectedDay;
});
// print('...');
}
which after the date and time has been selected the value is formatted like in the picture bellow
Now i want to be able to set the Scheduled Notification using the value from the selection but not sure how to do it... i have installed Flutter_Local_Notification and have imported it to my main.dart, have set the permission in the manifest file and have also tried to initial the plugin like down bellow
FlutterLocalNotificationsPlugin fltrNotification;
String _selectedParam;
int val;
#override
void initState() {
super.initState();
var androidInitilize = new AndroidInitializationSettings('app_icon');
var iOSinitilize = new IOSInitializationSettings();
var initilizationsSettings =
new InitializationSettings(androidInitilize, iOSinitilize);
fltrNotification = new FlutterLocalNotificationsPlugin();
fltrNotification.initialize(initilizationsSettings,
onSelectNotification: notificationSelected);
}
and i have also added the app_icon.png to my drawable folder
i have tried to follow some tutorial on how to do it but most of them only show how to set the netification using seconds but for my own project i want to set the schedule for a particular day, hour and minute
please how can i achive that?
You can use this my helper class
class NotificationPlugin {
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
var initializationSettings;
NotificationPlugin._() {
init();
}
init() async {
flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
if (Platform.isIOS) {
_requestIOSPermission();
}
initializePlatformSpecifics();
}
initializePlatformSpecifics() {
var initializationSettingsAndroid = AndroidInitializationSettings(
'mipmap/ic_launcher'); // <- default icon name is #mipmap/ic_launcher
var initializationSettingsIOS =
IOSInitializationSettings(onDidReceiveLocalNotification: (int a, String b, String c, d) {});
var initializationSettings =
InitializationSettings(initializationSettingsAndroid, initializationSettingsIOS);
flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: (String s) {});
initializationSettings =
InitializationSettings(initializationSettingsAndroid, initializationSettingsIOS);
}
_requestIOSPermission() {
flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>()
.requestPermissions(alert: false, badge: true, sound: true);
}
setOnNotificationClick(Function onNotificationClick) async {
await flutterLocalNotificationsPlugin.initialize(
initializationSettings,
onSelectNotification: (payload) async {
onNotificationClick(payload);
},
);
}
Future<void> showNotification(
{#required int id, #required String title, #required String body}) async {
var androidChannelSpecifics = AndroidNotificationDetails(
'CHANNEL_ID',
'CHANNEL_NAME',
'CHANNEL_DESCRIPTION',
importance: Importance.High,
priority: Priority.High,
);
var iosChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(
androidChannelSpecifics,
iosChannelSpecifics,
);
await flutterLocalNotificationsPlugin.show(id, title, body, platformChannelSpecifics,
payload: id.toString());
}
Future<void> showScheduledNotification(
{#required int id,
#required String title,
#required String body,
#required String date}) async {
var scheduledNotificationDateTime = DateTime.parse(date);
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'your other channel id', 'your other channel name', 'your other channel description');
var iOSPlatformChannelSpecifics = IOSNotificationDetails();
NotificationDetails platformChannelSpecifics =
NotificationDetails(androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.schedule(
id, '$title', ' $body', scheduledNotificationDateTime, platformChannelSpecifics,
androidAllowWhileIdle: true);
}
Future<void> removeNotifications() async {
await flutterLocalNotificationsPlugin.cancelAll();
}
}
NotificationPlugin notificationPlugin = NotificationPlugin._();
and then you can call
await notificationPlugin.showScheduledNotification(
id: 123,
title:"fancy title",
body: "data",
date: yourDate,
);
/////////////////////////////////
if you will not use the helper class
this is simply what you need
var scheduledNotificationDateTime = DateTime.parse(date); // replace whith your date
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'your other channel id', 'your other channel name', 'your other channel description');
var iOSPlatformChannelSpecifics = IOSNotificationDetails();
NotificationDetails platformChannelSpecifics =
NotificationDetails(androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.schedule(
id, '$title', ' $body', scheduledNotificationDateTime, platformChannelSpecifics,
androidAllowWhileIdle: true);
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 {}