Search code examples
androidbuttonandroid-intentandroid-activitymedia-player

How to stop a Mediaplayer when i press Home, BUT not in an other activity


first, sorry for my bad English With my code, I can stop the Mediaplayer when the home button is pressed, but I also stop it when I "open" an other activity. Then, i just want to know if i can stop the Mediaplayer ( mpFond in my code ) when I press Home button, but not when I open an other activity.

Here's my code:

private MediaPlayer mpFond;

public void onCreate(Bundle savedInstanceState) {
//some code

        mpFond = MediaPlayer.create(AccueilActivity.this,R.raw.accueil);    
        mpFond.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mpFond.setLooping(true);
        mpFond.start();

        // "definition" des boutons
    Button play = (Button) findViewById(R.id.play);

    //some code

    play.setOnClickListener(new View.OnClickListener() { // LE BOUTON JOUER

        @Override
        public void onClick(View v) {
            AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
            //Lorsqu'on clique sur "JOUER" 
            mp = MediaPlayer.create(AccueilActivity.this,R.raw.bruit);
            mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
            //if silent mode
            switch (am.getRingerMode()) {
            case AudioManager.RINGER_MODE_SILENT:
                mp.setVolume(0,0);
                break;
            }
            //demarrage du son
            mp.start();

            Intent intent = new Intent(app, MainActivity.class);
            startActivity(intent);
        }

    });
//some code
}

//some code

@Override
public void onPause()
{
   super.onPause();
   if(mpFond.isPlaying()){
   mpFond.pause();
   }

}

@Override
public void onStop()
{
   super.onStop();
  if(mpFond.isPlaying()){
    mpFond.stop();
  }
}

Solution

  • Everything is ok now. Just found the way to do that :

    @Override
    public void onPause()
    {
       super.onPause();
       if(mpFond.isPlaying()this.isFinishing()){
       mpFond.pause();
    }
    
    }
    
     @Override
    public void onStop()
    {
       super.onStop();
      if(this.isFinishing(){
        mpFond.stop();
      }
    }