Here is an issue I am facing when using a service in an Android app to play audio in the background.
The audio plays as expected in the background, and the app has a stop button that should be used to stop the audio play when the app comes back to the foreground. And this button is not working.
I use a class instance variable serviceIntent like this:
class MainActivity : AppCompatActivity() {
.....
private var serviceIntent:Intent? = null
.....
}
Here is how the service is started from the onStop() method of the main activity.
override fun onStop() {
super.onStop()
.....
serviceIntent = Intent(this, AudioService::class.java)
serviceIntent?.let {
it.putExtra("audioPath", audioPath)
it.putExtra("timePosit", playTimeStamp.toString())
it.putExtra("playMode", playMode)
.....
startForegroundService(it)
}
}
And here is how I try to stop the service when the stop button is tapped (but this is not working): (The two first lines are obviously only for debugging)
stopBtn.setOnClickListener {
if (serviceIntent == null) println("There is no +++serviceIntent+++")
else println("Trying to stop +++serviceIntent+++")
serviceIntent?.let {stopService(it)}
}
I can see the message: "Trying to stop +++serviceIntent+++" indicating that serviceIntent is not null, but the audio playing does not stop.
Any relevant feedback by some more experienced user will be much appreciated.