我正在尝试使自动化仪器播放,但坚持停止可运行的循环。这是我的完整代码 MainActivity.java 。
public class MainActivity extends Activity implements OnClickListener{
Button bt1,bt2;
Handler handler;
Runnable runnable;
MediaPlayer mp;
int i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt1 = (Button)findViewById(R.id.button1);
bt2 = (Button)findViewById(R.id.button2);
bt1.setOnClickListener(this);
bt2.setOnClickListener(this);
mp = MediaPlayer.create(MainActivity.this, R.raw.sound);
}
void playInstrument(){
if(mp.isPlaying()){
mp.release();
}
mp = MediaPlayer.create(MainActivity.this, R.raw.sound);
mp.start();
}
void play(){
i=0;
handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
i++;
System.out.println(i);
if(i==3){
System.out.println("Finish Playing");
MainActivity.this.handler.removeCallbacks(MainActivity.this.runnable);
}
playInstrument();
handler.postDelayed(this, 1000);
}
};
runnable.run();
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.button1:
play();
break;
case R.id.button2:
handler.removeCallbacks(runnable);
break;
}
}
}
这是xml activity_main.xml :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="43dp"
android:text="Start" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/button1"
android:layout_marginTop="36dp"
android:text="Stop" />
</RelativeLayout>
我可以通过使用button1点击停止它,但是如果i值已经为3,为什么它不会自动停止?它显示Log Cat上的完成播放,但保持循环。也许这只是我不理解的javaish问题
答案 0 :(得分:0)
if(i==3){
System.out.println("Finish Playing");
MainActivity.this.handler.removeCallbacks(MainActivity.this.runnable);
return;
}
否则你会再次发布;