Fixpoint
Fixpoint

Reputation: 9870

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?

Upvotes: 3

Views: 2969

Answers (3)

Fixpoint
Fixpoint

Reputation: 9870

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.

Upvotes: 1

RivieraKid
RivieraKid

Reputation: 5961

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.

Upvotes: 0

DeRagan
DeRagan

Reputation: 22930

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

Upvotes: 0

Related Questions