我有这三个类,即MainActivity,Options和Play。当用户单击“选项”按钮时,用户可以决定他/她是否想要播放音频。但默认情况下,虽然用户不会点击选项上的按钮,但音频仍会播放。
我在StackOverflow中找到了一些代码,但如果用户决定在决定播放音频后决定停止音频,我不知道如何停止音频。 (再次转到选项)
到目前为止,这是代码:
MainActivity.class (选项)
public class MainActivity extends Activity {
public MediaPlayer mp = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent a = new Intent(MainActivity.this, Play.class);
startActivity(a);
}
});
}
}
Play.java
public class Play extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
Button back = (Button) findViewById (R.id.button1);
back.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent menu = new Intent (getApplicationContext(), Menu.class);
startActivity(menu);
}
});
MainActivity z = new MainActivity();
MediaPlayer mp = z.mp;
if (mp == null) {
mp = MediaPlayer.create(Play.this, R.raw.math_game);
mp.start();
}
else if (mp.isPlaying()) {
mp.stop();
mp = null;
}
}
}
和主菜单
public class Menu extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
Button play, opt;
play = (Button) findViewById (R.id.play);
opt = (Button) findViewById (R.id.opt);
play.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent play = new Intent (Menu.this, Play.class);
startActivity(play);
}
});
opt.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent play = new Intent (Menu.this, MainActivity.class);
startActivity(play);
}
});
}
}
谢谢你:))
答案 0 :(得分:1)
查看Android活动生命周期(http://developer.android.com/training/basics/activity-lifecycle/index.html),您会发现有更多活动覆盖..即onPause,onResume,onStop和onDestroy。我想你会想要在播放活动的onPause中停止音乐。