2014-06-26 81 views
0

我寫了一些計時器。我想在單擊開始按鈕後在textview中顯示它。 我做了什麼。 每次我使用線程多次更新UI

timer = new Thread(new Runnable() { 
      @Override 
      public void run() { 

       while (!stopedButton) { 

        time = ""; 
        if (timerMinutes >= 60) { 
         timerMinutes = 0; 
         timerHours++; 
        } 

        if (timerHours < 10) 
         time = "0" + String.valueOf(timerHours) + ":"; 
        else 
         time = String.valueOf(timerHours) + ":"; 
        if (timerMinutes < 10) 
         time += "0" + String.valueOf(timerMinutes); 
        else 
         time += String.valueOf(timerMinutes); 
        runOnUiThread(new Runnable() { 
         public void run() { 
          if (!stopedButton) { 
           mTimeFromStartValue.setText(time); 
           timerMinutes++; 
          } else { 
           timerMinutes = 0; 
           timerHours = 0; 
          } 
         } 

        }); 
        Log.e(TAG, ""+timerHours); 
        Log.e(TAG, ""+timerMinutes); 
        Log.e(TAG, time); 
        try { 
         Thread.sleep(1 * 1000); 
        } catch (InterruptedException e) { 
         e.printStackTrace(); 
        } 
       } 

      } 
     }); 

所以它工作正常,但停車後,然後每一次啓動,並做了很多次後,我的計時器開始工作快。我儘量避免這種情況,我認爲我不需要每次都創建新的計時器。但我也需要在停止開始後有工作計時器。

我寫了一些像這樣的代碼:

if(timer.isAlive()){ 
     timer.resume(); 
    }else{ 
     timer.start(); 
    } 

但我得到這個異常:java.lang.IllegalThreadStateException: Thread already started

那麼如何解決這個問題?

+0

對於這種行爲在Android中推薦的方法是的TimerTask –

回答

0

您需要創建新的Thread實例才能啓動新線程。此外,您還需要使用interrupt()方法Thread類。

使用此代碼來完成你的主題:

@Override 
public void run() { 

    while (true) { 

     // Your code here 

     if(isInterrupted()){ 
      return; 
     } 
    } 

} 

使用此代碼被點擊停止按鈕時:

timer.interrupt(); 
timer.join();