firebase push notification android kotlin appears on the sender device

46 Views Asked by At

In android kotlin chat app I am using firebase FCM to send notification to the receiver device, how ever when button send is clicked the app sends the notification to both devices: receiver and sender. this is the function I use to send Notification:

private fun sendNotification(notification: PushNotification) =
    CoroutineScope(Dispatchers.IO).launch {
        try {
            RetrofitInstance.api.postNotification(notification)
        } catch (e: Exception) {
            Toast.makeText(this@MessagingActivity, e.message, Toast.LENGTH_SHORT).show()
        }
    }
private fun sendNotificationToReceiver(otherUserId: String, message: Message) {
    // Retrieve sender's user name
    val senderUserReference =              
    FirebaseDatabase.getInstance().getReference("Users").child(message.senderId!!)
    senderUserReference.addListenerForSingleValueEvent(object : ValueEventListener {
        override fun onDataChange(senderDataSnapshot: DataSnapshot) {
            val senderUser = senderDataSnapshot.getValue(User::class.java)
            if (senderUser != null) {
                val senderUserName = senderUser.userName

                // Use senderUserName as the title for the notification
                val notificationData = NotificationData(senderUserName, message.messageText!!)
                val receiverTopic = "/topics/user_$otherUserId"
                PushNotification(notificationData, receiverTopic).also {
                    FirebaseMessaging.getInstance().subscribeToTopic(receiverTopic)
                    sendNotification(it)
                }
            } else {
                // Handle the case where senderUser is null
                Log.e("MessagingActivity", "Sender user data is null")
            }
        }

        override fun onCancelled(databaseError: DatabaseError) {
            // Handle error
            Log.e("MessagingActivity", "DatabaseError: ${databaseError.message}")
        }
    })
}
0

There are 0 best solutions below