Flutter本地通知中onDidReceiveBackgroundNotificationResponse无法触发
Flutter本地通知onDidReceiveBackgroundNotificationResponse无法触发的解决方案
1. 统一通知渠道ID
你代码中初始化时创建的通知渠道ID是default_notification_channel_id,但调用show方法时使用的是pushnotificationapp作为渠道ID。Android后台通知点击事件的触发依赖通知所属渠道存在且配置一致,ID不匹配会直接导致回调失效。
修改createanddisplaynotification方法,将渠道ID与初始化时保持统一:
static void createanddisplaynotification(RemoteMessage message) async { try { final id = DateTime.now().millisecondsSinceEpoch ~/ 1000; // 使用和初始化阶段一致的渠道ID与名称 const NotificationDetails notificationDetails = NotificationDetails( android: AndroidNotificationDetails( "default_notification_channel_id", "Default Notification Channel", importance: Importance.max, priority: Priority.high, ), ); await _notificationsPlugin.show( id, message.notification!.title, message.notification!.body, notificationDetails, payload: message.data['_id'], ); } on Exception catch (e) { print(e); } }
2. 确保@pragma注解与代码混淆规则正确
虽然你已添加@pragma('vm:entry-point')注解,但需注意:
- 该注解必须直接标注在顶级函数或静态函数上,你的静态函数写法符合要求。
- 若开启代码混淆,需在
proguard-rules.pro中保留该方法,避免被混淆移除:
-keep class com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver -keep class com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin -keep class com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin$* -keep class 你的实际包名.LocalNotificationService { public static void onDidReceiveBackgroundNotificationResponse(...); }
3. 完善AndroidManifest配置
在AndroidManifest.xml中补充必要配置:
- Android 13及以上需添加通知权限:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
- 添加默认通知渠道的元数据配置(可选但推荐):
<meta-data android:name="com.dexterous.flutterlocalnotifications.default_notification_channel_id" android:value="default_notification_channel_id" />
4. 正确测试后台触发场景
onDidReceiveBackgroundNotificationResponse仅在**APP被完全杀死(从后台划掉)**的状态下,点击通知才会触发。若APP处于前台或后台运行状态,会触发onDidReceiveNotificationResponse(即你代码中打印'normal'的回调),这是正常逻辑,请勿混淆测试场景。
5. 确认依赖版本兼容性
onDidReceiveBackgroundNotificationResponse是替代旧APIonSelectNotification的新版本接口,若你的flutter_local_notifications版本过低,可能存在兼容性问题。确保pubspec.yaml中依赖为最新稳定版:
dependencies: flutter_local_notifications: ^16.1.0 # 替换为当前最新稳定版本
内容的提问来源于stack exchange,提问作者Aradhya Basak
相关产品推荐
相关产品推荐

