我知道如何启动音乐文件,但我不知道如何阻止它。这是我的主要活动:
public void button1 (View v){
Intent i = new Intent(MainActivity.this, CallActivity.class);
startActivity(i);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.music);
mp.setLooping(true);
mp.start();
}
答案 0 :(得分:2)
您的媒体播放器属于该方法的范围。在你的课堂上宣布它。
Class MediaDemo{
MediaPlayer mp=null;
mp = MediaPlayer.create(this, R.raw.music);
public void button1 (View v){
Intent i = new Intent(MainActivity.this, CallActivity.class);
startActivity(i);
mp.setLooping(true);
mp.start();
}
public void button2 (View v){
// your code goes here
mp.stop();
}
答案 1 :(得分:0)
将mp声明为该类中的全局并执行mp.stop();
答案 2 :(得分:0)
您需要使用两个按钮制作xml文件并将按钮ID设置为playButton和stopButton
现在使用以下代码..
public class MediaPlayerExample extends Activity implements OnClickListener {
Button playButton,stopButton;
MediaPlayer mp=null;
mp = MediaPlayer.create(this, R.raw.music);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout_xml_file);
playButton=(Button)findViewById(R.id.ShowDialog);
stopButton=(Button)findViewById(R.id.ShowToast);
playButton.setOnClickListener(this);
stopButton.setOnClickListener(this);
}
public void onClick(View v)
{
switch(v.getId())
{
case R.id.playButton: // your button should have this id in xml file
Intent i = new Intent(MainActivity.this, CallActivity.class);
startActivity(i);
mp.setLooping(true);
mp.start();
break;
case R.id.stopButton: //your button should have this id in xml file
mp.stop();
break;
}
}