什麼是Handler?
Handler是程序内部、線程間的一種通信機制。
Handler、Looper、MessageQueen、Message的關系
Message: 消息對象
MessageQueen: 存儲消息對象的隊列
Looper:負責循環讀取MessageQueen中的消息,讀到消息之後就把消息交給Handler去處理。
Handler:發送消息和處理消息
![]()
一文搞懂Handler機制
源碼解析
要想使用handler ,首先要保證目前所線上程存在Looper對象
主線程不需要主動建立Looper對象是因為主線程已經為你準備好了,詳見android.app.ActivityThread->Looper.prepareMainLooper()
我們建立的子線程如果想用handler接收資料,需要先通過Looper.prepare()建立Looper
Looper.prepare();
...//建立Handler并傳入
Looper.loop()
Looper類
Looper構造方法
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
建立Looper對象的時候,同時建立了MessageQueue,并讓Looper綁定目前線程。但我們從來不直接調用構造方法擷取Looper對象,而是使用Looper的prepare()方法
prepare()使用ThreadLocal 儲存目前Looper對象,ThreadLocal 類可以對資料進行線程隔離,保證了在目前線程隻能擷取目前線程的Looper對象,同時prepare()保證目前線程有且隻有一個Looper對象,間接保證了一個線程隻有一個MessageQueue對象
Looper的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));
}
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;
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
for (;;) {
Message msg = queue.next(); // might block 也許會堵塞,一會在next方法中解析
if (msg == null) {
return;
}
try {
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
msg.recycleUnchecked();
}
}
Lopper通過loop()開啟無限循環,通過MessageQueue的next()擷取message對象。一旦擷取就調用msg.target.dispatchMEssage(msg)将msg交給handler對象處理(msg.target是handler對象),最後回收
Handler類
Hanlder執行個體化
public Handler(Callback callback, boolean async) {
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;
}
執行個體化過程中擷取目前線程的MessageQueue對象,以便于将消息加入MessageQueue
發送消息
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);
}
enqueueMessage中首先為msg.target指派為this,為發送消息出隊列交給handler處理埋下伏筆。
處理消息
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
前面我們提到Looper.loop()擷取到消息時會調用handler的dispatchMessage方法進行處理,handler處理消息就是調用我們重寫的handleMessage()方法,或者我們可以在建立Handler執行個體時實作Callback接口,一樣可以處理從MessageQueue出來的消息
MessageQueue類
MessageQueue 構造方法
MessageQueue(boolean quitAllowed) {
mQuitAllowed = quitAllowed;
mPtr = nativeInit();
}
MessageQueue初始化過程同時初始化底層的NativeMessageQueue對象,并且持有NativeMessageQueue的記憶體位址(long)
MessageQueue的next()
Message next() {
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(); //刷一下,就當是Android系統的一種性能優化操作
}
nativePollOnce(ptr, nextPollTimeoutMillis);//native底層實作堵塞,堵塞狀态可被新消息喚醒,頭一次進來不會延遲
synchronized (this) {
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;//擷取頭節點消息
if (msg != null && msg.target == null) {
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);//擷取堵塞時間
} else {
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; //直接出隊列傳回給looper
}
} else {
nextPollTimeoutMillis = -1;//隊列已無消息,一直堵塞
}
if (mQuitting) {
dispose();
return null;
}
pendingIdleHandlerCount = 0;
nextPollTimeoutMillis = 0;
}
}
雖然looper也開啟了循環,但是到了真正幹活的時候它卻調用了MessageQueue的next(),要想搞明白怎麼個堵塞,先看這三個對應的條件
nextPollTimeoutMillis=0 不堵塞
nextPollTimeoutMillis<0 一直堵塞
nextPollTimeoutMillis>0 堵塞對應時長,可被新消息喚醒
next()中,因為消息隊列是按照延遲時間排序的,是以先考慮延遲最小的也就是頭消息。當頭消息為空,說明隊列中沒有消息了,nextPollTimeoutMIllis就被指派為-1,當頭消息延遲時間大于目前時間,堵塞消息要到延遲時間和目前時間的內插補點
當消息延遲時間小于等于0,直接傳回msg給handler處理
nativePollOnce(ptr, nextPollTimeoutMillis)方法是native底層實作堵塞邏輯,堵塞狀态會到時間喚醒,也可被新消息喚醒,一旦喚醒會重新擷取頭消息,重新評估是否堵塞或者直接傳回消息
消息入棧enqueueMessage()
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;
}
消息入棧時,首先會判斷新消息如果是第一個消息 或者 新消息沒有延遲 或者 新消息延遲時間小于隊列第一個消息的,都會立刻對這個消息進行處理。隻有當消息延遲大于隊列頭消息時,才會依次周遊消息隊列,将消息按延遲時間插入消息隊列響應位置。
Message類
Message 初始化
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
建議使用obtain()擷取Message對象,因為Message維護着一個消息池,這個消息池的資料結構是單向連結清單,優先從池子裡拿資料,如果池子裡沒有再建立對象。如果Message對象已存在,可以使用obtain(msg)方法,最終也會調用obtain()
消息的回收
void recycleUnchecked() {
flags = FLAG_IN_USE;
what = 0;
arg1 = 0;
arg2 = 0;
obj = null;
replyTo = null;
sendingUid = -1;
when = 0;
target = null;
callback = null;
data = null;
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
消息的回收不是将Message對象銷毀,而是将Message對象的值恢複初始值然後放回池子,等待使用
因為android會頻繁的使用Message的對象,使用“池”這種機制可以減少建立對象開辟記憶體的時間,更加高效的利用記憶體,是以"池"這種機制被應用于頻繁大量使用的類對象的情況,我們常說的“線程池”也是基于同樣的原理。
總結: 要想在目前線程使用handler機制,首先確定目前線程存在Looper
**Looper.parper()建立一個 目前線程的Looper對象,同時建立一個MessageQueue對象 **
每個線程隻有一個Looper對象和一個MessageQueue對象
Looper.loop()開始循環,沒有msg情況下進入堵塞狀态(-1)
Message對象最好通過Message.obtain()獲得
Handler發送消息進入隊列,如果沒有延遲喚醒堵塞 Looper獲得msg ,調用msg.targe.dispachMessage處理消息
關閉Activity如果棧中有未出棧的message,需清除handler.removeMessage(int)
子線程不再使用handler時,要調用loop.quit(),loop.quitSafely()
雖然表面上看是looper循環隊列,并将msg給handler,但實際上是MessageQueue的next()去完成的,MessageQueue同時還承擔消息的入隊列,并對消息按照延遲時間從小到大進行了排序。鑒于MessageQueue如此大的工作量,在Android 2.3版本後,MessageQueue中next()方法的堵塞機制轉移到了native層去處理,也就是我們使用的nativePollOnce(ptr, nextPollTimeoutMillis)方法
本篇博文沒有分析屏障邏輯(msg.target==null),以及底層的堵塞邏輯,也沒有分析異步消息邏輯(msg.isAsynchronous()==true)