Android端Firebase Cloud Messaging通知图标与跳转异常问题
FCM后台/关闭状态下通知问题修复
问题1:通知图标显示空白圆形
原因
应用处于后台或关闭状态时,FCM的notification类型消息会直接由系统通知栏处理,不会触发onMessageReceived方法,此时系统会使用Manifest中配置的默认通知图标,而非代码里设置的R.drawable.notification_icon。另外,Android通知图标要求必须是透明背景的单色矢量图/位图,不符合要求的图标会显示空白。
修复步骤
- 确保
notification_icon符合规范:使用透明背景,仅包含白色(或适配系统深色模式的单色)图形,建议用矢量图(Vector Asset)制作。 - 在
AndroidManifest.xml中添加FCM默认图标配置:
<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/notification_icon" /> <!-- 可选:配置深色模式下的图标颜色 --> <meta-data android:name="com.google.firebase.messaging.default_notification_color" android:resource="@color/notification_icon_color" />
问题2:点击通知打开应用而非指定网页
原因
后台/关闭状态下,notification类型消息的跳转逻辑由系统处理,系统默认会打开应用主Activity,而非代码中设置的ACTION_VIEW意图。要自定义跳转行为,必须使用数据消息(data payload),而非通知消息。
修复步骤
- 发送FCM消息时,使用
data字段传递内容,而非notification字段。示例后端发送的JSON格式:
{ "to": "用户设备token", "data": { "title": "更新通知", "body": "应用有新更新", "url": "https://github.com/georgeclensy/escape" } }
- 修改
MyFirebaseMessagingService的onMessageReceived方法,从remoteMessage.data中提取数据:
override fun onMessageReceived(remoteMessage: RemoteMessage) { super.onMessageReceived(remoteMessage) // 从data字段获取通知内容 val title = remoteMessage.data["title"] ?: "默认标题" val body = remoteMessage.data["body"] ?: "默认内容" val url = remoteMessage.data["url"] ?: "" val notificationIntent = if (url.isNotEmpty()) { Intent(Intent.ACTION_VIEW, Uri.parse(url)) } else { Intent(this, MainActivity::class.java) } sendNotification(this, title, body, "updates", "Updates", notificationIntent) }
- 保持
PendingIntent的标记正确(当前代码已添加FLAG_IMMUTABLE,适配Android 12+,无需修改)。
额外注意事项
- 测试后台通知时,需完全退出应用(划掉进程),不能仅按Home键。
- Android 13+需申请
POST_NOTIFICATIONS权限,并在运行时请求用户授权。 - 若同时使用
notification和data字段,后台状态下系统仍优先处理notification字段,建议仅用data字段统一前后台通知逻辑。
内容的提问来源于stack exchange,提问作者George Clensy
相关产品推荐
相关产品推荐

