I am using adhan dart package to get prayer times and scheduled notifications using flutterlocalnotification.zonedscedule().The problem is if user clicks on schedule notification button then only that day he will get notifications for prayer times. But I want when user installs app and clicks on schedule notification button then he will gets notification daily automatically at prayer times which are getting from adhan dart package.
我正在使用adhan dart包来获取祈祷时间和预定的通知,使用的是fltterLocalNotify ation.zonedscedule()。问题是,如果用户点击预定通知按钮,那么只有那天他才会收到祈祷时间的通知。但我希望当用户安装应用程序并点击时间表通知按钮,然后他将得到每天的祈祷时间自动通知,这是从adhan飞镖包。
Here is my notification service class
以下是我的通知服务类
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:intl/intl.dart';
import 'package:islamic/getprayertime.dart';
import 'package:timezone/timezone.dart' as tz;
class NotificationService {
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
static final NotificationService _notificationService =
NotificationService._internal();
factory NotificationService() {
return _notificationService;
}
NotificationService._internal();
Future<void> initializenotification() async {
//Android Platform configuration required to send notifications
AndroidInitializationSettings androidInitializationSettings =
const AndroidInitializationSettings('logo');
InitializationSettings initializationSettings =
InitializationSettings(android: androidInitializationSettings);
await flutterLocalNotificationsPlugin.initialize(initializationSettings);
}
backgroundtask() {
Prayers.getPrayertimes().then((value) {
final currenttime = DateTime.now();
if (value.fajr!.toLocal().isAfter(currenttime)) {
schedulePrayerTimeNotification(value.fajr!.toLocal(), 'Fajr');
}
if (value.dhuhr!.toLocal().isAfter(currenttime)) {
schedulePrayerTimeNotification(value.dhuhr!.toLocal(), 'Dhuhr');
}
if (value.asr!.toLocal().isAfter(currenttime)) {
schedulePrayerTimeNotification(value.asr!.toLocal(), 'Asr');
}
if (value.maghrib!.toLocal().isAfter(currenttime)) {
schedulePrayerTimeNotification(value.maghrib!.toLocal(), 'Maghrib');
}
if (value.isha!.toLocal().isAfter(currenttime)) {
schedulePrayerTimeNotification(value.isha!.toLocal(), 'Isha');
}
});
}
Future<void> schedulePrayerTimeNotification(
DateTime prayerTime, String prayerName) async {
const AndroidNotificationDetails androidNotificationDetails =
AndroidNotificationDetails(
'main_channel',
'Main Channel',
channelDescription: "ashwin",
importance: Importance.max,
priority: Priority.max,
);
const NotificationDetails notificationDetails =
NotificationDetails(android: androidNotificationDetails);
final formattedTime = DateFormat('h:mm a').format(prayerTime);
await flutterLocalNotificationsPlugin.zonedSchedule(
prayerName.hashCode,
'Prayer Time',
'It\'s time for $prayerName prayer at $formattedTime.',
tz.TZDateTime.from(prayerTime, tz.local),
notificationDetails,
androidAllowWhileIdle: true, //to show notification when app is closed
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
);
}
}
And here is my home class
这是我的班级
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:islamic/background_task.dart';
import 'package:islamic/drawer.dart';
class Homepage extends StatefulWidget {
const Homepage({super.key});
@override
State<Homepage> createState() => _HomepageState();
}
class _HomepageState extends State<Homepage> {
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
backgroundColor: Colors.indigo,
),
body: Center(
child: SizedBox(
height: 60,
width: 300,
child: ElevatedButton(
onPressed: () {
Get.snackbar(
'Prayer reminder',
'Your prayer reminder has been created',
snackPosition: SnackPosition.TOP,
icon: Icon(Icons.mosque),
);
NotificationService().backgroundtask();
},
style: ElevatedButton.styleFrom(backgroundColor: Colors.indigo),
child: Text(
'Set Prayer reminder',
style: TextStyle(color: Colors.white),
),
),
),
),
),
);
}
}
How can I do that Anyone can help me thanks in advance
我该怎么做呢?有没有人能帮我提前谢谢?
更多回答
You need to use the android_alarm_manager_plus
package in order to schedule daily prayer time notifications.
您需要使用Android_ALARM_MANAGER_PLUS包来计划日常祈祷时间通知。
- Add the android_alarm_manager_plus package to your pubspec.yaml file
- You can schedule the alarm when the user clicks the "schedule notification" button. The
homepage.dart
must be
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:islamic/notification_service.dart';
class Homepage extends StatefulWidget {
const Homepage({super.key});
@override
State<Homepage> createState() => _HomepageState();
}
class _HomepageState extends State<Homepage> {
List<String> scheduledPrayers = [];
@override
void initState() {
super.initState();
loadScheduledPrayers();
}
Future<void> loadScheduledPrayers() async {
final prayers = await NotificationService().getScheduledPrayerTimes();
setState(() {
scheduledPrayers = prayers;
});
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
backgroundColor: Colors.indigo,
),
body: Column(
children: [
ElevatedButton(
onPressed: () {
Get.snackbar(
'Prayer reminder',
'Your prayer reminder has been created',
snackPosition: SnackPosition.TOP,
icon: Icon(Icons.mosque),
);
// Schedule the daily recurring alarm
AndroidAlarmManager.periodic(
const Duration(hours: 24), // repeat daily
0, // alarm ID
NotificationService().backgroundTask, // callback method
exact: true,
wakeup: true,
);
},
style: ElevatedButton.styleFrom(backgroundColor: Colors.indigo),
child: Text(
'Set Prayer reminder',
style: TextStyle(color: Colors.white),
),
),
Expanded(
child: ListView.builder(
itemCount: scheduledPrayers.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(scheduledPrayers[index]),
);
},
),
),
],
),
),
);
}
}
- The
notification_service.dart
must be:
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:intl/intl.dart';
import 'package:islamic/getprayertime.dart';
import 'package:android_alarm_manager_plus/android_alarm_manager_plus.dart'; // Import the alarm manager package
import 'package:timezone/timezone.dart' as tz;
import 'package:shared_preferences/shared_preferences.dart';
class NotificationService {
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
static final NotificationService _notificationService =
NotificationService._internal();
factory NotificationService() {
return _notificationService;
}
NotificationService._internal();
Future<void> initializenotification() async {
// Android Platform configuration required to send notifications
AndroidInitializationSettings androidInitializationSettings =
const AndroidInitializationSettings('logo');
InitializationSettings initializationSettings =
InitializationSettings(android: androidInitializationSettings);
await flutterLocalNotificationsPlugin.initialize(initializationSettings);
}
Future<void> saveScheduledPrayerTime(
DateTime prayerTime, String prayerName) async {
final prefs = await SharedPreferences.getInstance();
final notifications = prefs.getStringList('scheduled_prayers') ?? [];
final formattedTime = DateFormat('h:mm a').format(prayerTime);
final notificationData = '$prayerName - $formattedTime';
notifications.add(notificationData);
await prefs.setStringList('scheduled_prayers', notifications);
}
Future<List<String>> getScheduledPrayerTimes() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getStringList('scheduled_prayers') ?? [];
}
backgroundTask() async {
Prayers.getPrayertimes().then((value) {
final currenttime = DateTime.now();
if (value.fajr!.toLocal().isAfter(currenttime)) {
schedulePrayerTimeNotification(value.fajr!.toLocal(), 'Fajr');
saveScheduledPrayerTime(value.fajr!.toLocal(), 'Fajr');
}
if (value.dhuhr!.toLocal().isAfter(currenttime)) {
schedulePrayerTimeNotification(value.dhuhr!.toLocal(), 'Dhuhr');
saveScheduledPrayerTime(value.dhuhr!.toLocal(), 'Dhuhr');
}
if (value.asr!.toLocal().isAfter(currenttime)) {
schedulePrayerTimeNotification(value.asr!.toLocal(), 'Asr');
saveScheduledPrayerTime(value.asr!.toLocal(), 'Asr');
}
if (value.maghrib!.toLocal().isAfter(currenttime)) {
schedulePrayerTimeNotification(value.maghrib!.toLocal(), 'Maghrib');
saveScheduledPrayerTime(value.maghrib!.toLocal(), 'Maghrib');
}
if (value.isha!.toLocal().isAfter(currenttime)) {
schedulePrayerTimeNotification(value.isha!.toLocal(), 'Isha');
saveScheduledPrayerTime(value.isha!.toLocal(), 'Isha');
}
});
}
Future<void> schedulePrayerTimeNotification(
DateTime prayerTime, String prayerName) async {
const AndroidNotificationDetails androidNotificationDetails =
AndroidNotificationDetails(
'main_channel',
'Main Channel',
channelDescription: "ashwin",
importance: Importance.max,
priority: Priority.max,
);
const NotificationDetails notificationDetails =
NotificationDetails(android: androidNotificationDetails);
final formattedTime = DateFormat('h:mm a').format(prayerTime);
await flutterLocalNotificationsPlugin.zonedSchedule(
prayerName.hashCode,
'Prayer Time',
'It\'s time for $prayerName prayer at $formattedTime.',
tz.TZDateTime.from(prayerTime, tz.local),
notificationDetails,
androidAllowWhileIdle: true, // to show notification when the app is closed
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
);
}
}
In order to update the list view when the user clicks the schedule notification button, you can call the loadScheduledPrayers()
method again after scheduling the alarm.
为了在用户单击Schedule通知按钮时更新列表视图,您可以在调度警报后再次调用loadScheduledPrayers()方法。
import 'package:flutter/material.dart';
import 'package:android_alarm_manager_plus/android_alarm_manager_plus.dart';
import 'package:islamic/notification_service.dart';
class Homepage extends StatefulWidget {
const Homepage({super.key});
@override
State<Homepage> createState() => _HomepageState();
}
class _HomepageState extends State<Homepage> {
List<String> scheduledPrayers = [];
@override
void initState() {
super.initState();
loadScheduledPrayers();
}
Future<void> loadScheduledPrayers() async {
final prayers = await NotificationService().getScheduledPrayerTimes();
setState(() {
scheduledPrayers = prayers;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home'),
),
body: Column(
children: [
ElevatedButton(
onPressed: () async {
// Schedule alarm
await AndroidAlarmManager.periodic(
Duration(hours: 24),
0,
NotificationService().backgroundTask,
exact: true,
wakeup: true,
);
// Reload scheduled prayers
await loadScheduledPrayers();
// Call setState
setState(() {});
},
child: Text('Schedule Notifications'),
),
// List scheduled prayers
Expanded(
child: ListView.builder(
itemCount: scheduledPrayers.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(scheduledPrayers[index]),
);
},
),
),
],
),
);
}
}
Kindly, let me know if it works.
如果管用,请让我知道。
更多回答
You don't need to call initializenotification() within your app's initialization. kindly clear that point
您不需要在应用程序的初始化过程中调用Initializenotify()。请澄清这一点
void main() { WidgetsFlutterBinding.ensureInitialized(); NotificationService().initializenotification(); tz.initializeTimeZones(); runApp(MyApp()); } Are you talking about Notificationservice().initializenotification() in main?
void main(){ WidgetsFlutterBinding.ensureInitialized(); NotificationService(). initializenofication(); tz.initializeTimeZones(); runApp(MyApp()); }你是在说main中的Notificationservice(). initializenofication()吗?
After having a look at your main()
, you need to call Notificationservice().initializenotification()
the way you already doing. Kindly, add the full dart code in question as well. I have also updated the answer.
在查看了Main()之后,您需要以已有的方式调用Notificationservice().initializenotification()。亲切地,添加完整的飞镖代码以及问题。我也更新了答案。
@AbdullahShahzad does it work for you?
@AbdullahShahzad对你有效吗?
I am checking it i will inform you soon
我正在检查,我会很快通知你的
我是一名优秀的程序员,十分优秀!