2014-06-26 80 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();