Flutter FCM:应用后台/关闭时如何保留AndroidNotificationDetails配色
解决FCM后台/关闭状态下通知配色不生效的问题
核心原因
当应用处于后台或完全关闭时,FCM的通知类型消息会直接由Android系统接收并展示,不会触发Flutter端的FirebaseMessaging.onMessage或后台handler里的自定义通知逻辑,而是优先使用FCM消息携带的Android配置,或系统通知渠道的默认配置——这就是你在AndroidNotificationDetails里设置的橙色不生效的原因。
具体解决步骤
1. 初始化时配置通知渠道的默认颜色
通知渠道创建后,其颜色属性无法通过代码修改,必须在首次创建时指定。确保App启动时初始化通知渠道,并设置目标橙色:
void setupFlutterNotification() { const AndroidNotificationChannel channel = AndroidNotificationChannel( 'your_channel_id', // 与前台展示通知时使用的channel.id完全一致 'your_channel_name', description: 'your_channel_description', importance: Importance.max, color: ControllerColors.getPrimaryColor(), // 在这里设置渠道默认颜色 ); final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); // 创建通知渠道 flutterLocalNotificationsPlugin .resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>() ?.createNotificationChannel(channel); }
将这段初始化代码放在main函数执行流的最前端,确保渠道在App启动时就被创建。
2. 给FCM消息添加Android颜色配置(可选)
如果需要覆盖渠道默认颜色,在发送FCM消息时可直接指定Android端的通知颜色:
- Firebase控制台发送:进入「高级选项」→「Android配置」,在「颜色」字段填入橙色的十六进制值(如
#FFA500)。 - API接口发送:在请求体的
android.notification节点中添加color参数:
{ "message": { "token": "设备推送令牌", "notification": { "title": "通知标题", "body": "通知内容" }, "android": { "notification": { "color": "#FFA500" } } } }
3. 后台handler手动展示数据消息(针对纯数据消息)
如果你的FCM消息是纯数据消息(不含notification字段),后台状态下会触发_firebaseMessagingBackgroundHandler,此时可以在handler里手动调用通知插件展示自定义配置的通知:
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage remoteMessage) async { await Firebase.initializeApp(); await setupFlutterNotification(); // 从数据字段中提取通知内容 String title = remoteMessage.data['title'] ?? '默认标题'; String body = remoteMessage.data['body'] ?? '默认内容'; final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); flutterLocalNotificationsPlugin.show( remoteMessage.data.hashCode, title, body, NotificationDetails( android: AndroidNotificationDetails( 'your_channel_id', 'your_channel_name', channelDescription: 'your_channel_description', color: ControllerColors.getPrimaryColor(), icon: "@mipmap/ic_launcher" ) ) ); }
注意:只有纯数据消息会触发后台handler,含notification字段的通知消息仍由系统直接展示。
验证注意事项
- 测试前需卸载重装App,确保新的通知渠道配置被系统正确加载。
- 分别测试后台、完全关闭两种状态下的通知展示效果。
内容的提问来源于stack exchange,提问作者ThomasF
相关产品推荐
相关产品推荐

