首页 > 解决方案 > 推送通知 Kotlin

问题描述

我尝试使用notificationBuilderand创建通知notificationManager。一切似乎都很好,但是当应用程序处于后台或前台时,通知都不会出现。

你能帮我吗?这是到目前为止的代码:

class MyFirebaseMessagingService : FirebaseMessagingService() {

    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        Log.i("info", "Message received: ${remoteMessage.from}")

        Log.i("info", remoteMessage.data.toString())

        if (remoteMessage.data != null) {
            showNotification(remoteMessage.data.get("title"), remoteMessage.data.get("text"))
        }


    }


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

        Log.i("info", "show notification $title    $body")



        val intent = Intent(this, MainActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        val pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT)
        val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
        val notificationBuilder = NotificationCompat.Builder(this)
                .setContentText(body)
                .setAutoCancel(true)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent)
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build())

    }
}

标签: androidkotlinpush-notificationpush

解决方案


推荐阅读