Looper負(fù)責(zé)創(chuàng)建一個(gè)MessageQueue,然后進(jìn)入一個(gè)無(wú)限循環(huán)體不斷從該MessageQueue中讀取消息,而消息的創(chuàng)建者就是一個(gè)或多個(gè)Handler 。
-
Looper , Handler , Message關(guān)系圖解
Looper()
Looper在線程中通常是這么用的
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
調(diào)用了 Looper.prepare() 接著調(diào)用了Looper.loop();先來(lái)看看Lopper 中的主要成員變量:
// sThreadLocal.get() will return null unless you've called prepare().
//在prepare 的時(shí)候 set 的值
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
private static Looper sMainLooper; // guarded by Looper.class
//消息隊(duì)列
final MessageQueue mQueue;
final Thread mThread;
ThreadLocal類為每一個(gè)線程都維護(hù)了自己獨(dú)有的變量拷貝。每個(gè)線程都擁有了自己獨(dú)立的一個(gè)變量,競(jìng)爭(zhēng)條件被徹底消除了,那就沒(méi)有任何必要對(duì)這些線程進(jìn)行同步,它們也能最大限度的由CPU調(diào)度,并發(fā)執(zhí)行。并且由于每個(gè)線程在訪問(wèn)該變量時(shí),讀取和修改的,都是自己獨(dú)有的那一份變量拷貝,變量被徹底封閉在每個(gè)訪問(wèn)的線程中,并發(fā)錯(cuò)誤出現(xiàn)的可能也完全消除了。對(duì)比前一種方案,這是一種以空間來(lái)?yè)Q取線程安全性的策略。具體可參看這里
prepare()
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
prepare 比較簡(jiǎn)單,只是初始化了 sThreadLocal的值。一個(gè) Looper 只能有一個(gè) ThreadLoacl 對(duì)象,當(dāng)sThreadLocal.get() != null拋出異常
ThreadLocal對(duì)象保證每個(gè)線程中的 Looper 實(shí)例互不相同
一句話概括 prepare(),對(duì)于每個(gè) thread 準(zhǔn)備一個(gè) Looper 變量,并保證每個(gè)Looper在每個(gè)線程中獨(dú)一無(wú)二
loop()
public static void loop() {
//這里得到的 Looper,就是prepare 中 set 的,一個(gè)線程對(duì)應(yīng)一個(gè) Looper
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
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();
//循環(huán)從 MessageQueue 取出消息執(zhí)行,MessageQueue在 Looper 的構(gòu)造函數(shù)中被創(chuàng)建
for (;;) {
Message msg = queue.next(); // 如果沒(méi)有消息則阻塞。
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
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
//MessageQueue中 取出的 msg,交給target.dispatchMessage 處理
msg.target.dispatchMessage(msg);
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();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed from 0x"
+ Long.toHexString(ident) + " to 0x"
+ Long.toHexString(newIdent) + " while dispatching to "
+ msg.target.getClass().getName() + " "
+ msg.callback + " what=" + msg.what);
}
msg.recycle();
}
}
mylooper()
public static Looper myLooper() {
return sThreadLocal.get();
}
直接返回ThreadLocal中存儲(chǔ)的 Looper 變量。
然后取出 looper 中的 Queue,并且循環(huán)取出隊(duì)列中的 message,交給msg.target.dispatchMessage(msg);處理.
target 是 handler 后面會(huì)講到
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
//post 的回調(diào)
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
handleMessage(msg)是一個(gè)空方法,我們?cè)趧?chuàng)建 handler 實(shí)例時(shí),復(fù)寫這個(gè)方法。然后根據(jù)msg.what進(jìn)行消息處理
Handler
public Handler(Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
final Class<? extends Handler> klass = getClass();
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
(klass.getModifiers() & Modifier.STATIC) == 0) {
Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
klass.getCanonicalName());
}
}
//通過(guò)Looper.myLooper()獲取了當(dāng)前線程保存的Looper實(shí)例,
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
// 獲取了這個(gè)Looper實(shí)例中保存的MessageQueue(消息隊(duì)列),這樣就保證了handler的實(shí)例與我們Looper實(shí)例中MessageQueue關(guān)聯(lián)上了。
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
同樣,通過(guò)Looper.myLooper()獲取當(dāng)前線程中的 Looper 對(duì)象,并且得到其中的 Queue
所有 sendMessage、sendMessageDelayed、sendEmptyMessageDelayed等,最終都調(diào)用
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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
//Looper的loop方法會(huì)取出每個(gè)msg然后交給msg,target.dispatchMessage(msg)去處理消息
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
最終會(huì)將msg 加入到 queue 的隊(duì)列中
post
mHandler.post(new Runnable()
{
@Override
public void run()
{
//do something 在 handler 線程
}
});
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
在getPostMessage中,得到了一個(gè)Message對(duì)象,然后將我們創(chuàng)建的Runable對(duì)象作為callback屬性,賦值給了此message.最終還是會(huì)調(diào)用enqueueMessage.
產(chǎn)生一個(gè)Message對(duì)象,可以new ,也可以使用Message.obtain()方法;兩者都可以,但是更建議使用obtain方法,因?yàn)镸essage內(nèi)部維護(hù)了一個(gè)Message池用于Message的復(fù)用,避免使用new 重新分配內(nèi)存。
在 dispathMessage 的過(guò)程中
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
在getPostMessage中,將post 中的Runnable賦值給了Message.callback
所以,會(huì)執(zhí)行handleCallback(msg)
private static void handleCallback(Message message) {
message.callback.run();
}
即執(zhí)行 Post 中的Runnable.
其實(shí)這個(gè)Runnable并沒(méi)有創(chuàng)建什么線程,而是發(fā)送了一條消息
MessageQueue
boolean enqueueMessage(Message msg, long when) {
if (msg.isInUse()) {
throw new AndroidRuntimeException(msg + " This message is already in use.");
}
if (msg.target == null) {
throw new AndroidRuntimeException("Message must have a target.");
}
synchronized (this) {
if (mQuitting) {
RuntimeException e = new RuntimeException(
msg.target + " sending message to a Handler on a dead thread");
Log.w("MessageQueue", e.getMessage(), e);
return false;
}
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// Inserted within the middle of the queue. Usually we don't have to wake
// up the event queue unless there is a barrier at the head of the queue
// and the message is the earliest asynchronous message in the queue.
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
總結(jié)
到此,這個(gè)流程已經(jīng)解釋完畢,讓我們首先總結(jié)一下
- 首先Looper.prepare()在本線程中保存一個(gè)Looper實(shí)例,然后該實(shí)例中保存一個(gè)MessageQueue對(duì)象;因?yàn)長(zhǎng)ooper.prepare()在一個(gè)線程中只能調(diào)用一次,所以MessageQueue在一個(gè)線程中只會(huì)存在一個(gè)。
- Looper.loop()會(huì)讓當(dāng)前線程進(jìn)入一個(gè)無(wú)限循環(huán),不斷從MessageQueue的實(shí)例中讀取消息,然后回調(diào)msg.target.dispatchMessage(msg)方法。
- Handler的構(gòu)造方法,會(huì)首先得到當(dāng)前線程中保存的Looper實(shí)例,進(jìn)而與Looper實(shí)例中的MessageQueue想關(guān)聯(lián)。
- Handler的sendMessage方法,會(huì)給msg的target賦值為handler自身,然后加入MessageQueue中。
- 在構(gòu)造Handler實(shí)例時(shí),我們會(huì)重寫handleMessage方法,也就是msg.target.dispatchMessage(msg)最終調(diào)用的方法。
- Activity的啟動(dòng)代碼中,已經(jīng)在當(dāng)前UI線程調(diào)用了Looper.prepare()和Looper.loop()方法。
- 異步消息處理線程啟動(dòng)后會(huì)進(jìn)入一個(gè)無(wú)限的循環(huán)體之中,每循環(huán)一次,從其內(nèi)部的消息隊(duì)列中取出一個(gè)消息,然后回調(diào)相應(yīng)的消息處理函數(shù),執(zhí)行完成一個(gè)消息后則繼續(xù)循環(huán)。若消息隊(duì)列為空,線程則會(huì)阻塞等待。
參考:
Android 異步消息處理機(jī)制 讓你深入理解 Looper、Handler、Message三者關(guān)系
