2012-09-17 12 views
0

我試圖每隔3秒週期運行一段代碼,這可以更改按鈕的顏色。問題運行代碼定期更新UI上的按鈕顏色

到目前爲止,我有:

ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(2); 

// This schedule a runnable task every 2 minutes 
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() { 
    public void run() { 

     queryFeedback2(); // display the data 
    } 
}, 0, 3, TimeUnit.SECONDS); 

該代碼將運行一段代碼,但不會對結果更新我的UI。

首先,什麼樣的代碼是導致我的UI更新的問題?

其次,這是我應定期運行我的代碼的方式嗎?有沒有更好的辦法?

回答

0

是的,有幾個選項可用。

  1. 螺紋
  2. Runnable接口
  3. 的TimerTask

their answer here規定由alex2k8:

final Runnable r = new Runnable() 
{ 
    public void run() 
    { 
     tv.append("Hello World"); 
     handler.postDelayed(this, 1000); 
    } 
}; 

handler.postDelayed(r, 1000); 

或者我們可以使用正常的線程,例如(與原亞軍) :

Thread thread = new Thread() 
{ 
    @Override 
    public void run() { 
     try { 
      while(true) { 
       sleep(1000); 
       handler.post(r); 
      } 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
    } 
}; 

thread.start(); 

您可以考慮您的Runnable對象,就像一個命令,可以 發送到要執行的消息隊列中,處理器只是一個幫手用於發送命令 對象。

更多細節在這裏 http://developer.android.com/reference/android/os/Handler.html

您可以從 處理程序更新UI。教程使用的處理程序,線程是上面提到的選項之間可用here.

選擇確實是基於你需要什麼樣的功能。如果你只需要在幾個時間間隔內做點什麼,那麼上面的任何一個都應該沒問題。

+0

正確。您必須爲此使用處理程序。 –