Я сталкиваюсь с проблемой с запланированными уведомлениями в моем приложении Flutter, используя пакет Flutter_local_notifications. Хотя немедленные уведомления функционируют правильно, запланированные уведомления не появляются, как ожидалось. В консоли отладки нет ошибок или предупреждений.import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_timezone/flutter_timezone.dart';
import 'package:timezone/timezone.dart' as tz;
import 'package:timezone/data/latest.dart' as tz;
class NotificationService {
final notificationsPlugin = FlutterLocalNotificationsPlugin();
bool _isInitialized = false;
bool get isInitialized => _isInitialized;
// Initialize
Future initNotification() async {
if (_isInitialized) return;
// Initialize timezone
tz.initializeTimeZones();
final String currentTimeZone = await FlutterTimezone.getLocalTimezone();
tz.setLocalLocation(tz.getLocation(currentTimeZone));
print("Device Timezone: $currentTimeZone");
const initSettingsAndroid =
AndroidInitializationSettings('@mipmap/ic_launcher');
const initSettings = InitializationSettings(android: initSettingsAndroid);
await notificationsPlugin.initialize(initSettings);
_isInitialized = true;
}
// Notification Detail
NotificationDetails notificationDetails() {
return NotificationDetails(
android: AndroidNotificationDetails(
'daily_channel_id',
'Daily Notifications',
channelDescription: 'Daily notifications for the app',
importance: Importance.max,
priority: Priority.high,
),
);
}
// Show Notifications
Future showNotifications({
int id = 0,
String? title,
String? body,
}) async {
return notificationsPlugin.show(
id,
title,
body,
notificationDetails(),
);
}
// Schedule a notification at a specified time (hour: 0-23, min: 0-59)
Future scheduleNotification({
int id = 1,
required String title,
required String body,
required int hour,
required int minute,
}) async {
// Get the current date/time in device's local timezone
final now = tz.TZDateTime.now(tz.local);
print("Current Time (TZ): $now");
// Create a date time for today at the specified hour and minute
var scheduledDate = tz.TZDateTime(
tz.local,
now.year,
now.month,
now.day,
hour,
minute,
);
print("Scheduled Time (Before Adjustment): $scheduledDate");
// Ensure scheduled time is in the future
if (scheduledDate.isBefore(now)) {
scheduledDate = scheduledDate.add(Duration(days: 1));
print("Scheduled Time Adjusted to Next Day: $scheduledDate");
}
// Schedule the notification
await notificationsPlugin.zonedSchedule(
id,
title,
body,
scheduledDate,
notificationDetails(),
androidScheduleMode: AndroidScheduleMode.inexactAllowWhileIdle,
matchDateTimeComponents: DateTimeComponents.dateAndTime,
);
print("Final Scheduled Time: $scheduledDate");
}
// Cancel all notifications
Future cancelAllNotifications() async {
await notificationsPlugin.cancelAll();
}
}
< /code>
Запустите немедленные уведомления с использованием метода
infedotifications, который работает как задумано. Зона правильно идентифицирована и устанавливается
с использованием пакетов Flutter_timezone и Timezone. Журналы указывают на то, что запланированное время
вычисляется правильно. Поскольку целевое устройство запускается Android 10,
не требуется дополнительных разрешений для планирования точных тревог.>
Подробнее здесь: https://stackoverflow.com/questions/795 ... ations-plu
Запланированные уведомления Flutter не работают с плагином Flutter_Local_Notifications ⇐ Android
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение