Flutter集成FCM实现安卓iOS双端悬浮通知兼容问题咨询
解决方法
步骤1:调整FCM推送payload结构,使用平台专属配置
FCM本身支持分别为安卓、iOS平台配置不同的推送参数,不需要全局共用notification字段,从根源避免安卓端自动弹出通知:
- 全局仅保留通用的
data字段 - 仅在iOS专属配置块中添加
notification相关参数 - 安卓专属配置块中明确不配置自动通知参数,避免FCM自动弹出
正确推送payload示例(以HTTP v1 API为例)
{ "message": { "topic": "all", "data": { "title": "Alert", "body": "App maintenance is underway." }, // iOS专属配置 "apns": { "payload": { "aps": { "alert": { "title": "Alert", "body": "App maintenance is underway." }, "sound": "default", "badge": 1 } } }, // 安卓专属配置,不添加notification字段,禁止FCM自动弹通知 "android": { "priority": "high" } } }
如果使用旧版Legacy API,配置方式如下:
{ "to": "/topics/all", "data": { "title": "Alert", "body": "App maintenance is underway." }, // 仅iOS会识别这个notification字段的配置 "notification": { "title": "Alert", "body": "App maintenance is underway.", "sound": "default" }, "android": { "notification": null }, "content_available": true, "mutable_content": true }
步骤2:代码侧兜底处理(避免配置失误导致重复通知)
在showNotification调用前增加平台判断,安卓端如果检测到FCM已经自动生成了RemoteNotification对象,就跳过手动弹出逻辑:
import 'dart:io'; // 原FirebaseMessaging.onMessage.listen回调逻辑修改为: FirebaseMessaging.onMessage.listen((RemoteMessage message) { print('Got a message whilst in the foreground!'); print('title ${message.data['title']}'); print('body ${message.data['body']}'); if (message.data.isNotEmpty) { // 安卓端如果自带notification,说明FCM会自动弹出,跳过手动弹出 if (Platform.isAndroid && message.notification != null) { return; } showNotification(message); } }); // 后台消息回调也做同样处理: Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async { await Firebase.initializeApp(); print('A message just showed up, id: ${message.messageId}'); if (Platform.isAndroid && message.notification != null) { return; } showNotification(message); }
注意事项
你现有代码中flutterLocalNotificationsPlugin.initialize没有实际执行调用,需要补全初始化参数和括号,否则本地通知可能无法正常弹出,修改参考:
await flutterLocalNotificationsPlugin.initialize( const InitializationSettings( android: AndroidInitializationSettings('@drawable/ic_stat_output_onlinepngtools') ) );
该配置方案不需要提前判断设备所属系统,FCM会自动根据设备平台加载对应配置,同时满足iOS正常展示通知、安卓端仅显示自定义悬浮通知的需求。
内容的提问来源于stack exchange,提问作者RJB
相关产品推荐
相关产品推荐

