在android中停止观察问题

时间:2011-05-06 06:16:46

标签: android

我用启动创建秒表,停止我使用它开始但不停止的代码。请帮我。 我的代码:

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);
    }
};

}

2 个答案:

答案 0 :(得分:0)

我认为您应该使用类级变量boolean shouldRun = true ; 在您的run()方法while中应该像这样使用

while(shouldRun)
{
 //implementation
}

并在b2.onClickListener()更改shouldRun = false;

修改 对于suspendresume,您可以在监听器中将shouldRun的值更改为shouldRun = true;以恢复按钮。请记住,当您stop更新时,您还应重置time。在suspend中,time应保持不变。

答案 1 :(得分:0)

我实施了用于解决时间测量的旋转拼图的秒表,我对它的看法有所不同。

  • 对于时间测量,我使用在DISPLAY_UPDATE_TIMEOUT之后触发的Handler对象。现在是时候更新显示的时间了。

为了开始计算我使用:

mLastStartTimestamp = System.currentTimeMillis();
mRepetitiveTimeoutHandler.postDelayed(processWatchTimer, DISPLAY_UPDATE_TIMEOUT);

并阻止它

mRepetitiveTimeoutHandler.removeCallbacks(processWatchTimer);
mStartStopElapsed = System.currentTimeMillis() - mLastStartTimestamp ;
updateTimeDisplay();    

在处理程序的每个触发器上,我执行以下操作:

private Runnable processWatchTimer = new Runnable()
{
    public void run() 
    {
        mRepetitiveTimeoutHandler.postDelayed(processWatchTimer, DISPLAY_UPDATE_TIMEOUT);
        updateTimeDisplay();            
    }
};