Android的消息機(jī)制是指Handler
的運(yùn)行機(jī)制,Handler是我們經(jīng)常需要用到的一個(gè)東西,所以熟練掌握這個(gè)知識(shí)點(diǎn)非常有必要。一般我們用Handler來更新UI界面,比如我們有一些耗時(shí)的操作需要在子線程中處理,如下載、請(qǐng)求網(wǎng)絡(luò)數(shù)據(jù)等,當(dāng)這些耗時(shí)的操作完成后,可能會(huì)需要在UI做一些改變,比如請(qǐng)求完數(shù)據(jù)后需要將結(jié)果數(shù)據(jù)顯示在頁(yè)面相應(yīng)的控件上,比如下載過程中需要在UI界面顯示下載進(jìn)度等,但是Android系統(tǒng)規(guī)定,在子線程中是不能更新UI控件的,否則會(huì)出現(xiàn)異常。系統(tǒng)不允許在子線程中訪問UI是因?yàn)锳ndroid的UI控件并不是線程安全的,如果在多線程并發(fā)訪問可能會(huì)導(dǎo)致UI控件的狀態(tài)不可控。那么當(dāng)子線程中需要更新UI時(shí),Android的消息機(jī)制是怎么把更新UI的操作切換到主線程中的呢?
雖然關(guān)于Android消息機(jī)制在實(shí)際開發(fā)過程中我們開發(fā)者一般只需要使用到Handler,但是我們有必要清楚在實(shí)際開發(fā)過程中,Handler是和MessageQueue
和Looper
一起協(xié)同工作的。MessageQueue即消息隊(duì)列,它是用來存儲(chǔ)消息的,以隊(duì)列的形式對(duì)消息進(jìn)行存取操作。Looper即輪詢器,用來輪詢消息隊(duì)列中是否有消息存在,MessageQueue是接收到消息后將其存儲(chǔ)起來,但它不能去處理消息,而Looper則是無限循環(huán)的去MessageQueue查看是否有新消息,有就去處理消息。
Handler在創(chuàng)建其對(duì)象的時(shí)候會(huì)采用當(dāng)前線程的Looper來構(gòu)造消息循環(huán)系統(tǒng),但是它是怎么獲取到當(dāng)前線程的Looper的呢?這里它用到了ThreadLocal
,ThreadLocal可以在不同的線程互不干擾的存儲(chǔ)并提供數(shù)據(jù),通過ThreadLocal就可以拿到每個(gè)線程的Looper。當(dāng)然一個(gè)線程默認(rèn)是沒有Looper的,如果需要在一個(gè)線程中使用Handler就必須為線程創(chuàng)建Looper,而UI線程也就是ActivityThread
在被創(chuàng)建時(shí)就會(huì)初始化Looper,所以在UI線程中,默認(rèn)就可以使用Handler。如果當(dāng)前線程中沒有Looper,就會(huì)出現(xiàn)下面的異常:
解決辦法就是為當(dāng)前線程創(chuàng)建一個(gè)Looper,錯(cuò)誤提示也告訴我們只需要調(diào)用
Looper.prepare();
就可以為當(dāng)前線程創(chuàng)建一個(gè)Looper,然后調(diào)用
Looper.loop();
來開啟消息輪詢,這樣在子線程中就同樣可以使用Handler了,比如這樣:
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
new Handler().post(new Runnable() {
@Override
public void run() {
}
});
Looper.loop();
}
}).start();
ThreadLocal的工作原理
上面提到了Handler在創(chuàng)建的時(shí)候會(huì)獲取到當(dāng)前線程的Looper來構(gòu)造消息循環(huán)系統(tǒng),而獲取Looper時(shí)用到了ThreadLocal,ThreadLocal是一個(gè)線程內(nèi)部的數(shù)據(jù)存儲(chǔ)類,通過它可以在指定的線程中存儲(chǔ)數(shù)據(jù),數(shù)據(jù)存儲(chǔ)后只有在指定的線程中才可以獲取到存儲(chǔ)的數(shù)據(jù),對(duì)于其他線程則無法獲取到。當(dāng)某些數(shù)據(jù)以線程為作用域并且不同線程具有不同的數(shù)據(jù)副本時(shí)就可以考慮使用ThreadLocal,比如Handler獲取當(dāng)前線程的Looper,Looper的作用域就只是當(dāng)前線程且不同的線程有不同的Looper,所以這時(shí)使用ThreadLocal就可以很容易的存取Looper。下面通過代碼來看看:
private ThreadLocal<String> mThreadLocal = new ThreadLocal<>();
// UI線程中賦值
mThreadLocal.set("shenhuniurou");
// UI線程中取值
Log.d(TAG, "UI線程中mThreadLocal=" + mThreadLocal.get());
new Thread("Thread1") {
@Override
public void run() {
// Thread1線程中賦值
mThreadLocal.set("shenhuniurou1");
// Thread1線程中取值
Log.d(TAG, "UThread1線程中mThreadLocal=" + mThreadLocal.get());
}
}.start();
new Thread("Thread2") {
@Override
public void run() {
// Thread2線程中賦值
mThreadLocal.set("shenhuniurou2");
// Thread2線程中取值
Log.d(TAG, "UThread1線程中mThreadLocal=" + mThreadLocal.get());
}
}.start();
日志輸出如圖:
上面的代碼我們發(fā)現(xiàn),在不同的線程訪問同一個(gè)ThreadLocal對(duì)象,獲取到的值卻不一樣。這是因?yàn)椴煌€程訪問同一個(gè)ThreadLocal的get方法,ThreadLocal內(nèi)部會(huì)從各自的線程中取一個(gè)數(shù)組,然后再?gòu)臄?shù)組中根據(jù)當(dāng)前ThreadLocal的索引去查找出對(duì)應(yīng)的value值,所以不同線程的數(shù)組是不同的。
Handler的工作原理
Handler在消息機(jī)制中的工作主要包括消息的發(fā)送和接收,發(fā)送消息有兩種方式,一種是采用post方式:
handler.post(Runnable)
or
handler.postDelayed(Runnable)
另一種采用sendMessage方式:
handler.sendMessage(Message)
實(shí)際上post的方式最終也是通過sendMessage的方式完成的,我們可以看看post方式的源碼:
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;
}
接下來我們看看Handler類中sendMessage方式的工作過程。我們發(fā)現(xiàn)所有sendMessage方法最后都會(huì)調(diào)用到下面這個(gè)方法去:
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);
}
而Handler中持有消息隊(duì)列的引用,在enqueueMessage方法中將消息添加到隊(duì)列中:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
上面這段代碼在調(diào)用MessageQueue的enqueueMessage方法前,為消息msg設(shè)置一個(gè)target,即當(dāng)前的Handler類,這個(gè)后面會(huì)有用。我們可以到MessageQueue這個(gè)類中去看看enqueueMessage這個(gè)方法:
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;
}
從這段代碼中我們可以發(fā)現(xiàn),消息隊(duì)列雖然名為隊(duì)列,可它內(nèi)部的數(shù)據(jù)結(jié)構(gòu)實(shí)際上是一個(gè)單鏈表。消息中的Runnable其實(shí)就是一個(gè)回調(diào)函數(shù),當(dāng)Looper處理完消息后,消息中的Runnable或者Handler的handleMessage
方法就會(huì)被調(diào)用,而Looper是運(yùn)行在創(chuàng)建Handler所在的線程中,這樣Runnable或者h(yuǎn)andleMessage中的事務(wù)處理就被切換到創(chuàng)建Handler的線程了。
我們可以看到Handler發(fā)送消息的過程實(shí)際上僅僅是往消息隊(duì)列中添加了一條消息。而Looper一直在輪詢查看是否有新消息:
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
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.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
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();
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();
}
}
可以看到,Looper取消息是調(diào)用了隊(duì)列的next方法,然后調(diào)用
msg.target.dispatchMessage(msg);
前面說過這個(gè)消息的target就是Handler,所以是調(diào)用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其實(shí)就是post發(fā)送消息時(shí)傳遞的那個(gè)Runnable,如果有發(fā)送消息時(shí)有Runnable,就調(diào)用Runnable的run方法:
private static void handleCallback(Message message) {
message.callback.run();
}
若沒有就檢查mCallback是否為空,不為空就調(diào)用mCallback的handleMessage方法。mCallback是一個(gè)接口,當(dāng)我們不想派生Handler的子類時(shí)可以采用實(shí)現(xiàn)Callback方式來實(shí)現(xiàn)。使用方法是當(dāng)前類實(shí)現(xiàn)Handler.Callback,然后重寫handleMessage方法。
public class MainActivity extends AppCompatActivity implements Handler.Callback {
@Override
public boolean handleMessage(Message msg) {
return false;
}
}
最后如果mCallback為空,就調(diào)用Handler的handleMessage方法:
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
MessageQueue的工作原理
消息隊(duì)列的主要工作包括消息的添加和讀取,分別使用的enqueueMesaage
和next
方法,上面已經(jīng)說過enqueueMessage方法了,就是把一條消息插入到單鏈表中,這里我們看一下next方法:
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
// Next message is not ready. Set a timeout to wake up when it is ready.
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// Got a message.
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
}
}
}
可以看到,next方法和loop方法一樣,是一個(gè)無線循環(huán)的方法,如果消息隊(duì)列中沒有消息,next方法會(huì)一直阻塞在這里,當(dāng)有新消息來時(shí),next方法會(huì)返回該消息并將其從單鏈表中移除。
Looper的工作原理
Looper輪詢器的工作就是輪詢消息,有消息就處理,否則就阻塞,它的構(gòu)造方法如下:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
首先它會(huì)創(chuàng)建一個(gè)MessageQueue,然后將當(dāng)前線程保存起來。前面也有提到如何創(chuàng)建一個(gè)Looper,即調(diào)用Looper的prepare方法來為當(dāng)前線程創(chuàng)建Looper:
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));
}
如果當(dāng)前線程的ThreadLocal已經(jīng)存在了Looper,調(diào)用prepare時(shí)則會(huì)拋出異常,每個(gè)線程只能創(chuàng)建一個(gè)Looper。創(chuàng)建完之后又將Looper保存到了ThreadLocal中。除了prepare方法外,Looper還提供了prepareMainLooper方法,該方法主要是給主線程也就是ActivityThread創(chuàng)建Looper使用的,但其本質(zhì)還是通過prepare方法實(shí)現(xiàn)的:
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
Looper也是可以退出的,Looper提供了quit
和quitSafely
方法來退出Looper,二者最終都是調(diào)用隊(duì)列的quit方法,只不過參數(shù)不同:
mQueue.quit(flag);
void quit(boolean safe) {
if (!mQuitAllowed) {
throw new IllegalStateException("Main thread not allowed to quit.");
}
synchronized (this) {
if (mQuitting) {
return;
}
mQuitting = true;
if (safe) {
removeAllFutureMessagesLocked();
} else {
removeAllMessagesLocked();
}
// We can assume mPtr != 0 because mQuitting was previously false.
nativeWake(mPtr);
}
}
quit是直接退出Looper,而quitSafely只是設(shè)定一個(gè)退出標(biāo)記,然后把消息隊(duì)列中的已有消息處理完畢后才安全退出。其實(shí)也就是下面這兩個(gè)方法的區(qū)別:
private void removeAllMessagesLocked() {
Message p = mMessages;
while (p != null) {
Message n = p.next;
p.recycleUnchecked();
p = n;
}
mMessages = null;
}
private void removeAllFutureMessagesLocked() {
final long now = SystemClock.uptimeMillis();
Message p = mMessages;
if (p != null) {
if (p.when > now) {
removeAllMessagesLocked();
} else {
Message n;
for (;;) {
n = p.next;
if (n == null) {
return;
}
if (n.when > now) {
break;
}
p = n;
}
p.next = null;
do {
p = n;
n = p.next;
p.recycleUnchecked();
} while (n != null);
}
}
}
Looper退出后,通過Handler發(fā)送消息會(huì)失敗,在子線程中如果手動(dòng)創(chuàng)建Looper,在事情處理完之后要調(diào)用quit方法來終止消息循環(huán),否則該子線程會(huì)一直處于等待狀態(tài),如果退出Looper以后,該線程就會(huì)終止。
Looper開啟消息循環(huán)的方法是loop,上面也提到過,它是無限循環(huán)的,能停止循環(huán)的就是消息隊(duì)列的next方法返回null,當(dāng)Looper調(diào)用了quit方法時(shí),Looper會(huì)調(diào)用消息隊(duì)列的quit或者quitSafely方法來通知消息隊(duì)列退出,當(dāng)消息隊(duì)列被標(biāo)記為退出狀態(tài)時(shí),它的next方法就會(huì)返回null,退出標(biāo)記就是這個(gè)變量mQuitting
,我們看到在隊(duì)列的quit方法出,它被標(biāo)記為true了。
到這里Handler、MessageQueue、Looper的工作原理都理清了,下面用一張圖說明Android消息機(jī)制的工作原理:
相信看到這里,你已經(jīng)對(duì)第一段中我們拋出的問題“Android的消息機(jī)制是怎么把更新UI的操作切換到主線程中的呢?”有答案了吧。