只需要解釋一點(diǎn):為什么handler可以用于子線程更新UI
(1)當(dāng)UI線程創(chuàng)建的時(shí)候會(huì)執(zhí)行ActivityThread的main方法:
Looper.prepareMainLooper()
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
//每個(gè)線程只允許有一個(gè)Looper,所以當(dāng)該線程的Looper存在時(shí),報(bào)異常
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
我們看看prepare()方法做了什么
private static void prepare(boolean quitAllowed) {
//sThreadLocal 是一個(gè)ThreadLocal類(lèi)型的實(shí)例,這個(gè)類(lèi)的作用簡(jiǎn)單說(shuō)就是為每個(gè)線程提供某個(gè)變量的副本來(lái)保證線程安全,以后會(huì)詳細(xì)說(shuō)
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
以上兩步做一個(gè)總結(jié),UI線程在初始化的時(shí)候會(huì)實(shí)例化一個(gè)Looper對(duì)象和一個(gè)MessageQueue對(duì)象,注意:一個(gè)線程只有一個(gè)looper實(shí)例,只有一個(gè)MessageQueue實(shí)例.
(2)ActivityThread中的另外一個(gè)方法:loop()
//不需要每行都看
public static void loop() {
//myLooper()返回的就是當(dāng)前線程的looper對(duì)象
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
//獲取當(dāng)前線程的MessageQueue對(duì)象
final MessageQueue queue = me.mQueue;
// Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
//開(kāi)啟無(wú)線循環(huán)去取消息
for (;;) {
//這里可能發(fā)生阻塞,為什么會(huì)阻塞?因?yàn)閝ueue有可能取不出消息,因此就會(huì)等待消息
Message msg = queue.next();
//當(dāng)取出的消息為空,退出循環(huán).什么時(shí)候?yàn)榭?需要看next源碼,到這里我們看看next()方法做了什么
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
// This must be in a local variable, in case a UI event sets the logger
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
final long traceTag = me.mTraceTag;
if (traceTag != 0) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
//這里是關(guān)鍵點(diǎn),取出消息來(lái)以后,把消息交給它的target對(duì)象去處理,target是誰(shuí),一會(huì)揭曉答案
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
// Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
...
msg.recycleUnchecked();
}
}
我們看看MessageQueue的next()方法做了什么
//只需要看中文注釋的地方
Message next() {
//這個(gè)mPtr決定了是否返回null,返回null的話(huà)則looper的loop()方法就會(huì)退出,也就是不會(huì)再處理消息
//used by native code 這個(gè)是這個(gè)字段的解釋,也就是說(shuō)這個(gè)字段由native方法控制
//當(dāng)我們調(diào)用looper的quit()或者quitSafely()方法的時(shí)候,這個(gè)字段的值就會(huì)被賦值為0
//quit()指的是立即退出消息循環(huán),不管MessageQueue里面還有沒(méi)有待處理的消息
//quitSafely()是等MessageQueue里面的消息處理完成后再退出
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
//開(kāi)啟無(wú)限循環(huán)去取消息,不用深究
for (;;) {
...
}
(3)通過(guò)looper的loop()方法,我們知道最終處理消息的是msg的target對(duì)象,下面我們來(lái)看看這個(gè)target是什么
我們?cè)谑褂胔andler的時(shí)候,會(huì)使用這個(gè)方法:
handler.sendMessage(msg);
我們看看這個(gè)方法做了什么:
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
接著看:
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) {
//這個(gè)消息隊(duì)列,就是當(dāng)前線程的唯一消息隊(duì)列,就是在創(chuàng)建looper的時(shí)候創(chuàng)建的那個(gè)唯一的MessageQueue,handler在哪個(gè)線程創(chuàng)建,這個(gè)MessageQueue就是哪個(gè)線程的
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);
}
接著看:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
//這個(gè)就是關(guān)鍵點(diǎn)!target對(duì)象就是handler本身,也就是說(shuō)這個(gè)msg是誰(shuí)發(fā)出的,最終由誰(shuí)的dispatchMessage()方法處理!!!
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
//這個(gè)方法就是把消息加入到MessageQueue的消息隊(duì)列里面,本著先進(jìn)先出的原則,先加入到隊(duì)列的消息優(yōu)先處理
return queue.enqueueMessage(msg, uptimeMillis);
}
(4)從上面看出方法的最終執(zhí)行者是我們創(chuàng)建的handler的dispatchMessage()方法:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
//當(dāng)使用handler.post(Runnable r)這個(gè)方法的時(shí)候會(huì)執(zhí)行這個(gè)方法,這個(gè)方法說(shuō)到底就是執(zhí)行r中的run()方法
handleCallback(msg);
} else {
//看到handleMessage()方法可能會(huì)更加熟悉,因?yàn)槲覀冊(cè)趧?chuàng)建handler的時(shí)候會(huì)重寫(xiě)這個(gè)方法,也就是最終調(diào)用的是我們重寫(xiě)的方法
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
(5)handler不僅可以用來(lái)更新ui,我們還可以在子線程創(chuàng)建handler,然后在其他線程使用這個(gè)handl實(shí)例發(fā)送消息,在子線程處理相應(yīng)的邏輯,注意我們需要手動(dòng)Looper.prepare().
new Thread(){
@Override
public void run() {
Looper.prepare();
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
super.run();
}
}.start();