Search code examples
androidbackgroundmedia-playerplaying

I want to stop mediaplayer when home button is pressed


When I am out of my app (when pressed home button or back button), the music keeps playing in the background. How can I stop it?

public class MainActivity extends Activity implements OnClickListener {

MediaPlayer ourSong;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ourSong = MediaPlayer.create(MainActivity.this, R.raw.girissong);
    ourSong.start();

    // codes

}

@Override
public void onClick(View v) {

    // some code

         }

         }

}

I made this code and it should stop when I go to next class and the next song will start


Solution

  • Place the below two methods in you class for stopping the Music play while navigating to other Screens and Home button respectively....

    @Override
    public void onPause()
    {
       super.onPause();
       if(ourSong.isPlaying())
       ourSong.stop();
       else
       return;
    }
    
    @Override
    public void onStop()
    {
       super.onStop();
      if(ourSong.isPlaying())
        ourSong.stop();
      else
       return;
    }