【发布时间】:2022-12-22 16:09:19
【问题描述】:
我正在使用以下代码接收和显示推送通知:
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.createNotificationChannels(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())
}
}
但 PN 仅在应用程序处于后台或关闭时显示。调试 FCMMessagingService,我可以看到 PN 由服务器发送并在 onMessageReceive() 中接收。 notify() 方法似乎不起作用,或者代码中的其他内容失败了。
根据this article,当应用程序在后台时,FCM 通知由内部 Firebase 服务处理,否则当应用程序在前台时,它们会在FirebaseMessagingService 的onMessageReceived() 中接收,我们必须手动显示它们notify()。但这不起作用。
我们已经在here、here、here和here之前看到过这个问题。但那可能是旧的 GCM 功能仍然存在于 FCM 中的时候。到这个时候,FCM 一定已经彻底检修过了。
我的问题是:
- 如果推送通知在应用程序处于前台时到达,处理推送通知的默认协议是什么?
- 看看其他流行的应用程序 - WhatsApp、Google Pay、Zomato - 我不记得当应用程序在前台时看到推送通知。这是否意味着当应用程序在前台时,推送通知永远不会出现在托盘中?
- 如果是这样,那么首先使用
NotificationManager.notify()函数的原因是什么?如果推送通知仅在应用程序处于后台时出现,并且由 Firebase 服务自动处理,那么为什么要使用此方法呢?这只是旧 GCM 库的遗物吗?
有人可以指出问题出在哪里吗?
【问题讨论】:
-
是的,推送通知只能在应用程序处于后台时显示,因为这是推送通知的目的。如果用户不使用该应用程序,请引起他们的注意。通知管理器和通知用于本地推送通知,这就是该方法存在的原因。
-
可能有一种解决方法可以在使用该应用程序时获取通知
-
这似乎是通知渠道的问题。手动调用 notify()应该在任何情况下都显示 PN。
标签: android firebase kotlin push-notification firebase-cloud-messaging