I am making a chat app and I am trying to make message notification. I have a Firebase database that i store all my data (users, friends, messages). When user sends a message, app adds that message to firebase database ( path is "/notification/user_who_recived/user_who_send" ).
my problem is i cant make service that gets message in "/notification..../" path and makes notification based on message.
here is my test code that doesnt work:
package com.cagsak.chatapp
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.IBinder
import androidx.core.app.NotificationCompat
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.FirebaseDatabase
class background_service : Service(){
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
println("background_service: THREAD İS STARTED")
val uid = FirebaseAuth.getInstance().uid ?: stopSelf()
val ref = FirebaseDatabase.getInstance().getReference("/notifications/$uid")
ref.get()
.addOnSuccessListener { data_list ->
println("background_service: MESSAGE GETTING IS SUCCESSFUL")
data_list.children.forEach { child ->
val data = child.getValue(ChatMessage::class.java)
if (data != null) {
println("background_service: MESSAGE RECEIVER IS FOUND")
SendNotification(data, baseContext)
child.ref.removeValue().addOnSuccessListener {
println("background_service: MESSAGE DATA IS DELETED")
}
}
}
}
return START_STICKY
}
override fun onBind(intent: Intent?): IBinder? {
return null
}
private fun SendNotification(message: ChatMessage, context: Context) {
FirebaseDatabase.getInstance()
.getReference("/users").get()
.addOnSuccessListener { userlist ->
userlist.children.forEach { user_data ->
val user = user_data.getValue(User::class.java)
if (user != null && user.uid == message.fromId) {
val intent = Intent(context, ChatMessage::class.java)
intent.putExtra("USERKEY", user)
val pendingIntent: PendingIntent =
PendingIntent.getActivity(context, 0, intent, 0)
NotificationCompat.Builder(context, "MY_CHANEL_ID")
.setSmallIcon(R.drawable.small_logo)
.setContentTitle(message.fromId)
.setContentText(message.text)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.build()
}
}
}
}
}