Search code examples
androidandroid-activitymedia-player

How to make MediaPlayer play music only while my app is in foreground?


I have an app consisting of several activities. I'd like a background music to play continuously while user is navigating between them and stop is user goes to home screen/some other app/locks the screen.

What is the best way to do this?


Solution

  • I ended up stopping music after 500ms timeout after onPause if it is not resumed in an onResume of some other activity. If activity switch takes longer than 500ms, then it's perfectly reasonable that music should stop until the next activity loads. And when user presses home button, 500ms delay before stopping music is not noticeable.