前面分析过handler相关的类handler源码分析,post方法实际上也是发送message,下面看看源码实现。
Handler.post()
public final boolean post(Runnable r){
return sendMessageDelayed(getPostMessage(r), 0);
}
public final boolean postDelayed(Runnable r, long delayMillis){
return sendMessageDelayed(getPostMessage(r), delayMillis);
}
//将传过来的Runnable赋值给message.callback,
//实际上就是发送一个带有Runnable的消息。
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
两个方法都调用sendMessageDelayed()
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
继续跟
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
MessageQueue queue = mQueue;
if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
return false;
}
return enqueueMessage(queue, msg, uptimeMillis);
}
接下来就是MessageQueue.enqueueMessage(),前面分析过发送message流程,这里不细说。最终Looper获取到消息调用Handler.dispatchMessage()完成回调。
Handler.dispatchMessage()
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
msg.callback不为空,会走handleCallback(msg)
private static void handleCallback(Message message) {
message.callback.run();
}
handler接收到消息后回调Runnable.run()。也就是说通过主线程初始化的handler,调用post()发送消息,Runnable.run()最终会回调在主线程。
子线程中经常会用runOnUiThread()更新ui,Activity.runOnUiThread()。
final Handler mHandler = new Handler();
...
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
mHandler是activity的成员变量,初始化在ui线程。runOnUiThread()也是调用Handler.post()发送带有Runnable的消息切换到ui线程。
网友评论