2011-05-06 78 views
0

我用[開始/暫停]和[重置]按鈕做簡單的秒錶。當我在暫停後按下開始按鈕時會出現問題。運行方法沒有調用。請幫幫我。 我的代碼是線程運行問題

public class StopWatch3 extends Activity implements Runnable{ 

// text view influenced by the Thread 
private TextView threadModifiedText; 
int time=0; 
Button b1,b2,b3; 
boolean shouldRun = false; 
/** 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); 
    Log.e("before",""+currentThread.getState()); 
    b1.setOnClickListener(new View.OnClickListener() 
    { 
     public void onClick(View view) 
     { 
      Log.e("stopw",(String) b1.getText()); 
      if(b1.getText().toString().equals("start")){ 
        if(currentThread.getState()==Thread.State.NEW){ 
         currentThread.start(); 
         Log.e("after",""+currentThread.getState()); 
         shouldRun = true; 
         b1.setText("pause"); 
        } 
        else{ 
         shouldRun = true; 
         b1.setText("pause"); 
        } 
      } 
      else if(b1.getText().toString().equals("pause")){ 
       shouldRun = false; 
       b1.setText("start"); 
      } 
     } 

    });  
    b2.setOnClickListener(new View.OnClickListener() 
    { 
     public void onClick(View view) 
     { 
      time=0; 
     } 

    });    
} 


@Override 
public void run(){ 
    try { 
     while(shouldRun){ 
      Thread.sleep(1000); 
      threadHandler.sendEmptyMessage(0); 
     } 
    } catch (InterruptedException e) { 
    } 
} 


private Handler threadHandler = new Handler() { 
    public void handleMessage(android.os.Message msg) { 
     time++; 
     threadModifiedText.setText(""+time); 
    } 
}; 

}

回答

0

我想你的線程只運行到結束的時候你設置shouldRun爲false。 只要程序運行,將while循環封閉到另一個while循環中即可。

1

無論如何,當它完成工作後,它就無法啓動線程,而且他的狀態也不再是新的了,您必須在這種情況下創建一個新線程。當然再次

else{ 
    shouldRun = true; 
    b1.setText("pause"); 
} 

而本代碼將使線程運行...

當你按下「開始」第二次,你達到這個部分