I'm developing an android app that is mostly run in the background and uses Firebase Realtime Database for data syncing.
I want the app to play a 10 second sound when new data is received from Firebase and I've successfully managed to implement this, however, my solution doesn't work on all devices.
Here's my code:
class MyViewModel constructor(
) : ViewModel() {
private var mediaPlayer: MediaPlayer? = null
fun initRtdListener(context: Context) {
val ref = Firebase.database.getReference("my-path")
mediaPlayer = MediaPlayer.create(context, R.raw.my_short_audio)
ref.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
mediaPlayer?.start()
}
override fun onCancelled(error: DatabaseError) {}
})
}
}
This solution works perfectly on most devices even when the app is running in the background, however, on some devices (like Realme X) the sound is played only when the app is in foreground. What could be the problem? Is it because I play the sound not in the context of a service? If yes, do I really need a service considering that my sounds are short?
P.S. I have two background services which are working without any issues on all devices