本文內容基于《Android開發藝術探索》,有興趣的同學可以買本書,值得一看。
](https://raw.githubusercontent.com/zhong1990/BlogResource/master/0_1317287552OWa9.gif)
1.Handler工作原理
Handler主要任務是發送和接收處理消息,發送消息可以通過post
或者send
相關方法來實現,我們先來看一下Handler
類中post
和send
方式的代碼實現
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;
}
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);
}
我們可以發現post
還是通過調用send
方式來發送消息的,發送消息只是通過queue.enqueueMessage(msg, uptimeMillis);
向消息隊列中插入一條消息,MessageQueue
會把消息交給Looper
,Looper
再把消息交給Handler
的dispatchMessage
方法處理,具體過程會在下面分析,現在我們來看一下dispatchMessage
的實現
public void dispatchMessage(Message msg) {
if (msg.callback != null) { //如果消息已設置callback,則調用該callback函數
handleCallback(msg);
} else {
if (mCallback != null) { //如果Handler已設置callback,則調用該callback處理消息
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg); //默認為空函數,用戶可重載處理自定義消息
}
}
從上面代碼可以看出,首先檢查Message
的callback
是否為null
,不為null
則交給handleCallback
方法執行,Message
的callback
是一個Runnable
對象,實際上就是post
傳入的Runable
對象(可查看Handler
的getPostMessage()
方法),handleCallback
中直接調用callback
的run
方法,handleCallback
實現如下
private static void handleCallback(Message message) {
message.callback.run();
}
如果msg.callback
為null,即消息是通過send
方式發送的,則會再判斷mCallback
是否為null
,不為null
則調用mCallback
的handleMessage
方法,Callback
是Handler
類中的一個接口,我們可以在中通過Handler handler = new Handler(callback)
來創建handler
并實現Callback
來處理消息。
public interface Callback {
public boolean handleMessage(Message msg);
}
如果mCallback
為null
則會調用Handler
的handleMessage
方法來處理消息,這是我們最常用的方式。
2.MessageQueue工作原理
接下來分析一下MessageQueue
的工作原理,MessageQueue
中通過enqueueMessage()
方法來插入消息,通過next()
方法來取出數據。enqueueMessage
方法實現如下
boolean enqueueMessage(Message msg, long when) {
...
synchronized (this) {
...
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; //mBlocked=true表示線程已被掛起
} 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;
}
通過上面代碼我們可以看出MessageQueue
是通過單鏈表的方式循環遍歷找到p.next
為空的Message
對象來插入消息,接下來看看next
方法的實現
Message next() {
...
int pendingIdleHandlerCount = -1; //空閑的handler個數。只有在第一次循環的時候值為-1。
int nextPollTimeoutMillis = 0; //下次輪詢時間,如果當前消息隊列中沒有消息,它要等待,為0,表示不等待,不為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) { //判斷時間是否可以處理這個消息,如果符合條件,把消息返回傳給looper處理。否則,算出需要等待時間,等待到該時間,然后執行
// 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 (false) Log.v("MessageQueue", "Returning message: " + msg);
return msg;
}
} else {
// 如果msg為null則吧nextPollTimeoutMillis賦值為-1,表示等到下一個消息
nextPollTimeoutMillis = -1;
}
...
}
...
}
}
可以看出next
方法中有一個無限循環的代碼塊在獲取message
,如果有新消息則將詳細從鏈表中移除并返回這條消息,如果消息隊列中沒有消息那么next
方法會一直阻塞在這里。
3.Looper工作原理
Looper
主要作用是循環從MessageQueue
取出消息處理,如果沒有新的消息則會阻塞,它的構造方法中會創建一個MessageQueue
對象,并獲取當前現成對象的引用
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
Handler
的創建必須在含有Looper
的線程中,否則會報錯,Looper
的創建可調用Looper.prepare()
,主線程中會在ActivityThread
的main()
方法中調用Looper.prepareMainLooper()
方法為主線程創建Looper
對象,所以在主線程中創建Handler
對象是不需要我們顯示的創建Looper
對象,在工作線程中創建線程如下所示
new Thread() {
@Override
public void run() {
Looper.prepare(); //創建Looper對象
Handler handler = new Handler(); //創建Handler對象
Looper.loop(); //開啟循環
}
}
只有點用loop()
方法消息循環才會起作用,loop
方法的實現如下
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) { //只有queue.next()返回為null才會跳出循環,MessageQueue只有退出next才會返回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.recycleUnchecked();
}
}
loop()
中是一個死循環,只有queue.next()
返回為null
才會跳出循環,MessageQueue
只有退出next()
才會返回null
,否則有新消息則會返回消息,沒有消息則會阻塞。獲取到新消息會掉用msg.target.dispatchMessage(msg);
來處理消息,msg.target
是發送這條消息的Handler對象,這樣就達到了誰發送的消息誰處理的效果。