Flutter iOS端FirebaseMessaging锁屏/后台时通知不显示问题求助
Flutter FirebaseMessaging后台(锁屏/切应用)通知不显示的解决方案
1. 确认Firebase消息类型
Firebase推送分通知消息和数据消息两种:
- 若发送的是通知消息,应用后台时系统会自动展示通知,无需通过
onBackgroundMessage处理; - 若发送的是数据消息(或混合消息中需自定义通知),才需要依赖
onBackgroundMessage手动构建通知。
先确认你发送的消息类型是否符合预期,若为纯通知消息但后台不显示,直接检查系统通知设置。
2. 提前创建Android通知渠道
你的代码中定义了通知渠道,但仅在后台handler中使用是不够的——渠道需要在应用启动时就完成创建,否则后台触发时可能因渠道未注册导致通知不显示。
在应用初始化阶段添加渠道创建逻辑:
// 全局声明插件实例 late FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin; // 应用启动时调用初始化 void initAppNotifications() async { flutterLocalNotificationsPlugin = await initializeFlutterLocalNotification(); // 创建Android通知渠道 const androidChannel = AndroidNotificationDetails( 'hubb channel id', 'Hubb Channel', channelDescription: 'hubb! everyone is here', importance: Importance.max, priority: Priority.high, visibility: NotificationVisibility.public, ); await flutterLocalNotificationsPlugin .resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>() ?.createNotificationChannel(AndroidNotificationChannel( androidChannel.channelId, androidChannel.channelName, description: androidChannel.channelDescription, importance: androidChannel.importance, )); }
3. 修正后台handler的插件实例使用
后台handler运行在隔离环境中,每次调用initializeFlutterLocalNotification()可能导致初始化失败。建议直接使用全局初始化好的插件实例,而非在handler中重复初始化:
Future _firebaseMessagingBackgroundHandler(RemoteMessage msg) async { print("Handling a background message: ${msg.messageId}"); if (msg.data["clearNotification"] != null) { clearNotification(); return; } const androidPlatformChannelSpecifics = AndroidNotificationDetails( 'hubb channel id', 'Hubb Channel', channelDescription: 'hubb! everyone is here', fullScreenIntent: true, sound: RawResourceAndroidNotificationSound('ringing_sound'), playSound: true, importance: Importance.max, priority: Priority.high, visibility: NotificationVisibility.public, ticker: 'ticker', ); const iosnotificationDetails = IOSNotificationDetails( sound: "ringing_sound.wav", presentAlert: true, presentSound: true, ); const platformChannelSpecifics = NotificationDetails( android: androidPlatformChannelSpecifics, iOS: iosnotificationDetails, ); // 使用全局已初始化的插件实例 await flutterLocalNotificationsPlugin.show( // 用消息ID生成唯一通知ID,避免重复通知被覆盖 msg.messageId.hashCode, 'Incoming Call', 'Hubb incoming call', platformChannelSpecifics, payload: jsonEncode(msg.data), ); }
4. 检查Android权限配置
- Android 13+需在
AndroidManifest.xml中添加通知权限:
并在运行时主动请求该权限。<uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> - 部分国产厂商(小米、华为等)需手动开启应用的后台运行权限,否则后台进程被限制后无法触发通知。
5. 验证锁屏通知权限
- Android:进入系统设置 → 通知 → 你的应用 → 锁屏通知,选择「显示所有通知内容」;
- iOS:进入系统设置 → 通知 → 你的应用 → 显示预览,选择「始终」。
内容的提问来源于stack exchange,提问作者Hamza Kaleem
相关产品推荐
相关产品推荐

