Android端FCM通知在后台/杀死状态下显示横幅的配置方法
Android后台/杀死状态下FCM消息显示横幅的配置参数问题
核心问题
当Android应用处于后台或被杀死状态时,FCM消息显示横幅需配置哪些具体参数?
调研方向
- A) FCM消息JSON定义
- B) Flutter代码配置(如
FCM.instance.makeAndroidShowBannerInBackground(true)) - C) Android原生自定义配置(如创建自定义消息通道)
当前环境与消息配置
使用Flutter+Firebase的应用,云函数采用JavaScript v1版本定义消息:
const multicastMessage = { tokens: tokens, // 设备令牌数组 notification: { title: `来自${userName}的提醒`, body: notificationBody, }, android: { priority: "high", // Android通知高优先级 ttl: 60, // 存活时间60秒(约1分钟) notification: { sound: "custom_notification_sound_alert", }, }, apns: { headers: { "apns-priority": "10", // APNs高优先级 // 60秒后过期 "apns-expiration": `${Math.floor(Date.now() / 1000) + 60}`, }, payload: { aps: { "alert": { title: `来自${userName}的提醒`, body: notificationBody, }, "sound": "CustomNotificationSoundAlert.wav", }, }, }, };
遇到的问题
消息可正常推送到Android和iOS客户端,但Android端在应用后台或被杀死状态下,通知仅以小图标形式出现在系统托盘,不会在界面顶部显示横幅。
已尝试操作
- 找到一个较早的相关话题,但不确定是否仍适用;
- 查阅Firebase FCM官方文档,但未找到直接针对该问题的明确说明,因FCM体系复杂难以定位具体查阅方向。
疑问与线索
原本认为FCM作为封装层无需原生配置,但查看Firebase Android SDK源码发现,默认创建的通知通道使用IMPORTANCE_DEFAULT,注释说明该级别“全平台显示、有提示音,但不会视觉干扰”,这可能是横幅不显示的原因。
同时存在以下疑问:
- 如果默认通道优先级不足,为何FCM消息JSON中存在Android优先级字段?
- SDK为何不能根据JSON中的优先级自动创建对应级别的默认通道?
- 是否只是
priority: "high"的大小写问题(比如需要大写"High")?
解决方案总结
要实现Android后台/杀死状态下FCM消息显示横幅,需同时配置以下内容:
FCM消息JSON配置
- 确保
android.priority设为"high"(v1 API要求小写,此参数控制消息送达优先级,保证消息不被延迟); - 在
android.notification中指定自定义通知通道ID,示例:android: { priority: "high", notification: { sound: "custom_notification_sound_alert", channelId: "high_priority_channel" // 绑定自定义高优先级通道 }, }
- 确保
Android原生创建高优先级通知通道
FCM默认通道为IMPORTANCE_DEFAULT,该级别不会弹出横幅,必须手动创建IMPORTANCE_HIGH级别的通道。在Android原生代码(如MainActivity或自定义Application类)中添加如下代码:import android.app.NotificationChannel; import android.app.NotificationManager; import android.os.Build; import androidx.core.app.NotificationManagerCompat; // 在应用启动时执行此方法 private void createNotificationChannels() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel highPriorityChannel = new NotificationChannel( "high_priority_channel", "高优先级通知", NotificationManager.IMPORTANCE_HIGH ); highPriorityChannel.setDescription("用于显示需要立即关注的通知横幅"); highPriorityChannel.enableVibration(true); // 可选:开启震动 NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); notificationManager.createNotificationChannel(highPriorityChannel); } }注意:Android通知通道一旦创建,其级别无法修改,若需调整需卸载重装应用后重新创建。
Flutter端补充配置
使用firebase_messaging插件时,确保调用以下方法开启前台通知展示选项:await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions( alert: true, badge: true, sound: true, );注:
makeAndroidShowBannerInBackground(true)在新版插件中已被替代,以官方最新文档为准。
疑问解答
- FCM的
android.priority控制消息送达优先级,而Android通知的显示级别由通道的importance属性决定,两者是独立的配置项; - SDK不会自动创建不同级别的通道,因为通道是系统级配置,需要开发者自主管理,避免频繁创建通道导致系统通知设置混乱;
priority: "high"的写法正确,v1 API要求小写,大写会被视为无效参数。
内容的提问来源于stack exchange,提问作者Nerdy Bunz
相关产品推荐
相关产品推荐

