How to make Android MediaPlayer () stop when the application is closed?

My Android app creates MediaPlayer () and plays the melody. I need it to stop playing when the user leaves the application. I also need to somehow press the volume buttons so that users can adjust the volume of the songs ... Any ideas?

MediaPlayer mp;

public void setupMediaPlayer()
{
    mp = MediaPlayer.create(context, R.raw.song);
    mp.setLooping(true);
    mp.start(); 
}

public void stopMediaPlayer()
{
    mp.stop();
}
+3
source share
3 answers

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

@Override
protected void onPause() {
    super.onPause();
    stopMediaPlayer();
}

In the second half: try taking a look at the AudioManager class (especially AUDIO_FOCUS_GAIN ) and see if it can handle what you're looking for.

, , ... , 90-, MIDI-, , , ...

+3

onResume(), , .

+1

stopMediaPlayer , eldarerathis, :

 @Override
protected void onPause() {
    super.onPause();
    releaseMediaPlayer();
}

, ...

:

, , this - .

, .:)

+1

Source: https://habr.com/ru/post/1765372/


All Articles