如何在Flutter中使用awesome包实现指定时间触发通知的功能?
实现awesome包定时触发通知的调整方案
核心调整逻辑
你只需要在createNotification方法中新增schedule参数配置触发时间即可,具体调整步骤如下:
- 首先把
AwesomeNotifications().initialize初始化逻辑移到App启动入口(比如main函数中runApp之前执行),不要每次调用通知方法都重复初始化 - 提前申请相关权限:Android 12及以上版本需要申请
SCHEDULE_EXACT_ALARM权限,iOS需要允许通知后台触发权限,否则定时通知可能无法正常触发 - 调用
NotificationCalendar类配置你需要的触发时间,传入schedule参数即可
调整后的完整示例代码
// 初始化逻辑移到App启动处,此处可注释避免重复执行 // AwesomeNotifications().initialize( // '', // [ // NotificationChannel( // channelKey: 'basic_channel', // channelName: 'Basic notifications', // channelDescription: 'Notification channel for basic tests', // defaultColor: Color(0xFF9D50DD), // ledColor: Colors.white, // playSound: true, // importance: NotificationImportance.Max, // defaultRingtoneType: DefaultRingtoneType.Notification, // ) // ] // ); Future<void> scheduleNotificationAtSpecificTime(int id, DateTime targetTime) async { await AwesomeNotifications().createNotification( content: NotificationContent( id: id, channelKey: 'basic_channel', title: 'Anonymous says:', body: 'Hi there!', payload: {'uuid': 'user-profile-uuid'}, displayOnBackground: true, displayOnForeground: true, ), // 新增schedule配置触发时间 schedule: NotificationCalendar( year: targetTime.year, month: targetTime.month, day: targetTime.day, hour: targetTime.hour, minute: targetTime.minute, second: 0, millisecond: 0, // 低功耗模式下也触发通知 allowWhileIdle: true, // 如果需要重复触发,添加repeats: true即可 // repeats: false, ) ); }
常见定时场景配置说明
- 单次指定时间触发:如上示例传入完整的目标时间即可
- 每天固定时间重复触发:把
year/month/day参数留空,仅指定hour和minute,同时设置repeats: true - 每周固定时间重复触发:仅指定
weekday、hour、minute,同时设置repeats: true - 取消指定定时通知:调用
AwesomeNotifications().cancel(通知id)即可取消对应定时任务
内容的提问来源于stack exchange,提问作者Abdelrahman Bahig
相关产品推荐
相关产品推荐

