Flutter的flutter_local_notifications安卓Release版无通知显示,求更优方案
解决flutter_local_notifications在Android Release包中无法显示通知的规范方案
在使用flutter_local_notifications ^16.3.1+1开发Flutter应用时,Release包在安卓设备上无法显示本地通知,直接关闭shrinkResources虽然能解决问题,但会放弃资源压缩优化,以下是更健壮规范的修复方案:
方案一:通过ProGuard规则保留通知相关代码与资源
Android的代码混淆(minifyEnabled)和资源压缩(shrinkResources)会移除未被直接引用的类和资源,而通知相关组件可能被误判为无用内容。在android/app/proguard-rules.pro中添加规则,强制保留必要内容:
# 保留flutter_local_notifications核心类 -keep class com.dexterous.** { *; } # 若使用FCM相关通知扩展,保留对应类 -keep class com.google.firebase.messaging.** { *; } # 保留自定义通知处理类(替换为你的项目类路径) -keep class com.yourpackage.yourproject.** { *; } # 保留通知图标资源(替换为你的图标文件名前缀) -keepresources drawable/ic_notif_*,mipmap/ic_notif_*
添加后即可开启shrinkResources true和minifyEnabled true,兼顾包体积优化与通知功能正常。
方案二:完善AndroidManifest.xml配置
检查android/app/src/main/AndroidManifest.xml,确保权限、服务声明齐全:
<!-- Android 13+ 需添加通知权限 --> <uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <!-- 声明flutter_local_notifications所需的后台服务 --> <service android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver" android:exported="false"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <action android:name="android.intent.action.MY_PACKAGE_REPLACED" /> </intent-filter> </service> <service android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver" android:exported="false" /> <service android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationService" android:exported="false" />
同时确保通知图标符合安卓规范:背景透明,避免因图标显示异常导致通知被系统隐藏。
方案三:修正Flutter端通知初始化代码
在Flutter代码中,确保为Android平台正确配置初始化参数与通知渠道(Android 8.0+必需):
final AndroidInitializationSettings androidInitSettings = AndroidInitializationSettings('@mipmap/ic_notification'); // 替换为你的图标资源名 final InitializationSettings initSettings = InitializationSettings(android: androidInitSettings); await flutterLocalNotificationsPlugin.initialize(initSettings); // 创建通知渠道 const AndroidNotificationChannel channel = AndroidNotificationChannel( 'primary_channel', '主通知渠道', description: '接收应用所有本地通知', importance: Importance.max, ); await flutterLocalNotificationsPlugin .resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>() ?.createNotificationChannel(channel);
注意:通知图标资源必须存在于安卓项目的mipmap或drawable目录中,且未被资源压缩移除。
内容的提问来源于stack exchange,提问作者MeLean
相关产品推荐
相关产品推荐

