Flutter使用flutter_local_notifications插件定时通知到点不触发问题求助
Flutter使用flutter_local_notifications插件定时通知到点不触发问题求助
各位好,我现在遇到了flutter_local_notifications插件定时通知的棘手问题,想请大家帮忙排查下:
我用zonedSchedule创建的定时通知,明明已经出现在待处理通知列表里,但到了指定时间就是完全不触发。本地通知(非定时的)是能正常弹出的,只有定时的不行。目前我先用20秒后触发的测试用例来验证功能,结果到点也没反应,想先解决这个测试场景,再扩展到“指定日期9点触发”的实际需求。
依赖版本
我当前使用的依赖版本如下:
flutter_timezone: ^4.1.0 flutter_local_notifications: ^19.1.0 timezone: ^0.10.1 flutter_local_notifications_linux: ^6.0.0
之前尝试过降级flutter_local_notifications版本,但会抛出一堆编译错误,所以只能停留在这个版本。
Android权限配置
已经在AndroidManifest.xml中添加了以下必要权限:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/> <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM"/> <uses-permission android:name="android.permission.USE_EXACT_ALARM"/>
核心代码实现
定时通知调度方法
Future<void> scheduleNotification({ required int id, required String title, required String body, required String payload, required DateTime scheduledTime, }) async { print("Get Date Time: $scheduledTime"); await notificationsPlugin.zonedSchedule( id, title, body, tz.TZDateTime.from(scheduledTime, tz.local), await notificationDetails(), payload: payload, androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle, ); }
查看待处理通知的调试方法
Future<void> debugPrintPendingNotifications() async { final pendingNotifications = await notificationsPlugin.pendingNotificationRequests(); if (pendingNotifications.isEmpty) { print('No pending notifications'); return; } print('══════ Pending Notifications ══════'); for (final notification in pendingNotifications) { print(''' ID: ${notification.id} Title: ${notification.title} Body: ${notification.body} Scheduled for: ${notification.payload} '''); } print('═══════════════════════════════════'); }
调用定时通知的代码
await NotificationService().scheduleNotification( id: 0, title: "Test", body: "Remember to complete your $title by today!", payload: checklistData["ChecklistDate"], scheduledTime: now.add(Duration(seconds: 20)) ); print("Schdule Noti: ${now.add(Duration(seconds: 20))}"); print("Now: ${now}");
当前运行现象
从日志能看到,待处理通知确实已经被创建,但到了定时时间(比如测试用的20秒后)就是没有任何弹出:
I/flutter (13102): Schdule Noti: 2025-05-05 12:27:14.395999 I/flutter (13102): Now: 2025-05-05 12:26:54.395999 I/flutter (13102): ══════ Pending Notifications ══════ I/flutter (13102): ID: 0 I/flutter (13102): Title: Test I/flutter (13102): Body: Remember to complete your trip to taiwan by today! I/flutter (13102): Scheduled for: 2025-05-06 I/flutter (13102): ═══════════════════════════════════ I/flutter (13102): Reminder save successfully ... I/flutter (13102): 2025-05-05 12:27:19.126829 // 这里已经过了定时时间,通知依然没弹出
有没有朋友遇到过类似的情况?麻烦帮忙分析下可能哪里出了问题,非常感谢!
内容来源于stack exchange
相关产品推荐
相关产品推荐

