Flutter集成FCM与flutter_local_notifications时Android 12+崩溃求助
解决Flutter FCM通知崩溃、类未找到及前台不显示问题
1. 修复'Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified'崩溃
- 打开安卓项目
android/app/build.gradle,若compileSdkVersion和targetSdkVersion为31及以上,添加WorkManager兼容依赖:dependencies { // 其他依赖保留 implementation "androidx.work:work-runtime:2.8.1" // 版本需≥2.7.0 } - 或升级FCM相关依赖到最新稳定版:
在android/build.gradle更新Google服务插件:
在dependencies { classpath 'com.google.gms:google-services:4.4.0' // 最新稳定版 }android/app/build.gradle更新firebase-messaging:implementation 'com.google.firebase:firebase-messaging:23.3.1' // 最新稳定版
2. 解决'com.example.blog_app.java.MyFirebaseMessagingService'类未找到错误
- 检查
android/app/src/main/AndroidManifest.xml中服务注册路径:若用Kotlin实现服务,路径需去掉.java后缀;若用Java,确认文件在java/com/example/blog_app/目录下,类名与注册名称完全一致。 - 正确的服务注册示例:
<service android:name=".MyFirebaseMessagingService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service> - 执行
flutter clean→flutter pub get,重新编译项目。
3. 修复前台不显示通知问题
- 确保正确初始化
flutter_local_notifications:final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); Future<void> _initializeNotifications() async { const AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings('@mipmap/ic_launcher'); const InitializationSettings initializationSettings = InitializationSettings(android: initializationSettingsAndroid); await flutterLocalNotificationsPlugin.initialize(initializationSettings); await _createNotificationChannel(); // 调用渠道创建方法 } - 配置前台消息监听并显示通知:
void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); await _initializeNotifications(); FirebaseMessaging.onMessage.listen((RemoteMessage message) { RemoteNotification? notification = message.notification; AndroidNotification? android = message.notification?.android; if (notification != null && android != null) { flutterLocalNotificationsPlugin.show( notification.hashCode, notification.title, notification.body, NotificationDetails( android: AndroidNotificationDetails( 'blog_app_channel', 'Blog App Notifications', channelDescription: 'Notifications for blog updates', icon: android.smallIcon, ), ), ); } }); FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler); runApp(const MyApp()); } - 补充创建Android通知渠道(Android 8.0+强制要求):
Future<void> _createNotificationChannel() async { const AndroidNotificationChannel channel = AndroidNotificationChannel( 'blog_app_channel', 'Blog App Notifications', description: 'Notifications for blog updates', importance: Importance.max, ); await flutterLocalNotificationsPlugin .resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>() ?.createNotificationChannel(channel); }
内容的提问来源于stack exchange,提问作者ayush
相关产品推荐
相关产品推荐

