Search code examples
androidkotlinandroid-serviceandroid-mediaplayer

onPause alternative in android service?


I have a android project that requires music to be played in the background. I believe using a service would be the right thing for this so I set one up in the following way:

internal class Song : Service() {
    private var mediaPlayer: MediaPlayer? = null


    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
        mediaPlayer = MediaPlayer.create(this, R.raw.song1)
        mediaPlayer!!.isLooping = true // Set looping
        mediaPlayer!!.setVolume(100f, 100f)
    }

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        mediaPlayer!!.start()
        return startId
    }

    override fun onDestroy() {
        mediaPlayer!!.stop()
        mediaPlayer!!.release()
    }
}

I tested this and the music works perfectly between activities and has no errors. However when the user leaves the app running in the background (I believe its either suspended or minimized?), it still plays the music. I need the app to not play music while the app is suspended, however continue if the user re-opens it. After some googling, most answers are to do with using onPause() and onResume(). However these methods do not work in services.

So are there any alternatives? If so how can I apply them to my service?

If not, any ideas how I can program a workaround?

Thanks in advance, Joshu


Solution

  • How is your app setup? Is it one activity or multiple activites?

    If you don't want to play it in the background and it's a single activity, then don't use a service at all. Just play it in your Activity, and start/stop the music in onPause.

    If your app is multiple Activities and you want it to play in all activities without stopping/restarting, then a Service is still applicable. In that case, you'll want to start it with bindService rather than startService, so it's stopped as soon as the last Activity unbinds. Each Activity should bind it in onStart and unbind in onStop. This should keep it playing as you go between activites, but stop it when the app is minimized.

    See https://developer.android.com/guide/components/bound-services for an intro on bound services.