Android的消息機制主要是指Handler的運行機制,Handler的主要作用是將一個任務切換到某個指定的線程中去執行,在實際開發中,通常用來在子線程切換到UI線程更新UI;
完整的Hanlder使用方式是這樣的:
class HanlderThread extends Thread{
Handler mHandler;
@Override
public void run() {
Looper.prepare();
mHandler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
//接受處理消息
}
};
Looper.loop();
}
}
爲何要加 Looper.prepare()? 先看到Handler的構造方法:
public Handler(@Nullable 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 " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
其中有一個判斷, if (mLooper == null)則拋異常,也就是說創建Handler之前必須創建Looper,那麼爲什麼我們平時使用的時候並沒有看到Looper,那是因爲在主線程中已經創建了Looper。
一、Looper
首先看到Looper對象是通過prepare()方法生成的:
public static void prepare() {
prepare(true);
}
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是否已經存在,如果不存在則new一個,並保存在sThreadLocal中;sThreadLocal是一個ThreadLocal的變量,ThreadLocal是一個線程本地存儲去,用來在指定的線程中存儲數據,只有在指定的線程中可以獲取到存儲的數據;此處就是通過ThreadLocal將looper對象綁定到當前線程。所以通過looper就將Handler關聯到當前線程;
二、發送消息
創建了Handler對象,接下來就是發送消息了,通常的步驟是:
//構建message對象
Message message = Message.obtain();
message.what = 1;
message.obj = "我要發消息";
mHandler.sendMessage(message);
從Handler源碼可以看到,Handler發送消息的方式有send和post兩類;其中post方法會調用getPostMessage()方法,構建一個Message,並將傳入的Runnable賦值給Message.callabck變量。
最終都是調用sendMessageAtTime(Message msg, long uptimeMillis)方法:
public boolean sendMessageAtTime(@NonNull 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(@NonNull MessageQueue queue, @NonNull Message msg,
long uptimeMillis) {
msg.target = this;
msg.workSourceUid = ThreadLocalWorkSource.getUid();
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
可以看到先是創建了MessageQueue對象,這個MessageQueue來自Looper中 new MessageQueue(quitAllowed);
最後調用了MessageQueue的enqueueMessage(msg, uptimeMillis)方法:
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) {
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
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;
}
if (needWake) {
//next方法讀取消息時,觸發nativePollOnce方法結束等待
nativeWake(mPtr);
}
}
return true;
}
MessageQueue是一個單向鏈表的結構,發送消息後按照時間的先後順序排列;
三、獲取消息
消息發送後會開啓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();
// Allow overriding a threshold with a system prop. e.g.
// adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
final int thresholdOverride =
SystemProperties.getInt("log.looper."
+ Process.myUid() + "."
+ Thread.currentThread().getName()
+ ".slow", 0);
boolean slowDeliveryDetected = false;
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
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
// Make sure the observer won't change while processing a transaction.
final Observer observer = sObserver;
//省略部分無關代碼
......
final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
final long dispatchEnd;
Object token = null;
if (observer != null) {
token = observer.messageDispatchStarting();
}
long origWorkSource = ThreadLocalWorkSource.setUid(msg.workSourceUid);
try {
msg.target.dispatchMessage(msg);
if (observer != null) {
observer.messageDispatched(token, msg);
}
} catch (Exception exception) {
if (observer != null) {
observer.dispatchingThrewException(token, msg, exception);
}
throw exception;
} finally {
ThreadLocalWorkSource.restore(origWorkSource);
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
//省略部分無關代碼
......
msg.recycleUnchecked();
}
}
先拿到MessageQueue,然後進入死循環調用MessageQueue的next()方法去拿到消息;
Message next() {
//省略部分無關代碼
......
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
//native層處理等待
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;
}
//省略部分無關代碼
......
}
其中也是一個無限循環,去獲取Message,獲取之後會將該message從隊列中刪除,如果沒有message則掛起繼續等待下一個message到來。
獲取到message之後調用msg.target.dispatchMessage(msg)方法分發,其中msg.target就是當前Handler(在Handler的enqueueMessage方法中賦值),最終進入到Hanlder的dispatchMessage(msg)分發Message;
四、消息分發:
查看Hanlder的dispatchMessage(msg)方法:
public void dispatchMessage(@NonNull Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
可以看到分發的邏輯:
1、如果message的callback不爲null,則調用message.callback.run(),此處的callback就是post方法系列中傳入的Runnable,最終執行Runnable的run方法。
2、如果Handler的mCallback不爲null,則調用mCallback.handleMessage(msg);
3、最後調用Handler自身的handleMessage(msg)方法。
總結:
創建Handler對象,在創建Handler對象的時候需要先獲取Looper對象,Looper對象通過ThreadLocal與當前線程綁定,在Looper初始化的時候new MessageQueue;通過Handler的sendMessageAtTime 方法發送一個Message,然後調用MessageQueue的enqueueMessage方法按照時間先後順序插入到消息隊列;開啓loop方法無限循環從MessageQueue的next方法獲取Message,其中next方法也是通過無限循環從MessageQueue中取出Message,取出後將Message從MessageQueue中移除,如果沒有消息就堵塞等待下一個消息到來;取出Message後調用Handler的dispatchMessage方法分發。