按下后退按钮时如何停止背景音乐?

时间:2014-01-05 13:08:31

标签: android

我有2项活动。两种不同的背景音乐。当我按下第一个活动上的按钮时,它将进入此活动并且音乐的更改顺利进行,但我想在按下后退按钮时停止背景音乐。我试过这个,但它强行关闭。还有其他办法吗?

public class Categories extends Activity{

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

    mp = MediaPlayer.create(Categories.this, R.raw.looney);
    mp.setLooping(true);         
    mp.start();

    Button cartoonButton = (Button) findViewById(R.id.cartoon);             
    cartoonButton.setOnClickListener(new View.OnClickListener() {           
        public void onClick(View v) {
            Intent launchCartoon = new Intent(Categories.this, Cartoon.class);
            startActivity(launchCartoon);   

        }
    }); 


    Button superButton = (Button) findViewById(R.id.hero);
    superButton.setOnClickListener(new View.OnClickListener() 
    {           
        public void onClick(View v) {
            Intent launchSuperheroes = new Intent(Categories.this, SuperHeroes.class);
            startActivity(launchSuperheroes);

        }
    });

    Button singerButton = (Button) findViewById(R.id.singer);
    singerButton.setOnClickListener(new View.OnClickListener() {            
        public void onClick(View v) {
            Intent launchSinger = new Intent(Categories.this, Singer.class);
            startActivity(launchSinger);

        }
    });

    Button famousButton = (Button) findViewById(R.id.famous);
    famousButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            Intent launchFamous = new Intent(Categories.this, Famous.class);
            startActivity(launchFamous);

        }
    });
}

@Override
protected void onResume() {
    super.onResume();
    mp.start();
}

@Override
protected void onPause() {
    super.onPause();
    if (mp != null) {
        mp.stop();
        mp.release();
        mp = null;
    }
}

}

1 个答案:

答案 0 :(得分:0)

您可以尝试以下代码:

@Override
 public void onBackPressed() {
      if (player.isPlaying()) {
            player.stop();
      }
      player.release();
      super.onBackPressed();
 }

希望这可以帮助你:)