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监听系统通知的发布,在通知展示前修改内容。但这个方案需要用户手动授予“通知访问权限”,体验上有一定门槛。
步骤:
- 创建继承自
NotificationListenerService的类,重写onNotificationPosted()方法 - 在方法中拦截Firebase发送的通知,修改其内容后重新发布
- 在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
相关产品推荐
相关产品推荐

