簡體   English   中英

在 Kotlin 中處理推送通知

[英]Handle Push Notification in Kotlin

我正在為我的聊天應用程序使用 Kotlin 導航組件架構,並且我正在使用 Firebase 消息服務來集成推送通知,我的要求是當我在用戶聊天屏幕上時隱藏或禁用通知。請告訴我,我該如何實現這個。 這是我顯示通知的代碼

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)
} }

我的通知類是:

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 的值是否為 true(這意味着用戶是在聊天屏幕中)如果為真,則不發送通知,如果為假則不發送通知

設置 sharedPref 值 在該聊天活動的 onResume 中設置為 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)
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM