Android中FCM后台/杀死状态下悬浮通知不显示问题求助
解决FCM后台/杀死状态下悬浮通知不显示的问题
我来帮你搞定这个问题!你遇到的核心问题是Android 8.0+的通知渠道权限和FCM消息payload的处理逻辑导致的,咱们一步步调整:
1. 修复通知渠道的重要性级别(关键!)
Android 8.0之后,只有高优先级的通知渠道才能触发悬浮(Heads Up)通知。你当前代码里把渠道重要性设为IMPORTANCE_DEFAULT,这是普通级别,后台时系统不会弹出悬浮通知。
修改Android端创建渠道的代码:
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ val channelName ="ScheduleChannel" // 把IMPORTANCE_DEFAULT改成IMPORTANCE_HIGH val channel = NotificationChannel(channelId,channelName,NotificationManager.IMPORTANCE_HIGH) channel.enableLights(true) channel.lightColor= 0x00FFFF channel.setShowBadge(false) // 可选:确保渠道的声音配置正确 val audioAttributes = AudioAttributes.Builder() .setUsage(AudioAttributes.USAGE_NOTIFICATION) .build() channel.setSound(defaultSoundUri, audioAttributes) notificationManager.createNotificationChannel(channel) }
2. 调整FCM消息的Payload配置
你当前用的是notification类型的消息,当应用在后台/被杀死时,FCM会直接把消息交给系统处理,不会走你的FirebaseMessagingService,所以你在Service里设置的高优先级参数根本不会生效。
需要在Node.js的消息里明确指定Android通知的优先级和渠道ID:
var message = { android: { priority: 'high', // 新增android通知配置,指定优先级和渠道ID notification: { priority: 'high', channelId: '1000' // 必须和Android端的channelId完全一致! } }, notification: { title: 'Updated', body: pushMsg }, condition: condition };
3. 优化PendingIntent的兼容性(Android 12+)
Android 12及以上版本要求PendingIntent必须指定FLAG_IMMUTABLE或FLAG_MUTABLE,否则会抛出异常。修改你的PendingIntent创建代码:
val pendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { PendingIntent.getActivity( this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) } else { PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT) }
4. 可选:改用Data消息完全自定义通知
如果你想完全自己控制通知的展示逻辑(不管前台/后台),建议改用data类型的消息。这种消息无论应用状态如何,都会触发onMessageReceived,你可以在Service里完全自定义通知:
Node.js代码修改:
var message = { android: { priority: 'high' }, data: { title: 'Updated', body: pushMsg }, condition: condition };
Android端Service修改:
override fun onMessageReceived(remoteMessage: RemoteMessage) { Log.d("TAG", "From: " + remoteMessage.from!!) // 从data中获取消息内容 val messageBody = remoteMessage.data["body"] val messageTitle = remoteMessage.data["title"] // 剩下的通知构建逻辑和你原来的一样... }
测试注意事项
- 测试后台状态时,一定要完全退出应用(不要在开发者选项里设置“不保留活动”,用正常的返回键退出)
- 确保设备的通知权限已经打开,并且你的应用通知渠道的“重要性”设置为“高”(可以在系统设置-应用和通知-你的应用-通知里查看)
内容的提问来源于stack exchange,提问作者jakchang
相关产品推荐
相关产品推荐

