0.前言
Handler,Looper,MessageQueue三者配合共同完成Android的消息機(jī)制,每個(gè)線程都有自己的消息隊(duì)列桶良。消息機(jī)制是進(jìn)程起來就會(huì)從android.app.ActivityThread#main方法為main主線程創(chuàng)建一個(gè)MessageQueue消息隊(duì)列并通過Looper#loop方法進(jìn)入不斷從消息隊(duì)列獲取消息的過程。所以子線程需要自己添加一個(gè)線程隊(duì)列沮翔。
1.Handler,MessageQueue,Looper三角關(guān)系
Handler:負(fù)責(zé)生產(chǎn)消息陨帆,接收消息。將消息post到消息隊(duì)列MessageQueue中去采蚀。
Looper:負(fù)責(zé)循環(huán)從MessageQueue消息隊(duì)列中獲取消息疲牵,然后通過Handler分發(fā)消息出去各自處理。
MessageQueue:當(dāng)前線程的消息隊(duì)列榆鼠,用于接受Handler post過來的消息纲爸,存儲(chǔ)消息。
2.Handler工作過程分析
以下代碼我們平時(shí)開發(fā)過程中應(yīng)該非常熟悉妆够,我們就從這里分析识啦。
new Handler().post(new Runnable() {
@Override
public void run() {
}
});
首先我們從Handler post/postDelayed方法分析,具體這兩個(gè)方法僅僅從消息池中獲取一個(gè)消息實(shí)體神妹,然后將Runnable類型r賦值給callback颓哮,用于后面回調(diào)。方法如下:
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
public final boolean postDelayed(Runnable r, long delayMillis)
{
return sendMessageDelayed(getPostMessage(r), delayMillis);
}
我們可以看到post/postDelayed方法最終都是調(diào)用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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
通過以上代碼queue.enqueueMessage(msg, uptimeMillis)可以看出题翻,其實(shí)就是將一個(gè)消息加入到消息隊(duì)列MessageQueue中。接下來我們繼續(xù)跟進(jìn)MessageQueue#enqueueMessage方法腰鬼。
3.MessageQueue工作過程分析
首頁我們看看MessageQueue這個(gè)消息隊(duì)列是什么時(shí)候創(chuàng)建的嵌赠。在這里我們大家平時(shí)開發(fā)過程中很少說到android程序的入口,學(xué)過C語言的同學(xué)應(yīng)該知道程序的入口就是main方法熄赡,那android是不是也用main方法呢姜挺?同樣也有,位于ActivityThread中main方法(android.app.ActivityThread#main)
public static void main(String[] args) {
彼硫。
炊豪。
凌箕。
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
AsyncTask.init();
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
以上我們看到Looper#prepareMainLooper方法
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
再跟進(jìn)prepare方法如下:
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));
}
我們看到sThreadLocal.set(new Looper(quitAllowed)),Looper構(gòu)造方法如下:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
沒錯(cuò)就是這里词渤。然后我們跟進(jìn)到Looper構(gòu)造方法中牵舱,我們看到,原理MessageQueue是在Looper中初始化的缺虐。在這里我們看到sThreadLocal對(duì)象引用芜壁,這個(gè)其實(shí)就是一個(gè)本地變量副本,跟進(jìn)ThreadLocal.set(new Looper(quitAllowed))方法你可以看到其實(shí)跟線程有關(guān)聯(lián)了高氮。這里就不贅述了慧妄。具體看我上篇:ThreadLocal分析。到這里其實(shí)我們應(yīng)該可以知道每個(gè)線程都有自己的消息隊(duì)列剪芍。
接著我們看看消息加入隊(duì)列塞淹,源碼如下:
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
synchronized (this) {
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w(TAG, e.getMessage(), e);
msg.recycle();
return false;
}
msg.markInUse();
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;
}
4.Looper工作過程分析
首先我們從上面android.app.ActivityThread#main方法中我們可以看到,通過Looper.prepareMainLooper方法在Looper類中創(chuàng)建一個(gè)當(dāng)前本地線程關(guān)聯(lián)Looper對(duì)象并創(chuàng)建一個(gè)消息隊(duì)列罪裹。然后通過Looper.loop方法不斷的從消息隊(duì)列中獲取消息并通過Handler分發(fā)出對(duì)應(yīng)的消息饱普。下面我們重點(diǎn)看看Looper#loop方法:
public static void loop() {
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();
for (;;) {
Message msg = queue.next(); // might block
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);
}
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.recycleUnchecked();
}
}
1.通過myLooper獲取當(dāng)前線程的Looper對(duì)象。
2.獲取的myLooper不為空状共,這個(gè)時(shí)候取出Looper構(gòu)造函數(shù)中創(chuàng)建的MessageQueue消息隊(duì)列费彼。
3.然后進(jìn)入一個(gè)死循環(huán)中,通過queue.next取出下一個(gè)Message消息口芍,消息為空則直接返回箍铲,反之繼續(xù)執(zhí)行。
4.通過dispatchMessage方法分發(fā)消息出去鬓椭。這里我們看到是通過msg.target對(duì)象分發(fā)的颠猴,那msg.target是啥東西?我們看回android.os.Handler#enqueueMessage方法:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
將msg.target 賦值為 this小染,這里我們知道m(xù)sg.target其實(shí)就是一個(gè)Handler對(duì)象翘瓮。
5.接著我們繼續(xù)分析消息分發(fā)的過程,通過msg.target.dispatchMessage會(huì)調(diào)用android.os.Handler#dispatchMessage方法:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
當(dāng)msg.callback不為空就調(diào)用handleCallback方法裤翩,msg.callback又是啥呢资盅?我們回憶下android.os.Handler#getPostMessage(java.lang.Runnable)方法:
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
msg.callback其實(shí)是Handler#post方法的一個(gè)Runnable對(duì)象。
反之當(dāng)msg.callback為空踊赠,同時(shí)mCallback不會(huì)空呵扛,就通過Callback接口回調(diào)到調(diào)用的地方,同時(shí)直接return筐带。
public Handler(Looper looper, Callback callback) {
this(looper, callback, false);
}
通過上面可以看出mCallback是實(shí)例化Handler的時(shí)候傳進(jìn)來的今穿,則消息就會(huì)回調(diào)到對(duì)應(yīng)的handleMessage方法中。
到此整個(gè)消息機(jī)制的過程就分析完了伦籍。