Handler在Android開發(fā)中無處不在隶校,它的使用方式想必大家都已經(jīng)很熟練了漏益,這里主要是分析它的原理。
我們從ActivityThread#main方法開始深胳,一步步理解Handler的機制绰疤。相關(guān)代碼如下:
/frameworks/base/core/java/android/app/ActivityThread.java
public static void main(String[] args) {
...
Looper.prepareMainLooper();
...
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
在ActivityThread初始化時就通過Looper建立了消息循環(huán)機制,先看下初始化部分舞终,相關(guān)代碼如下:
/frameworks/base/core/java/android/os/Looper.java
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
// 確保主線程僅有一個Looper實例
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
private static void prepare(boolean quitAllowed) {
// 確保線程僅對應一個Looper
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
這里通過ThreadLocal確保線程安全轻庆,且保證任何線程只能對應一個Looper實例。Looper實例化時敛劝,就確定了它所在的線程余爆,同時創(chuàng)建了一個MessageQueue,代碼如下:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
MessageQueue稍后再研究夸盟,先看下Looper#loop的實現(xiàn)蛾方,代碼如下:
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;
}
...
try {
// 分發(fā)消息
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
...
msg.recycleUnchecked();
}
}
這里建立了一個無限循環(huán)桩砰,不斷地從MessageQueue中獲取消息,然后進行分發(fā)释簿,而我們使用的Handler并沒有直接綁定在Looper中亚隅,而是綁定在msg.target變量里,這樣做的好處是可以創(chuàng)建多個Handler庶溶。下面我們轉(zhuǎn)到MessageQueue中煮纵,了解下MessageQueue#next方法沉删,代碼如下:
/frameworks/base/core/java/android/os/MessageQueue.java
Message next() {
...
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.
// 沒到msg分發(fā)時間
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;
}
...
}
...
}
}
這里通過for循環(huán)不斷的獲取消息醉途,然后等待消息分發(fā)時間到之后將消息分發(fā)出去矾瑰,這樣消息循環(huán)就建立好了。不過這里我們看到一段對異步消息的處理隘擎,為了更好的理解這段的作用殴穴,我們在文末再分析。接下來就應該通過Handler來發(fā)送消息和處理消息货葬,Handler發(fā)送消息的方法有很多種采幌,我們主要使用的有以下幾種:
handler.sendMessage(msg)
handler.sendMessageDelayed(msg, delay)
handler.post(runnable)
handler.postDelayed(runnable, delay)
除了以上幾個,還有幾個類似的方法震桶,甚至還有一個Handler#sendMessageAtFrontOfQueue方法休傍,可以在消息隊列的最前面插入消息,不過這些方法的原理都是一致的蹲姐,我們著重分析Handler#sendMessage和Handler#post這兩個方法磨取。代碼如下:
/frameworks/base/core/java/android/os/Handler.java
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
可以看到,它們最終都是調(diào)用了Handler#sendMessageDelayed方法柴墩,只是通過post方式最終將Runnable轉(zhuǎn)成了Message對象忙厌,具體的做法如下:
private static Message getPostMessage(Runnable r) {
// 從一個全局的對象池里獲取Message對象,可以重復使用江咳,這樣就節(jié)省了new對象的開支
Message m = Message.obtain();
m.callback = r;
return m;
}
也就是說這個Runnable實例就是作為Message的callback的逢净。繼續(xù)看Handler#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;
...
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);
}
最終歼指,所有的方法都會調(diào)用到這個Handler#enqueueMessage方法爹土,將Handler本身作為Message的target參數(shù),然后將消息入隊踩身,最后在Looper中分發(fā)胀茵。接下來看下入隊的操作,代碼如下:
/frameworks/base/core/java/android/os/MessageQueue.java
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) {
// 新消息需要更早分發(fā)
// 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();
// 根據(jù)時間順序惰赋,將消息插入到合適的位置
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)宰掉,消息在入隊時,就已經(jīng)按照時間順序排列好了赁濒,最后到了分發(fā)階段,分發(fā)是通過Handler#dispatchMessage完成的孟害,代碼如下:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
private static void handleCallback(Message message) {
message.callback.run();
}
原來拒炎,如果在發(fā)送Message時設(shè)置了callback,就會由我們設(shè)置的Runnable來處理挨务,否則击你,就通過Handler初始化時指定的Callback處理玉组,如果都沒有設(shè)置,就通過Handler#handleMessage方法來處理丁侄。這個mCallback是在構(gòu)造函數(shù)中實例化的惯雳,我們看幾個構(gòu)造方法就明白了:
public Handler() {
this(null, false);
}
public Handler(Callback callback) {
this(callback, false);
}
public Handler(Looper looper) {
this(looper, null, false);
}
public Handler(Looper looper, Callback callback) {
this(looper, callback, false);
}
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
現(xiàn)在我們來解釋下前面提到的異步消息。通過向MessageQueue中發(fā)送消息就可以讓事件按照指定的時間和順序來執(zhí)行鸿摇,但如果想要讓消息有優(yōu)先級區(qū)別呢石景?可以使用MessageQueue#postSyncBarrier方法,代碼如下:
public int postSyncBarrier() {
return postSyncBarrier(SystemClock.uptimeMillis());
}
private int postSyncBarrier(long when) {
// Enqueue a new sync barrier token.
// We don't need to wake the queue because the purpose of a barrier is to stall it.
synchronized (this) {
final int token = mNextBarrierToken++;
final Message msg = Message.obtain();
msg.markInUse();
msg.when = when;
msg.arg1 = token;
Message prev = null;
Message p = mMessages;
if (when != 0) {
while (p != null && p.when <= when) {
prev = p;
p = p.next;
}
}
if (prev != null) { // invariant: p == prev.next
msg.next = p;
prev.next = msg;
} else {
msg.next = p;
mMessages = msg;
}
return token;
}
}
看起來這個方法也沒有什么特別的地方拙吉,唯一的區(qū)別就是消息沒有target潮孽,也就是沒有Handler對象,MessageQueue在執(zhí)行next方法時就會走到if (msg != null && msg.target == null)
中筷黔,此時它會忽略其間所有的同步消息往史,直到找到一個異步消息并開始執(zhí)行,這個做法稱之為同步屏障佛舱。調(diào)用此方法后可以得到一個token值椎例,可以通過這個值取消屏障。然后我們就可以向MessageQueue發(fā)送一個異步消息请祖,優(yōu)先執(zhí)行此事件了粟矿。MessageQueue#postSyncBarrier通常需要與MessageQueue#removeSyncBarrier成對使用,否則就再也接收不到同步消息了损拢。目前陌粹,這個方法被標記為HIDE,在API層面無法調(diào)用福压。
在RootViewImpl#scheduleTraversals方法中掏秩,為了讓Android系統(tǒng)能夠更快的響應UI的刷新事件,就使用了此方法荆姆,代碼如下:
void scheduleTraversals() {
if (!mTraversalScheduled) {
mTraversalScheduled = true;
mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
mChoreographer.postCallback(
Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
if (!mUnbufferedInputDispatch) {
scheduleConsumeBatchedInput();
}
notifyRendererOfFramePending();
pokeDrawLockIfNeeded();
}
}
具體的分析請看Android源碼分析之Activity啟動與View繪制流程(一)蒙幻。
至此,我們對Handler機制就有了清晰的認識胆筒,它并不復雜邮破,但是功能十分強大,掌握它的原理以后使用時會更加順手。