You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter插件notification_listener_service仅Debug可用,Release模式失效求助

Flutter notification_listener_service在Release/Debug构建版本中无法监听通知的解决方案

问题分析

Debug模式下通知监听正常,但通过flutter build apk --release或flutter build apk --debug打包后的版本无法接收通知,核心原因通常是代码混淆移除了关键服务类、权限未正确生效或系统后台限制拦截了服务运行。

解决步骤

1. 添加ProGuard/R8混淆规则

Release构建时R8会自动混淆未标记的类,插件的原生服务类可能被误删。在android/app/proguard-rules.pro文件中添加以下规则:

-keep class notification.listener.service.NotificationListener { *; }
-keep class notification.listener.service.NotificationEvent { *; }
-keep class notification.listener.service.NotificationListenerService { *; }

2. 确认AndroidManifest配置正确性

检查你的服务配置,确保类名、权限和IntentFilter完全匹配插件要求:

<service
    android:label="notifications"
    android:name="notification.listener.service.NotificationListener"
    android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"
    android:exported="true">
    <intent-filter>
        <action android:name="android.service.notification.NotificationListenerService" />
    </intent-filter>
</service>

注意:若插件版本更新,需对照插件文档确认类名是否变化。

3. 强制引导用户授予并验证权限

打包后的版本可能存在权限状态缓存,需主动引导用户到系统设置页确认权限:
修改Flutter代码中的checkPermission方法:

Future<void> checkPermission() async {
  bool status = await NotificationListenerService.isPermissionGranted();
  if (!status) {
    // 跳转到通知监听权限设置页面
    await NotificationListenerService.openPermissionSettings();
    // 重新检查权限状态
    status = await NotificationListenerService.isPermissionGranted();
  }
  if (status) listen();
  havePermission = status;
  setState(() {});
}

安装APK后,手动进入设置 > 应用 > 你的应用 > 通知访问,确认权限已开启。

4. 防止Stream订阅被GC回收

在listen方法中持有Stream订阅对象,避免被垃圾回收器回收:

// 新增成员变量保存订阅
StreamSubscription? _notificationSubscription;

Future<void> listen() async {
  try {
    print("LISTEN");
    // 先取消旧订阅,避免重复监听
    _notificationSubscription?.cancel();
    _notificationSubscription = NotificationListenerService.notificationsStream.listen((event) {
      print("NEW EVENT: ");
      print(event);
      events.add(event);
      setState(() {});
    });
  } catch (e) {
    errorMessage = e.toString();
    setState(() {});
  }
}

// 在页面销毁时取消订阅
@override
void dispose() {
  _notificationSubscription?.cancel();
  super.dispose();
}

5. 解除系统后台限制

部分国产Android设备(小米、华为等)对后台服务有严格限制:

  • 进入应用设置,开启后台运行权限或设置为无限制后台
  • 关闭应用的电池优化选项

验证方法

  1. 执行flutter build apk --release构建安装包并安装
  2. 确认通知访问权限已开启
  3. 发送测试通知,通过adb logcat -s Flutter命令查看Flutter控制台日志,验证是否收到通知事件

内容的提问来源于stack exchange,提问作者Stel K9

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 03:12:04