title: Keep sound playing within the App but stop it when App goes to the background
body: <p>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:</p>
  
  <pre><code>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()
      }
  }
  </code></pre>
  
  <p>EDIT:</p>
  
  <p>I tried to implement <a href="https://stackoverflow.com/a/54433734/10858057">this answer</a>, but had to translate it to kotlin. I think I did everything right, but I get an <code>unresolved reference: mediaPlayer</code> in the Lifecycleobserver.</p>
  
  <p>Here´s the Observer:</p>
  
  <pre><code>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()
  }
  }
  </code></pre>
  
  <p>And here are the relevant parts of MainActivity</p>
  
  <pre><code>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()
      }
  </code></pre>
  
  <p>Any idea what I am missing here?</p>