今天看到了一個runOnUiThread()方法用來更新UI,覺得很神奇!!
方法一:handler機制不說了。
方法二:利用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.
如果當前線程是UI主線程,則直接執行Runnable的代碼;否則將Runnable post到UI線程的消息隊列。 --看代碼實現就知道了
Parameters
action the action to run on the UI thread
public final void runOnUiThread(Runnable action) { if (Thread.currentThread() != mUiThread) { mHandler.post(action);//將Runnable Post到消息隊列,由內部的mHandler來處理,實際上也是Handler的處理方式 } else { action.run();//已經在UI線程,直接運行。 } }
參考地址:
http://www.android100.org/html/201406/07/20384.html
http://blog.csdn.net/annkie/article/details/8496219