tylercomp tylercomp - 2 months ago 4
Android Question

How to get Android MediaPlayer() to stop when app is closed?

My android app creates a MediaPlayer() and plays a looping song. I need to have it stop playing when the user leaves the app. I also need to get at the volume buttons somehow, to let users adjust the songs volume... Any Ideas?

MediaPlayer mp;

public void setupMediaPlayer()
mp = MediaPlayer.create(context, R.raw.song);

public void stopMediaPlayer()


Per the first half of your question: you should get what you want if you call stopMediaPlayer() inside onPause() and onDestroy(). Example:

protected void onPause() {

Per the second half: Try taking a look at the AudioManager class (particularly AUDIO_FOCUS_GAIN), and see if that can handle what you're looking for.

Make sure the looping audio makes sense in the context of the app, though...if there's one thing I don't miss from the amateur websites of the mid-90's it's that awful MIDI background music that everyone seemed to put in them...