You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin中如何在App后台运行时禁用FCM推送通知?

解决FCM后台通知无法通过showNotification控制的问题

FCM的通知消息(Notification Message)在App后台时会直接由系统接管展示,不会进入onMessageReceived,所以没法直接通过你当前的逻辑拦截。有两种可行方案解决这个问题:

方案一:改用数据消息(Data Message)发送

数据消息不管App处于前台还是后台,都会触发onMessageReceived方法,这样你就能统一用showNotification变量控制通知展示逻辑。

服务器端调整消息结构

把原来的通知消息改成数据消息,示例JSON结构如下:

{
  "to": "目标设备的FCM Token",
  "data": {
    "title": "你的通知标题",
    "body": "你的通知内容",
    // 可添加其他自定义字段
  }
}

App端统一处理逻辑

修改onMessageReceived,读取数据消息内容并判断是否展示:

override fun onMessageReceived(remoteMessage: RemoteMessage) {
    super.onMessageReceived(remoteMessage)
    
    // 从data字段提取通知内容
    val title = remoteMessage.data["title"]
    val body = remoteMessage.data["body"]
    
    // 统一判断是否展示通知
    if (showNotification && title != null && body != null) {
        generateNot(title, body)
    }
}

这种方案的优势是前后台逻辑完全一致,所有通知都由App自主控制,无系统干预。

方案二:通过通知通道(Notification Channel)控制

如果无法修改服务器端消息类型,只能用通知消息的话,可以通过禁用FCM对应的通知通道来阻止系统展示通知。

操作步骤:

  1. 确保App创建了FCM专属通知通道(若未手动创建,FCM会自动生成默认通道,ID通常为fcm_default_channel)。
  2. 当showNotification为false时,禁用该通道:
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val fcmChannel = notificationManager.getNotificationChannel("fcm_default_channel")
fcmChannel?.let {
    // 将通道重要性设为NONE,系统不再展示该通道的通知
    it.importance = NotificationManager.IMPORTANCE_NONE
    notificationManager.createNotificationChannel(it)
}
  1. 需要恢复通知时,将通道重要性改回原级别(比如IMPORTANCE_DEFAULT)。

注意:此方法会全局禁用该通道的所有通知,若有其他业务通知复用该通道会一同被屏蔽,建议给FCM单独配置专属通道。

内容的提问来源于stack exchange,提问作者Mi_Dhah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 14:09:21