在 Kotlin 中处理推送通知

Handle Push Notification in Kotlin

我正在为我的聊天应用程序使用 Kotlin 导航组件架构,我正在使用 Firebase 消息服务来集成推送通知,我的要求是在我进行用户聊天时隐藏或禁用通知 screen.Please 让我知道,我怎样才能做到这一点。 这是我显示通知的代码

class MyFirebaseMessagingService : FirebaseMessagingService() {
 override fun onMessageReceived(remoteMessage: RemoteMessage?) {
     
        Log.d(TAG, "From: ${remoteMessage?.from}")

        remoteMessage?.data?.let {
            Log.d(TAG, "data payload: " + remoteMessage.data.toString())
            val params =remoteMessage.data.get("body")
            val objects = JSONObject(params)
            Log.e("JSON OBJECT", objects.toString())

            val title = remoteMessage.data.get("title").toString()

           sendNotification(messageBody,title, applicationContext)
} }

我的通知class是:

fun NotificationManager.sendNotification(messageBody: String, title: String, applicationContext: Context) {

    notificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

   
    // TODO: Step 1.12 create PendingIntent
    if(title.equals("Ride Request")) {
        fragmentId  = R.id.notificationFragment

    }
    else if(title.equals("Ride Accepted")) {
      fragmentId = R.id.inboxFragment
    }
    else if(title.equals("New Message")) {
        fragmentId = R.id.inboxFragment
    }

    // ---------- creating navgraph intent to open specific fragment ------------
    var contentPendingIntent = NavDeepLinkBuilder(applicationContext)
        .setComponentName(HomeActivity::class.java)
        .setGraph(R.navigation.home_bottom_navigation)
        .setDestination(fragmentId)
        .setArguments(bundle)
        .createPendingIntent()

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        notificationChannel = NotificationChannel(channel_id, description, 
        NotificationManager.IMPORTANCE_HIGH)
        notificationChannel.enableLights(true)
        notificationChannel.lightColor = R.color.colorPrimary
        notificationChannel.enableVibration(true)
        notificationManager.createNotificationChannel(notificationChannel)

        builder = NotificationCompat.Builder(applicationContext, channel_id)
            .setSmallIcon(R.drawable.icon_car)
            .setContentTitle(applicationContext.getString(R.string.app_name))
            .setContentText(messageBody)
            .setContentIntent(contentPendingIntent)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setAutoCancel(true)

    

    }else {

         builder = NotificationCompat.Builder(applicationContext, 
             applicationContext.getString(R.string.app_name))
            .setSmallIcon(R.drawable.icon_car)
            .setContentTitle(applicationContext.getString(R.string.app_name))
            .setContentText(messageBody)
            .setContentIntent(contentPendingIntent)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setAutoCancel(true)


    }

    notify(NOTIFICATION_ID, builder.build())
}

我不知道这是否完美,但你也可以试试

如果用户在聊天屏幕中,您可以创建一个 sharedPref 并将变量的值设置为 true(即用户在聊天屏幕中) 所以在 onMessageReceived() 中检查 sharedPref 的值是否为真(这意味着用户在聊天屏幕中) 如果为真则不发送通知如果为假则发送通知

设置sharedPref值 在该聊天的 onResume 中 activity 设置为 true 在 onPause 设置为 false

试试这个

class InboxFragment : Fragment() {

    companion object {
        var userId: String? = null
    }

    override fun onStart() {
        userId = navArgs.userId
    }

    override fun onStop() {
        userId = null
    }

}


class MyFirebaseMessagingService : FirebaseMessagingService() {

    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        ...
        if (InboxFragment.userId != remoteMessage.data.get("userId"))
            sendNotification(messageBody, title, applicationContext)
    }

}