引子
在子線程中利用Handler機制來實現(xiàn)UI更新想必都不會陌生,最近項目中注意到了一種Thread中轉(zhuǎn)換到ActivityThread的方式:
new Thread(new Runnable){
@Override
public void run(){
Handler mHandler = new Handler(Looper.getMainLooper);
mHandler.post(new Runnable){
@Override
public void run(){
//操作UI線程
}
}
}
}
與常見Message方式不同,而是直接轉(zhuǎn)到UI線程,有更大的靈活性,但實現(xiàn)方式感覺有點懵,Handler是如何實現(xiàn)線程的轉(zhuǎn)換的,就下定決心看看Android消息機制的原理。
所以寫這篇文章主要是記錄消息機制的原理,并結(jié)合上例分析過程,讓自己對Handler機制有一個比較清晰的認識。
實現(xiàn)過程
這里有三個類:
MessageQueue:消息隊列,主要提供了消息隊列的插入(enqueueMessage)與彈出(next)功能;
Looper:主要實現(xiàn)無限循環(huán)的讀取MessageQueue中是否有新Message,查找到會分發(fā)(dispatchMessage)給Handler處理,否則一直等待;
Handler:Handler實現(xiàn)向MessageQueue發(fā)送Message,另外Looper接收到Message后調(diào)用Handler的處理,即具體實現(xiàn)Android消息機制的類。
先來看一張圖,此圖很好的說明了Handler消息機制的實現(xiàn)過程(非常好的UML序列圖,我就偷懶不畫了,出自 http://blog.csdn.net/oracleot/article/details/19163007)
圖上很清楚的示出,關(guān)于線程轉(zhuǎn)換的過程:Handler發(fā)送消息(post或sendMessage),只需取得對應(yīng)的Handler實例,沒有耗時處理,不限定線程;而一個線程若想Handler消息機制,初始化該線程的Handler前,需要創(chuàng)建自己的Looper與對應(yīng)的QueueMessage,loop()方法在該線程上循環(huán)查詢消息,當(dāng)Looper接收到新消息會調(diào)用Handler相應(yīng)的處理方法,這個過程發(fā)生在Handler所屬線程中;
而引子示例中,可以通過Looper.getMainLooper獲取UI線程的靜態(tài)Looper是因為Android系統(tǒng)在創(chuàng)建Activity時已經(jīng)初始化Looper,屬于一個特例。因此我們不止可以利用Hanlder機制實現(xiàn)對UI線程的操作,而可以實現(xiàn)轉(zhuǎn)換到任意線程處理消息。
下面來看看這三個類的主要實現(xiàn)方法:
MessageQueue
主要完成消息隊列的管理,主要方法插入與彈出,分別對應(yīng)enqueueMessage與next兩個方法
- 先來看enqueueMessage
可以看到MessageQueue并非實現(xiàn)一個隊列,而是一個單鏈表,而該方法主要實現(xiàn)一個Message的插入,而參數(shù)when指定了Message的發(fā)送時間。
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;
}
...
}
return true;
}
- 再來看next:
next實現(xiàn)了一個無限循環(huán)的方法,無消息一直處于阻塞。當(dāng)有消息時,返回該條消息并從鏈表中移除。
Message next() {
...
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;
}
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}
}
...
}
Looper
Looper 扮演著消息循環(huán)的角色,不停地從MessageQueue查詢是否有新消息,如果有的話立刻執(zhí)行,否則阻塞。
- Looper 的創(chuàng)建
首先創(chuàng)建Looper需要調(diào)用靜態(tài)prepare方法,源碼中利用了ThreadLocal這個類,大概的功能是:可以將Looper所處的線程作為Key,而Looper實例作為Value,實現(xiàn)每個每個線程Looper的獨立存儲。
prepare方法中通過get判斷該線程是否已存在Looper,若存在會報錯,不存在的話會將該線程與該Looper以鍵值存儲,從而保證了只有一個Looper實例。
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
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));
}
- loop函數(shù)的分析
這個方法是Loop的最主要的功能方法,實現(xiàn)無限循環(huán)讀取MessageQueue.next,無消息時處于等待阻塞狀態(tài),查詢到新消息會立即執(zhí)行msg.target.dispatchMessage(msg)交與Handler處理。跳出循環(huán)的唯一方式是quit方法被調(diào)用時queue.next會返回null,會直接跳出循環(huán),因此在使用Looper是因記得quit的調(diào)用。
而msg.target.dispatchMessage(msg),這句,調(diào)用了msg的target對象的dispatchMessage函數(shù),其實target就是Handler對象,具體下節(jié)會有分析。
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.recycle();
}
}
Handler
先來看Handler是如何創(chuàng)建的,創(chuàng)建時處理化了兩個引用,mQueue與消息插入有關(guān),callback與消息處理有關(guān),具體分析看后面。
public Handler() {
this(null, false);
}
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());
}
}
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
- 消息插入部分
首先是通過當(dāng)前線程的Looper來獲取MessageQueue實例,獲取實例的目的主要是將消息放入鏈表中,這里就用到了之前說的enqueueMessage插入,并可指定插入時間,Handler中sendMessage,post等發(fā)送消息的方法就是利用這個原理:
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) {
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);
}
- 消息發(fā)送部分
在Looper中提過,Looper從隊列里面取出消息后,調(diào)用Handler的dispatchMessage函數(shù),現(xiàn)在看下實現(xiàn):
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
這里有兩個回調(diào),msg.callback指的是Handler.post中的Runnable,即若是post提交的消息直接給handleCallback處理,實現(xiàn)很簡單:
private static void handleCallback(Message message) {
message.callback.run();
}
然后第二個mCallback是構(gòu)建Handler時傳入的引用,在使用上就是我們最熟悉的handleMessage方法,我們經(jīng)常通過重寫該方法實現(xiàn)消息處理邏輯。也就是說若不存在msg.callback,就會在收到消息后調(diào)用我們定義的handleMessage。這時執(zhí)行的代碼已經(jīng)切換到Handler所在線程~!
關(guān)于自己
其實是第一次花時間把自己看的源碼分析用心記錄下來,所以雖然是熱門知識,也希望能分享出來,當(dāng)作激勵自己繼續(xù)去進步、專研。
我的博客,期待大家的指證與交流~