提问者:小点点

收到Firebase云消息,但没有弹出!!!--科特林


我正在构建一个从Firebase接收通知的应用程序。应用程序收到通知但没有弹出它。

任何帮助!

类MyFirebaseMessagingService:FirebaseMessagingService(){

val TAG = "FirebaseMessagingService"

override fun onMessageReceived(p0: RemoteMessage) {    

    super.onMessageReceived(p0)
    Log.d(TAG, "{$p0}")


    if (p0.notification !=null){
        showNotification(p0.notification?.title, p0.notification?.body)

    }

}


private fun showNotification(title: String?, body: String?){

    val intent=Intent(applicationContext, MainActivity::class.java)
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
    val pendingIntent=PendingIntent.getActivities(
        this,
        0,
        arrayOf(intent),
        PendingIntent.FLAG_UPDATE_CURRENT
    )
    //val soundUri=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)


    val notificationBuilder = NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.ic_logo_border)
        .setContentTitle(title)
        .setContentText(body)
        .setAutoCancel(true)
        .setContentIntent(pendingIntent)
        .setPriority(2)

    val notificationManager=getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    notificationManager.notify(0, notificationBuilder.build())


}

override fun onNewToken(token: String) {
    super.onNewToken(token)
    Log.d(TAG, "Refreshed token: $token")

}

共1个答案

匿名用户

我想这是因为Android8.0的通知通道。

在生成通知之前调用此函数。

private fun createNotificationChannel(context: Context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            val existingChannel = notificationManager.getNotificationChannel(CHANNEL_ID)
            if (existingChannel == null) {
                // Create the NotificationChannel
                val name = context.getString(R.string.defaultChannel)
                val importance = NotificationManager.IMPORTANCE_DEFAULT
                val mChannel = NotificationChannel(CHANNEL_ID, name, importance)
                mChannel.description = context.getString(R.string.notificationDescription)
                notificationManager.createNotificationChannel(mChannel)
            }
        }
    }

并将其与代码一起使用

NotificationManagerCompat.from(context).apply {
    cancelAll() // Remove prior notifications; only allow one at a time.
    notify(1 or your notification id, notificationBuilder.build())
}

而不是

val notificationManager=getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager 
notificationManager.notify(0, notificationBuilder.build())