Android 更新UI的兩種方法——handler和runOnUiThread()

今天看到了一個runOnUiThread()方法用來更新UI,以爲很神奇!!html

方法一:handler機制不說了。java

方法二:利用Activity.runOnUiThread(Runnable)把更新ui的代碼建立在Runnable中,而後在須要更新ui時,把這個Runnable對象傳給Activity.runOnUiThread(Runnable)。 這樣Runnable對像就能在ui程序中被調用。若是當前線程是UI線程,那麼行動是當即執行。若是當前線程不是UI線程,操做是發佈到事件隊列的UI線程
 
FusionField.currentActivity.runOnUiThread(new Runnable()    
        {    
            public void run()    
            {    
                Toast.makeText(getApplicationContext(), , "Update My UI",    
                        Toast.LENGTH_LONG).show();    
            }    
    
        });  

public final void runOnUiThread (Runnable action)

Added in  API level 1

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.android

若是當前線程是UI主線程,則直接執行Runnable的代碼;不然將Runnable post到UI線程的消息隊列。  --看代碼實現就知道了api

Parameters

action   the action to run on the UI threadide

public final void runOnUiThread(Runnable action) {  
       if (Thread.currentThread() != mUiThread) {  
           mHandler.post(action);//將Runnable Post到消息隊列,由內部的mHandler來處理,實際上也是Handler的處理方式  
       } else {  
           action.run();//已經在UI線程,直接運行。  
       }  
   }  

 

參考地址:post

http://www.android100.org/html/201406/07/20384.htmlui

http://blog.csdn.net/annkie/article/details/8496219spa

相關文章
相關標籤/搜索