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

Android后台时FirebaseMessagingService未触发,如何修改含通知与数据负载的消息?

解决方案

方案1:后端仅发送数据负载(推荐)

直接让后端只发送纯数据负载的消息,不要包含通知字段。这样无论应用处于前台还是后台,onMessageReceived()都会被触发,你可以在方法内完全自定义通知的内容、样式、行为,处理完后调用NotificationManager手动展示通知。

示例代码片段:

override fun onMessageReceived(remoteMessage: RemoteMessage) {
    // 提取自定义数据
    val customData = remoteMessage.data
    val title = customData["title"] ?: "默认标题"
    val content = "修改后的内容:${customData["content"]}"

    // 构建自定义通知
    val notificationBuilder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.ic_notification)
        .setContentTitle(title)
        .setContentText(content)
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)

    // 展示通知
    val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    notificationManager.notify(System.currentTimeMillis().toInt(), notificationBuilder.build())
}

方案2:拦截系统通知(需用户授权)

如果后端无法调整消息格式,可以使用NotificationListenerService监听系统通知的发布,在通知展示前修改内容。但这个方案需要用户手动授予“通知访问权限”,体验上有一定门槛。

步骤:

  1. 创建继承自NotificationListenerService的类,重写onNotificationPosted()方法
  2. 在方法中拦截Firebase发送的通知,修改其内容后重新发布
  3. 在Manifest中声明服务并添加对应权限

注意:这种方式需要处理系统版本兼容,且部分厂商可能会限制该服务的运行。

方案3:处理通知点击后的逻辑(仅补充方案)

如果不需要修改通知展示内容,只需要在用户点击通知时处理自定义数据,可以在启动的Activity中获取Intent里的附加数据:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    // 获取数据
    val data = intent.extras
    data?.let {
        val customKey = it.getString("custom_key")
        // 处理数据逻辑
    }
}

但此方案无法修改通知展示时的内容,只能处理点击后的行为。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 01:07:04