Question

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

Was it helpful?

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;
}

OTHER TIPS

Override the onPause method of the activity and call stop on the MediaPlayer.

Check out what you want to do on onPause. Example:

protected void onPause() {
     super.onPause();

     ourSong.stop();
 }

You have to override onKeyDown() method and check the keyevent if it is home key or back button methong, and inside this method stop your media player object then release it. mp.stop(); mp.release();

you should probably put

if (player != null && player.isPlaying()) {
    player.stop();
    player.release();
    player = null;
}

inside your onStop(), or onDestroy() method of your activity also.

If you put it in onStop() the audio would stop when the home button is pressed(or anytime another activity takes over phone rings perhaps).

If you put it in onDestroy() it would keep playing until the system needs the resources that your application is using. Either way it is a good idea so that your app is not holding on the the MediaPlayer resources incase the user doesn't hit the stop button for whatever reason.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top