2014-01-15 23 views
0

我正在嘗試構建一個計時器,它以秒爲單位進行倒計時,並且每次更新一個TextView以顯示剩餘時間。從我可以告訴計時器代碼工作正常(事件之間1秒,並從小時和分鐘轉換爲秒罰款),因爲我測試了它在Android以外,並在Android中使用Log.d()。更新textview是什麼給我的問題。當最初嘗試更新textview時,我得到了空指針,導致只有UI線程可以訪問UI(我對錯誤消息的解釋),並添加了允許訪問和更新它的runOnUiThread(),但它現在不能正確更新。我認爲這是問題所在,但我不完全確定,並且不知道如何解決問題或想出更好的方法來解決問題。我會欣賞另一雙眼睛。由於在android中創建計時器的問題

final static int delay = 1000; 
final static int period = 1000; 


public void start(int hin, int min) { 
     run = true; 
     int hrinsec = (hin * (60 * 60)); 
     int mininsec = (min * 60); 
     secs = hrinsec + mininsec; 
     run = false; 
     interval = secs; 
     Timer t = new Timer(); 
     t.scheduleAtFixedRate(new TimerTask() { 
      public void run() { 
       // Convert seconds back to hrs and mins 
       hrsFromSecs(secs); 
       minsFromSecs(secs); 
       secsFromSecs(secs); 
       dint total = hours + minutes + seconds; 
       output = hours + " Hours " + minutes + " Minutes " + seconds 
         + " Seconds"; 
//    Countdown and update the textview 
       runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         timer.setText(output); 
       }}); 

        secs = secs - 1; 
        checkIfDone(total); 
      } 
     }, delay, period); 
    } 
+0

您應該使用的AsyncTask定時任務。不要在UI線程中運行。 – ChuongPham

回答