站內搜尋

2011/3/1

Android Tips 開發小技巧 - Activity.runOnUiThread

真的只能說,偷懶,的的確確是人類進步的原動力。
上一篇我們討論到有關於 Handler 和 UI thread 的關係,
這一次,我們介紹更簡單方便的小工具,讓你來更新你的 UI。


Handler 的確是很好用的東西,但有的時後,我們只是希望更新一下 UI 的畫面,其實做的事情非常單純,就像上一篇舉出來的例子一樣..
    
Handler mHandler = new Handler();     
       .     
       ....     
       .     
mHandler.post(new Runnable() {     
    public void run()     
    {     
        TextView textBox= (TextView)getViewById(R.id.textbox);     
        textBox.setText(R.string.login_failed);     
    }     
});     

只是為了很單純的事情,但卻使用了不少的程式碼。
當你的程式需要不斷大量的更新 UI 的時後,這種程式我相信應該會讓你感到不耐煩。

另外,有些時後你也不是非常確定這個程式段是否一定由非 UI thread 來呼叫,假設呼叫的是 UI thread,其實是不需要使用到 Handler的。而這些比較繁索的思考,卻往往浪費我們在開發程式的時間。

沒錯,Google 的工程師們「也許」也有相同的煩惱,於是,他們提供了一個非常方便的 API

Activity.runOnUiThread( Runnable action )

故名思意,引數所帶入的 action,將會保證在 UI thread 被執行,所以,上面的程式碼,我們可以更精簡的改寫為..
    
   // A instance of Activity     
       ....     
       .     
    runOnUiThread(new Runnable() {     
        public void run()     
        {     
            TextView textBox= (TextView)getViewById(R.id.textbox);     
            textBox.setText(R.string.login_failed);     
        }     
    });     

如此一來,所有的煩惱都消失了。

但,也許有的人會好奇,這個好用的 API 是否運用了什麼複雜的技術。
其實,說穿了真的不值一提,只不過是一個很簡單的偷懶 function 罷了呀!!!
      
// Reference from Activity.java       
/**       
* Runs the specified action on the UI thread. If the current thread is the UI       
* thread, then the action is executed immediately. If the current thread is       
* not the UI thread, the action is posted to the event queue of the UI thread.       
*       
* @param action the action to run on the UI thread       
*/       
public final void runOnUiThread(Runnable action) {       
    if (Thread.currentThread() != mUiThread) {       
        mHandler.post(action);       
    } else {       
        action.run();       
    }       
}

由上面的 Code,我們可以很簡單的發現,其實 Google 的工程師們,也只是運用了一個 member 來判斷是否為 UI thread。假設不是,還是要依靠 Handler 來完成接下來的工作。

所以說,江湖一點訣,說破不值錢呀!!!

沒有留言:

張貼留言

熱門文章