除了發送消息以外,咱們還有如下幾種方法能夠在子線程中進行UI操做:java
public boolean post(Runnable action) { Handler handler; if (mAttachInfo != null) { handler = mAttachInfo.mHandler; } else { ViewRoot.getRunQueue().post(action); return true; } return handler.post(action); } public final boolean post(Runnable r) { return sendMessageDelayed(getPostMessage(r), 0); }
原來這裏仍是調用了sendMessageDelayed()方法去發送一條消息啊,而且還使用了getPostMessage()方法將Runnable對象轉換成了一條消息,咱們來看下這個方法的源碼:ide
private final Message getPostMessage(Runnable r) { Message m = Message.obtain(); m.callback = r; return m; }
在這個方法中將消息的callback字段的值指定爲傳入的Runnable對象。咦?這個callback字段看起來有些眼熟啊,喔!在Handler的dispatchMessage()方法中原來有作一個檢查,若是Message的callback等於null纔會去調用handleMessage()方法,不然就調用handleCallback()方法。那咱們快來看下handleCallback()方法中的代碼吧:post
private final void handleCallback(Message message) { message.callback.run(); }
很簡單,就是直接調用了一開始傳入的Runnable對象的run()方法。spa
所以在子線程中經過Handler的post()方法進行UI操做就能夠這麼寫:線程
public class MainActivity extends Activity { private Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); handler = new Handler(); new Thread(new Runnable() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { // 在這裏進行UI操做 } }); } }).start(); } }
雖然寫法上相差不少,可是原理是徹底同樣的,咱們在Runnable對象的run()方法裏更新UI,效果徹底等同於在handleMessage()方法中更新UI。code
public boolean post(Runnable action) { Handler handler; if (mAttachInfo != null) { handler = mAttachInfo.mHandler; } else { ViewRoot.getRunQueue().post(action); return true; } return handler.post(action); }
若是當前的線程不等於UI線程(主線程),就去調用Handler的post()方法,不然就直接調用Runnable對象的run()方法。對象
public final void runOnUiThread(Runnable action) { if (Thread.currentThread() != mUiThread) { mHandler.post(action); } else { action.run(); } }