如果我通过 Firebase 云功能使用数据消息发送,为什么不会显示通知?



我像这样使用云函数发送FCM

const payload = {
data: {
imagePath: imagePath,
priority: priority,
title: title,
body: body
}
}
await admin.messaging().sendToDevice(token,payload)

这是我的Android应用程序上的代码,在onMessageReceived中,下面的onMessageReceived代码实际上被调用了,但我不知道为什么通知没有显示在我的设备中

override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
var title: String = ""
var body: String = ""
var priority: String = ""
var imagePath: String = ""

remoteMessage.notification?.let {
title = it.title ?: ""
body = it.body ?: ""
}

val notificationData = remoteMessage.data
priority = notificationData["priority"] ?: ""
imagePath = notificationData["imagePath"] ?: ""
title = notificationData["title"] ?: ""
body = notificationData["body"] ?: ""
setUpNotification(title,body,priority,imagePath)
}

并向设备显示通知

private fun setUpNotification(title: String, message: String, priority: String, imagePath: String) {

val channel = if (priority == "high") NOTIFICATION_CHANNEL_IMPORTANT else NOTIFICATION_CHANNEL_MISCELLANEOUS
var notification = NotificationCompat.Builder(this, channel)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle(title)
.setContentText(message)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setAutoCancel(true)
.setOnlyAlertOnce(true)
.build()
notificationManager.notify(1, notification)
}

但是如果我像这样在有效负载上添加通知消息(不仅仅是数据消息(

const payload = {
notification: {
body: body,
title: title,
},
data: {
imagePath: imagePath,
priority: priority,
title: title,
body: body
}
}

然后通知将显示在我的设备上

试试这个:

private fun sendNotification(title: String, messageBody: String, notify_type: String) {
var icon= BitmapFactory.decodeResource(resources,
R.mipmap.ic_launcher);
val intent = Intent("SplashActivity")// use your activity 
intent.putExtra("type", "notification")// here i'm passing data onClick of notification
intent.putExtra("title", notify_type)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val r = Random()
val i1 = r.nextInt(20 - 0 + 1) + 0
val pendingIntent = PendingIntent.getActivity(this,i1,intent,PendingIntent.FLAG_UPDATE_CURRENT)
val channelId = this.resources.getString(R.string.default_notification_channel_id)
val builder = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_appicon)
.setContentTitle(title)
.setContentText(messageBody).setAutoCancel(true).setContentIntent(pendingIntent)
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(channelId, "Default channel",NotificationManager.IMPORTANCE_HIGH)
manager.createNotificationChannel(channel)
}
manager.notify(i1,builder.build())
}

根据 FCM 文档,有两种类型的消息:通知消息和数据消息。

当您将Notification部分添加到按摩中时,您将按摩类型从数据类型更改为通知类型。 在同一文档中,您可以找到通知类型"自动向最终用户设备显示消息"。

我认为这种机制负责在您添加部分时显示通知Notification。您可以搜索解决方案是您的客户端应用程序,因为问题很可能出在那里。

相关内容

  • 没有找到相关文章

最新更新