我在程序中创建了一个秒表 stopwatch,当然可以开始和停止。我用的以下的代码来实现这个功能。秒表可以开始,但是不能停止。
public class StopWatch2 extends Activity implements Runnable{
// text view influenced by the Thread
private TextView threadModifiedText;
int time=0;
Button b1,b2,b3;
/** Called when the activity is first created. */
Thread currentThread = new Thread(this);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stopwatch);
b1=(Button)findViewById(R.id.button1);
b2=(Button)findViewById(R.id.button2);
b3=(Button)findViewById(R.id.button3);
threadModifiedText = (TextView) findViewById(R.id.textView1);
b1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
currentThread.start();
}
});
b2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
currentThread.stop();
}
});
}
//Method you must override to control what the Thread is doing
@Override
public void run(){
try {
while(true){
currentThread.sleep(1000, 0);
threadHandler.sendEmptyMessage(0);
}
// signaling things to the outside world goes like this
} catch (InterruptedException e) {
}
}
private Handler threadHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
time++;
threadModifiedText.setText(""+time);
}
};
}
请求大家帮忙指出程序中的错误。谢谢!
你应该使用一个类变量boolean shouldRun = true ;
在你的run()方法中while
应该这样
while(shouldRun)
{
//implementation
}
在b2.onClickListener()
改成shouldRun = false;
while(true),你应该在按停止的时候跳出。
thread.stop方法jdk中强烈建议停用,如楼上所说,你可以在点button的时候设置一个flag,在while中判断此flag来退出while