Search code examples
androidaudiokotlinandroid-mediaplayerandroid-lifecycle

Keep sound playing within the App but stop it when App goes to the background


So I have a Sound I want to play continuously throughout the whole of my App. But as soon as the App goes to background, the sound should stop. I´m trying to do this during onStop(). The problem is that onStop() is called every time the activity is stopped, regardless of whether I stay within the app or not. Is there a way to differentiate between those cases? Something like this:

override fun onStop() {
    if [App is left but not destroyed] {
        super.onStop()
        mediaLength = mediaPlayer.currentPosition
        mediaPlayer.pause()
    }
    else { //i.e. activity is left but the new activity is from the same app.
        super.onStop()
    }
}

EDIT:

I tried to implement this answer, but had to translate it to kotlin. I think I did everything right, but I get an unresolved reference: mediaPlayer in the Lifecycleobserver.

Here´s the Observer:

package com.example.asdasd.soulfetch

import android.app.Application
import android.arch.lifecycle.Lifecycle
import android.arch.lifecycle.LifecycleObserver
import android.arch.lifecycle.OnLifecycleEvent
import android.arch.lifecycle.ProcessLifecycleOwner


class CheckLifeCycle: Application(), LifecycleObserver {
override fun onCreate() {
    super.onCreate()
    ProcessLifecycleOwner.get().getLifecycle().addObserver(this)
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onAppBackground() {
    MainActivity.mediaPlayer.pause()
}
}

And here are the relevant parts of MainActivity

class MainActivity : AppCompatActivity() {

lateinit var mediaPlayer: MediaPlayer

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    mediaPlayer = MediaPlayer()

    fun playBordun() {
        mediaPlayer = MediaPlayer.create(this, R.raw.cbordun)
        mediaPlayer.isLooping = true
        mediaPlayer.start()
        }
    playBordun()
    }
override fun onDestroy() {
    super.onDestroy()
    mediaPlayer.stop()
    mediaPlayer.reset()
    mediaPlayer.release()
    }

Any idea what I am missing here?


Solution

  • You can't gain such functionality using activity. Activity is highly prone to be destroyed, recreated. You should use Service to attain such functionality, as the service will persist, whether your activity is destroyed or not.

    This article is old and out of date, but can still learn using service with music from it