概述
前面 講了消息機制中的 MessageQueue,Looper 與 MessageQueue 的關聯是 Looper 會通過輪詢,不斷從 MessageQueue 中獲取新消息,如果有新消息就會立即處理,沒有新消息就會阻塞。
示例
子線程創建Handler,需要綁定對應的 Looper,不然會報錯:
new Thread(new Runnable() {
@Override
public void run() {
//方法一:創建子線程的 Looper
//需要加Looper.prepare(); 不然會報錯
Looper.prepare();
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Toast.makeText(getApplicationContext(), "handler msg", Toast.LENGTH_LONG).show();
}
};
handler.sendEmptyMessage(1);
//需要加Looper.loop() 開啓消息輪詢
Looper.loop();
//方法二:獲取主線程的looper,或者說是UI線程的looper
/* Handler handler2 = new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message msg) {
//super.handleMessage(msg);
LogUtils.e("twj124", "handleMessage");
Toast.makeText(getApplicationContext(), "handler msg", Toast.LENGTH_LONG).show();
}
};
handler2.sendEmptyMessage(1);*/
}
}).start();
源碼
因爲一個線程只有一個 Looper 和 一個 MessageQueue,在 Looper 的構造方法中,會初始化該線程對應的 MessageQueue 並獲取當前線程:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
Looper 最重要的方法是loop()
,該方法會不斷從 MessageQueue 中取消息。
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static void loop() {
final Looper me = myLooper();
//如果沒有當前線程沒有創建對應的 Looper,就會拋出異常。
//因此,在子線程中,需要調用 Looper.prepare() 和 Looper.loop()
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
//獲取到與Looper 綁定的 MessageQueue
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 (;;) {
//調用MessageQueue的next方法,將消息按照時間順序插入到消息隊列
//沒有消息是
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 slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
final long end;
try {
//msg.target實際爲發送這條消息的Handler對象
//dispatchMessage:與Looper對象在同一個線程,而handleMessage()與Handler創建在同一個線程,因此實現了線程切換
//這樣,Handler發送的消息最終會交給它的dispatchMessage來處理,該方法最後會調用handleMessage()來處理
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (slowDispatchThresholdMs > 0) {
final long time = end - start;
if (time > slowDispatchThresholdMs) {
Slog.w(TAG, "Dispatch took " + time + "ms on "
+ Thread.currentThread().getName() + ", h=" +
msg.target + " cb=" + msg.callback + " msg=" + msg.what);
}
}
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();
}
}
可以看到,loop()
方法是一個死循環,只有當 MessageQueue 的 next()
方法爲 null 時,纔會結束循環。那麼MessageQueue 的 next()
什麼時候回返回 null 呢?我們看 next()
方法:
//MessageQueue#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;
}
//省略。。。
}
//Looper#quit()
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);
}
}
可以看到,當 Looper 的 quit()
/ quitSafely()
方法被調用時,消息隊列就會被標記爲退出狀態( mQuitting = true
),消息隊列的 next()
就會返回 null。因此,在子線程中,如果手動創建了 Looper,那麼在完成所有任務後應該調用quit()
來終止消息循環,否則這個子線程一直處於等待狀態,而如果退出 Looper 後,該線程就會立刻終止。所以,在不需要的時候,應該養成良好的編程習慣來終止 Looper。