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 s开发者_运维技巧creen.
What is the best way to do this?
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.
You can use a service to do the same. It is the best way to tun background tasks
Here is a sample service
http://androidcore.com/android-programming-tutorials/638-how-to-use-android-services.html
You can try adding mediaplayer related code here
Implement onPause
and onResume
. These are called by Android when your activity is sent to the background and when it comes back to the foreground. Use onStop
to handle when your app is killed by Android and no longer visible or running.
精彩评论