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

You can use a service to do the same. It is the best way to tun background tasks Here is a sample service androidcore.com/android-programming-tuto... You can try adding mediaplayer related code here.

The main problem is how to make that service pause when app is in background and destroy when app is destroyed. – Shooshpanchick Feb 18 at 10:27 I am not sure if you can pause the player while pressing the home key. As you know Home Key event cannot be overridden for security constraints.

When pressing home android just puts your application on the background but still your tasks or services will run. If you have a dummy root activity that doesn't require the application to play music you can try adding android:finishOnTaskLaunch in your manifest to that root activity or you can try setting cleartop flag . – DeRagan Feb 18 at 12:18.

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.

This is what I ended up doing now, plus this: before transferring control to another activity of my app I raise a special flag "do not kill service on onPause" to avoid interrupting music. But in some cases (e.g. Config change) onCreate/onDestroy is called anyway and I can not intercept it to raise that flag. This is why I'm looking for a more general solution.

– Shooshpanchick Feb 18 at 11:21.

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.

Mediaplayer is made to play multimedia content because it brooks in from a network like the Internet, or from local storage on a hard drive or other resource.It is one type of software program that translate several audio and video codecs, covering many digital music and video formats. The creators of media players focus on providing superior user knowledge because of this, media players are specifically tailored toward the media type. Make Mediaplayer.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions