FCM推送仅在后台显示问题排查及相关技术疑问
FCM前台推送通知不显示问题排查与疑问解答
问题代码
override fun onMessageReceived(remoteMessage: RemoteMessage) { if (remoteMessage.getNotification() != null) { var title : String = remoteMessage.notification!!.title!! var message : String = remoteMessage.notification!!.body!! val intent = Intent(this, LoginCommonActivity::class.java) intent.addFlags(intent.FLAG_ACTIVITY_CLEAR_TOP) val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT) var builder: NotificationCompat.Builder; val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager //val notificationManager = NotificationManagerCompat.from(applicationContext) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val notificationChannel = NotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_HIGH) notificationManager.createNotificationChannel(notificationChannel) builder = NotificationCompat.Builder(applicationContext, notificationChannel.id) } else { builder = NotificationCompat.Builder(applicationContext) } builder = builder.setSmallIcon(R.drawable.ic_app_logo_black) .setContentTitle(title) .setContentText(message) .setAutoCancel(true) .setVisibility(Notification.VISIBILITY_PUBLIC) .setDefaults(Notification.DEFAULT_ALL) .setVibrate(longArrayOf(1000, 1000, 1000, 1000)) .setOnlyAlertOnce(true) .setContentIntent(pendingIntent) notificationManager.notify(System.currentTimeMillis().toInt(), builder.build()) } }
问题描述
我用上述代码接收并展示FCM推送通知,但推送仅在应用后台或关闭状态时显示。调试FirebaseMessagingService时,能确认服务器已发送推送且onMessageReceived()已接收,但notify()方法似乎未生效。
根据Firebase官方文档,应用后台时FCM通知由Firebase内部服务处理,前台时则由FirebaseMessagingService的onMessageReceived()接收,需手动调用notify()展示,但当前逻辑不生效。
我有以下疑问:
- 应用前台时,处理推送通知的默认规则是什么?
- 观察WhatsApp、Google Pay、Zomato等应用,前台时从未看到推送通知,是否意味着前台时推送不会显示在通知栏?
- 若上述情况成立,
NotificationManager.notify()存在的意义是什么?是否是旧GCM库遗留的功能?
恳请指出问题所在。
问题排查与解答
代码问题修复
- 通知通道创建API错误:Android O及以上版本代码中,你调用了
createNotificationChannels()(复数),但该方法参数是List<NotificationChannel>,正确调用应为createNotificationChannel()(单数)。这个错误会导致通知通道创建失败,直接导致前台无法展示通知。 - Intent方法拼写错误:
intent.addflags()应为intent.addFlags()(首字母大写),此错误不影响通知显示,但会导致后续页面跳转逻辑异常。 - 通知ID潜在冲突:使用
System.currentTimeMillis().toInt()作为通知ID,短时间内多次推送可能出现ID重复覆盖的情况,建议改用固定唯一ID或递增ID。
疑问解答
- 前台处理推送的默认规则:
FCM推送分两类:- 通知消息:应用前台时,直接传递到
onMessageReceived(),系统不会自动展示通知,需开发者手动调用notify();应用后台/关闭时,由系统自动展示通知。 - 数据消息:无论应用处于前台还是后台,都会传递到
onMessageReceived(),需开发者自行处理展示逻辑。
- 通知消息:应用前台时,直接传递到
- 前台是否显示通知栏:
这是应用的设计选择,而非强制规则。WhatsApp这类应用在前台时,会把推送内容直接展示在App内界面,避免重复打扰用户;但开发者完全可以选择在前台展示通知栏,比如新闻类App通常会这么做。 NotificationManager.notify()的意义:
它不是GCM遗留功能,是Android系统通知框架的核心API,负责向系统发送通知请求。FCM仅负责传递推送内容,通知的展示样式、交互行为等完全由开发者通过该API控制,比如自定义布局、添加操作按钮、设置优先级等,所有推送服务最终都依赖这个API完成通知展示。
内容的提问来源于stack exchange,提问作者Yash Sampat
相关产品推荐
相关产品推荐

