
前言
為什么要老藥換新湯
作為Android中 至關重要 的機制之一,十多年來,分析它的文章不斷,大量的內容已經被挖掘過了,所以:
-
已經對這一機制熟稔于心的讀者,在這篇文章中,看不到新東西了,
-
但對于還不太熟悉訊息機制的讀者,可以在文章的基礎上,繼續挖一挖,
一般,諸如此類有關Android的訊息機制的文章,經過簡單的檢索和分析,大部分是圍繞:
-
Handler,Looper,MQ的關系
-
上層的Handler,Looper、MQ 原始碼分析
展開的,單純的從這些角度學習的話,并不能 完全理解 訊息機制,
這篇文章本質還是一次腦暴 ,一來:避免腦暴跑偏 ,二來:幫助讀者 捋清內容脈絡 ,先放出腦圖:

腦暴:OS解決行程間通信問題
程式世界中,存在著大量的 通信 場景,搜索我們的知識,解決 行程間通信 問題有以下幾種方式:
這段內容可以泛讀,了解就行,不影響往下閱讀
管道
-
普通管道pipe:一種 半雙工 的通信方式,資料只能 單向流動 ,而且只能在具有 親緣關系 的行程間使用,
-
命令流管道s_pipe: 全雙工,可以同時雙向傳輸
-
命名管道FIFO:半雙工 的通信方式,允許 在 無親緣關系 的行程間通信,
訊息佇列 MessageQueue:
訊息的鏈表,存放在內核 中 并由 訊息佇列識別符號 標識,訊息佇列克服了 信號傳遞資訊少、管道 只能承載 無格式位元組流 以及 緩沖區大小受限 等缺點,
共享存盤 SharedMemory:
映射一段 能被其他行程所訪問 的記憶體,這段共享記憶體由 一個行程創建,但 多個行程都可以訪問,共享記憶體是 最快的 IPC 方式,它是針對 其他 行程間通信方式 運行效率低 而專門設計的,往往與其他通信機制一同使用,如 信號量 配合使用,來實作行程間的同步和通信,
信號量 Semaphore:
是一個 計數器 ,可以用來控制多個行程對共享資源的訪問,它常作為一種 鎖機制,防止某行程正在訪問共享資源時, 其他行程也訪問該資源,實作 資源的行程獨占,因此,主要作為 行程間 以及 同一行程內執行緒間 的同步手段,
套接字Socket:
與其他通信機制不同的是,它可以 通過網路 ,在 不同機器之間 進行行程通信,
信號 signal:
用于通知接收行程 某事件已發生,機制比較復雜,
我們可以想象,Android之間也有大量的 行程間通信場景,OS必須采用 至少一種 機制,以實作行程間通信,
仔細研究下去,我們發現,Android OS用了不止一種方式,而且,Android 還基于 OpenBinder 開發了 Binder 用于 用戶空間 內的行程間通信,
這里我們留一個問題以后探究:
Android 有沒有使用 Linux內核中的MessageQueue機制 干事情
基于訊息佇列的訊息機制設計有很多優勢,Android 在很多通信場景內,采用了這一設計思路,
訊息機制的三要素
不管在哪,我們談到訊息機制,都會有這三個要素:
-
訊息佇列
-
訊息回圈(分發)
-
訊息處理
訊息佇列 ,是 訊息物件 的佇列,基本規則是 FIFO,
訊息回圈(分發), 基本是通用的機制,利用 死回圈 不斷的取出訊息佇列頭部的訊息,派發執行
訊息處理,這里不得不提到 訊息 有兩種形式:
-
Enrichment 自身資訊完備
-
Query-Back 自身資訊不完備,需要回查
這兩者的取舍,主要看系統中 生成訊息的開銷 和 回查資訊的開銷 兩者的博弈,
在資訊完備后,接收者即可處理訊息,
Android Framework
Android 的Framework中的訊息佇列有兩個:
Java層 frameworks/base/core/java/android/os/MessageQueue.java
Native層 frameworks/base/core/jni/android_os_MessageQueue.cpp
Java層的MQ并不是 List 或者 Queue 之類的 Jdk內的資料結構實作,
Native層的原始碼我下載了一份 Android 10 的 原始碼(https://github.com/leobert-lan/Blog/blob/main/Android/Mechanism/Message/code/android_os_MessageQueue.cpp) ,并不長,大家可以完整的讀一讀,
并不難理解:用戶空間 會接收到來自 內核空間 的 訊息 , 從 下圖 我們可知,這部分訊息先被 Native層 獲知,所以:
-
通過 Native層 建立訊息佇列,它擁有訊息佇列的各種基本能力
-
利用JNI 打通 Java層 和 Native層 的 Runtime屏障,在Java層 映射 出訊息佇列
-
應用建立在Java層之上,在Java層中實作訊息的 分發 和 處理
PS:在Android 2.3那個時代,訊息佇列的實作是在Java層的,至于10年前為何改成了 native實作, 推測和CPU空轉有關,筆者沒有繼續探究下去,如果有讀者了解,希望可以留言幫我解惑,

PS:還有一張經典的 系統啟動架構圖 沒有找到,這張圖更加直觀
代碼決議
我們簡單的 閱讀、分析 下Native中的MQ原始碼
Native層訊息佇列的創建:
static jlong android\_os\_MessageQueue\_nativeInit(JNIEnv\* env, jclass clazz) {
NativeMessageQueue\* nativeMessageQueue = new NativeMessageQueue();
if (!nativeMessageQueue) {
jniThrowRuntimeException(env, "Unable to allocate native queue");
return 0;
}
nativeMessageQueue->incStrong(env);
return reinterpret\_cast<jlong>(nativeMessageQueue);
}
很簡單,創建一個Native層的訊息佇列,如果創建失敗,拋例外資訊,回傳0,否則將指標轉換為Java的long型值回傳,當然,會被Java層的MQ所持有,
NativeMessageQueue 類的建構式
NativeMessageQueue::NativeMessageQueue() :
mPollEnv(NULL), mPollObj(NULL), mExceptionObj(NULL) {
mLooper = Looper::getForThread();
if (mLooper == NULL) {
mLooper = new Looper(false);
Looper::setForThread(mLooper);
}
}
這里的Looper是native層Looper,通過靜態方法 Looper::getForThread() 獲取物件實體,如果未獲取到,則創建實體,并通過靜態方法設定,
看一下Java層MQ中會使用到的native方法
class MessageQueue {
private long mPtr; // used by native code
private native static long nativeInit();
private native static void nativeDestroy(long ptr);
private native void nativePollOnce(long ptr, int timeoutMillis); /\*non-static for callbacks\*/
private native static void nativeWake(long ptr);
private native static boolean nativeIsPolling(long ptr);
private native static void nativeSetFileDescriptorEvents(long ptr, int fd, int events);
}
對應簽名:
static const JNINativeMethod gMessageQueueMethods\[\] = {
/\* name, signature, funcPtr \*/
{ "nativeInit", "()J", (void\*)android\_os\_MessageQueue\_nativeInit },
{ "nativeDestroy", "(J)V", (void\*)android\_os\_MessageQueue\_nativeDestroy },
{ "nativePollOnce", "(JI)V", (void\*)android\_os\_MessageQueue\_nativePollOnce },
{ "nativeWake", "(J)V", (void\*)android\_os\_MessageQueue\_nativeWake },
{ "nativeIsPolling", "(J)Z", (void\*)android\_os\_MessageQueue\_nativeIsPolling },
{ "nativeSetFileDescriptorEvents", "(JII)V",
(void\*)android\_os\_MessageQueue\_nativeSetFileDescriptorEvents },
};
mPtr 是Native層MQ的記憶體地址在Java層的映射,
-
Java層判斷MQ是否還在作業:
private boolean isPollingLocked() {
// If the loop is quitting then it must not be idling.
// We can assume mPtr != 0 when mQuitting is false.
return !mQuitting && nativeIsPolling(mPtr);
}
static jboolean android\_os\_MessageQueue\_nativeIsPolling(JNIEnv\* env, jclass clazz, jlong ptr) {
NativeMessageQueue\* nativeMessageQueue = reinterpret\_cast<NativeMessageQueue\*>(ptr);
return nativeMessageQueue->getLooper()->isPolling();
}
/\*\*
\* Returns whether this looper's thread is currently polling for more work to do.
\* This is a good signal that the loop is still alive rather than being stuck
\* handling a callback. Note that this method is intrinsically racy, since the
\* state of the loop can change before you get the result back.
\*/
bool isPolling() const;
-
喚醒 Native層MQ:
static void android\_os\_MessageQueue\_nativeWake(JNIEnv\* env, jclass clazz, jlong ptr) {
NativeMessageQueue\* nativeMessageQueue = reinterpret\_cast<NativeMessageQueue\*>(ptr);
nativeMessageQueue->wake();
}
void NativeMessageQueue::wake() {
mLooper->wake();
}
-
Native層Poll:
static void android\_os\_MessageQueue\_nativePollOnce(JNIEnv\* env, jobject obj,
jlong ptr, jint timeoutMillis) {
NativeMessageQueue\* nativeMessageQueue = reinterpret\_cast<NativeMessageQueue\*>(ptr);
nativeMessageQueue->pollOnce(env, obj, timeoutMillis);
}
void NativeMessageQueue::pollOnce(JNIEnv\* env, jobject pollObj, int timeoutMillis) {
mPollEnv = env;
mPollObj = pollObj;
mLooper->pollOnce(timeoutMillis);
mPollObj = NULL;
mPollEnv = NULL;
if (mExceptionObj) {
env->Throw(mExceptionObj);
env->DeleteLocalRef(mExceptionObj);
mExceptionObj = NULL;
}
}
這里比較重要,我們先大概看下 Native層的Looper是 如何分發訊息 的
//Looper.h
int pollOnce(int timeoutMillis, int\* outFd, int\* outEvents, void\*\* outData);
inline int pollOnce(int timeoutMillis) {
return pollOnce(timeoutMillis, NULL, NULL, NULL);
}
//實作
int Looper::pollOnce(int timeoutMillis, int\* outFd, int\* outEvents, void\*\* outData) {
int result = 0;
for (;;) {
while (mResponseIndex < mResponses.size()) {
const Response& response = mResponses.itemAt(mResponseIndex++);
int ident = response.request.ident;
if (ident >= 0) {
int fd = response.request.fd;
int events = response.events;
void\* data = https://www.cnblogs.com/BlueSocks/p/response.request.data;
#if DEBUG/_POLL/_AND/_WAKE
ALOGD("%p ~ pollOnce - returning signalled identifier %d: "
"fd=%d, events=0x%x, data=https://www.cnblogs.com/BlueSocks/p/%p",
this, ident, fd, events, data);
#endif
if (outFd != NULL) \*outFd = fd;
if (outEvents != NULL) \*outEvents = events;
if (outData != NULL) \*outData = https://www.cnblogs.com/BlueSocks/p/data;
return ident;
}
}
if (result != 0) {
#if DEBUG/_POLL/_AND/_WAKE
ALOGD("%p ~ pollOnce - returning result %d", this, result);
#endif
if (outFd != NULL) \*outFd = 0;
if (outEvents != NULL) \*outEvents = 0;
if (outData != NULL) \*outData = https://www.cnblogs.com/BlueSocks/p/NULL;
return result;
}
result = pollInner(timeoutMillis);
}
}
先處理Native層滯留的Response,然后呼叫pollInner,這里的細節比較復雜,稍后我們在 Native Looper決議 中進行腦暴,
先于此處細節分析,我們知道,呼叫一個方法,這是阻塞的 ,用大白話描述即在方法回傳前,呼叫者在 等待,
Java層調動 native void nativePollOnce(long ptr, int timeoutMillis); 程序中是阻塞的,
此時我們再閱讀下Java層MQ的訊息獲取:代碼比較長,直接在代碼中進行要點注釋,
在看之前,我們先單純從 TDD的角度 思考下,有哪些 主要場景 :當然,這些場景不一定都合乎Android現有的設計
訊息佇列是否在作業中
-
作業中,期望回傳訊息
-
不作業,期望回傳null
作業中的訊息佇列 當前 是否有訊息
-
特殊的 內部功能性訊息,期望MQ內部自行處理
-
已經到處理時間的訊息, 回傳訊息
-
未到處理時間,如果都是排過序的,期望 空轉保持阻塞 or 回傳靜默并設定喚醒?按照前面的討論,是期望 保持空轉
-
不存在訊息,阻塞 or 回傳null?-- 如果回傳null,則在外部需要需要 保持空轉 或者 喚醒機制,以支持正常運作,從封裝角度出發,應當 保持空轉,自己解決問題
-
存在訊息
class MessageQueue {
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.
// 1. 如果 native訊息佇列指標映射已經為0,即虛參考,說明訊息佇列已經退出,沒有訊息了,
// 則回傳 null
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
// 2. 死回圈,當為獲取到需要 \`分發處理\` 的訊息時,保持空轉
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
// 3. 呼叫native層方法,poll message,注意,訊息還存在于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;
//4. 如果發現 barrier ,即同步屏障,則尋找佇列中的下一個可能存在的異步訊息
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) {
// 5. 發現了訊息,
// 如果是還沒有到約定時間的訊息,則設定一個 \`下次喚醒\` 的最大時間差
// 否則 \`維護單鏈表資訊\` 并回傳訊息
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;
}
// 處理 是否需要 停止訊息佇列
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}
// 維護 接下來需要處理的 IDLEHandler 資訊,
// 如果沒有 IDLEHandler,則直接進入下一輪訊息獲取環節
// 否則處理 IDLEHandler
// If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler\[Math.max(pendingIdleHandlerCount, 4)\];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
// 處理 IDLEHandler
// Run the idle handlers.
// We only ever reach this code block during the first iteration.
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers\[i\];
mPendingIdleHandlers\[i\] = null; // release the reference to the handler
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
// Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0;
// While calling an idle handler, a new message could have been delivered
// so go back and look again for a pending message without waiting.
nextPollTimeoutMillis = 0;
}
}
}
-
Java層壓入訊息
這就比較簡單了,當訊息本身合法,且訊息佇列還在作業中時,依舊從 TDD角度 出發:
如果訊息佇列沒有頭,期望直接作為頭
如果有頭
-
訊息處理時間 先于 頭訊息 或者是需要立即處理的訊息,則作為新的頭
-
否則按照 處理時間 插入到合適位置
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
synchronized (this) {
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
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;
}
同步屏障 barrier后面單獨腦暴, 其他部分就先不看了
Java層訊息分發
這一節開始,我們腦暴訊息分發,前面我們已經看過了 MessageQueue ,訊息分發就是 不停地 從 MessageQueue 中取出訊息,并指派給處理者, 完成這一作業的,是Looper,
在前面,我們已經知道了,Native層也有Looper,但是不難理解:
-
訊息佇列需要 橋梁 連通 Java層和Native層
-
Looper只需要 在自己這一端,處理自己的訊息佇列分發即可
所以,我們看Java層的訊息分發時,看Java層的Looper即可,關注三個主要方法:
-
出門上班
-
作業
-
下班回家
-
出門上班 prepare
class Looper {
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就夠了,只要它還活著,就沒必要再建一個,
-
責任到人,一個Looper服務于一個Thread,這需要 注冊 ,代表著 某個Thread 已經由自己服務了,利用了ThreadLocal,因為多執行緒訪問集合,總需要考慮
競爭,這很不人道主義,干脆分家,每個Thread操作自己的內容互不干擾,也就沒有了競爭,于是封裝了 ThreadLocal
-
上班 loop
注意作業性質是 分發,并不需要自己處理
-
沒有 注冊 自然就找不到負責這份作業的人,
-
已經在作業了就不要催,催了會導致作業出錯,順序出現問題,
-
作業就是不斷的取出 老板-- MQ 的 指令 -- Message,并交給 相關負責人 -- Handler 去處理,并記錄資訊
-
007,不眠不休,當MQ再也不發出訊息了,沒活干了,大家都散了吧,下班回家
class 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.");
}
if (me.mInLoop) {
Slog.w(TAG, "Loop again would have the queued messages be executed"
+ " before this one completed.");
}
me.mInLoop = true;
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 traceTag = me.mTraceTag;
long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
if (thresholdOverride > 0) {
slowDispatchThresholdMs = thresholdOverride;
slowDeliveryThresholdMs = thresholdOverride;
}
final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);
final boolean needStartTime = logSlowDelivery || logSlowDispatch;
final boolean needEndTime = logSlowDispatch;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
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);
}
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} catch (Exception exception) {
if (observer != null) {
observer.dispatchingThrewException(token, msg, exception);
}
throw exception;
} finally {
ThreadLocalWorkSource.restore(origWorkSource);
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (logSlowDelivery) {
if (slowDeliveryDetected) {
if ((dispatchStart - msg.when) <= 10) {
Slog.w(TAG, "Drained");
slowDeliveryDetected = false;
}
} else {
if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
msg)) {
// Once we write a slow delivery log, suppress until the queue drains.
slowDeliveryDetected = true;
}
}
}
if (logSlowDispatch) {
showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", 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();
}
}
}
-
下班 quit/quitSafely
這是比較粗暴的行為,MQ離開了Looper就沒法正常作業了,即下班即意味著辭職
class Looper {
public void quit() {
mQueue.quit(false);
}
public void quitSafely() {
mQueue.quit(true);
}
}
/ Handler /
這里就比較清晰了,API基本分為以下幾類:
-
面向使用者:
-
創建Message,通過Message的 享元模式
-
發送訊息,注意postRunnable也是一個訊息
-
移除訊息,
-
退出等
面向訊息處理:
class Handler {
/\*\*
\* Subclasses must implement this to receive messages.
\*/
public void handleMessage(@NonNull Message msg) {
}
/\*\*
\* Handle system messages here.
\* Looper分發時呼叫的API
\*/
public void dispatchMessage(@NonNull Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
}
如果有 Handler callback,則交給callback處理,否則自己處理,如果沒覆寫 handleMessage ,訊息相當于被 drop 了,
訊息發送部分可以結合下圖梳理:

階段性小結,至此,我們已經對 Framework層的訊息機制 有一個完整的了解了, 前面我們梳理了:
-
Native層 和 Java層均有訊息佇列,并且通過JNI和指標映射,存在對應關系
-
Native層 和 Java層MQ 訊息獲取時的大致程序
-
Java層 Looper 如何作業
-
Java層 Handler 大致概覽
根據前面梳理的內容,可以總結:從 Java Runtime 看:
-
訊息佇列機制服務于 執行緒級別,即一個執行緒有一個作業中的訊息佇列即可,當然,也可以沒有,
-
即,一個Thread 至多有 一個作業中的Looper,
-
Looper 和 Java層MQ 一一對應
-
Handler 是MQ的入口,也是 訊息 的處理者
-
訊息-- Message 應用了 享元模式,自身資訊足夠,滿足 自洽,創建訊息的開銷性對較大,所以利用享元模式對訊息物件進行復用,
下面我們再繼續探究細節,解決前面語焉不詳處留下的疑惑:
-
訊息的型別和本質
-
Native層Looper 的pollInner
型別和本質
message中的幾個重要成員變數:
class Message {
public int what;
public int arg1;
public int arg2;
public Object obj;
public Messenger replyTo;
/\*package\*/ int flags;
public long when;
/\*package\*/ Bundle data;
/\*package\*/ Handler target;
/\*package\*/ Runnable callback;
}
其中 target是 目標,如果沒有目標,那就是一個特殊的訊息: 同步屏障 即 barrier;
what 是訊息標識 arg1 和 arg2 是開銷較小的 資料,如果 不足以表達資訊 則可以放入 Bundle data 中,
replyTo 和 obj 是跨行程傳遞訊息時使用的,暫且不看,
flags 是 message 的狀態標識,例如 是否在使用中,是否是同步訊息
上面提到的同步屏障,即 barrier,其作用是攔截后面的 同步訊息 不被獲取,在前面閱讀Java層MQ的next方法時讀到過,
我們還記得,next方法中,使用死回圈,嘗試讀出一個滿足處理條件的訊息,如果取不到,因為死回圈的存在,呼叫者(Looper)會被一直阻塞,
此時可以印證一個結論,訊息按照 功能分類 可以分為 三種:
-
普通訊息
-
同步屏障訊息
-
異步訊息
其中同步訊息是一種內部機制,設定屏障之后需要在合適時間取消屏障,否則會導致 普通訊息永遠無法被處理,而取消時,需要用到設定屏障時回傳的token,
Native層Looper
相信大家都對 Native層 的Looper產生興趣了,想看看它在Native層都干些什么,
對完整原始碼感興趣的可以看 這里(https://github.com/leobert-lan/Blog/blob/main/Android/Mechanism/Message/code/Looper.cpp) ,下面我們節選部分進行閱讀,
前面提到了Looper的pollOnce,處理完擱置的Response之后,會呼叫pollInner獲取訊息
int Looper::pollInner(int timeoutMillis) {
#if DEBUG\_POLL\_AND\_WAKE
ALOGD("%p ~ pollOnce - waiting: timeoutMillis=%d", this, timeoutMillis);
#endif
// Adjust the timeout based on when the next message is due.
if (timeoutMillis != 0 && mNextMessageUptime != LLONG\_MAX) {
nsecs\_t now = systemTime(SYSTEM\_TIME\_MONOTONIC);
int messageTimeoutMillis = toMillisecondTimeoutDelay(now, mNextMessageUptime);
if (messageTimeoutMillis >= 0
&& (timeoutMillis < 0 || messageTimeoutMillis < timeoutMillis)) {
timeoutMillis = messageTimeoutMillis;
}
#if DEBUG\_POLL\_AND\_WAKE
ALOGD("%p ~ pollOnce - next message in %lldns, adjusted timeout: timeoutMillis=%d",
this, mNextMessageUptime - now, timeoutMillis);
#endif
}
// Poll.
int result = ALOOPER\_POLL\_WAKE;
mResponses.clear();
mResponseIndex = 0;
struct epoll\_event eventItems\[EPOLL\_MAX\_EVENTS\];
//注意 1
int eventCount = epoll\_wait(mEpollFd, eventItems, EPOLL\_MAX\_EVENTS, timeoutMillis);
// Acquire lock.
mLock.lock();
// 注意 2
// Check for poll error.
if (eventCount < 0) {
if (errno == EINTR) {
goto Done;
}
ALOGW("Poll failed with an unexpected error, errno=%d", errno);
result = ALOOPER\_POLL\_ERROR;
goto Done;
}
// 注意 3
// Check for poll timeout.
if (eventCount == 0) {
#if DEBUG\_POLL\_AND\_WAKE
ALOGD("%p ~ pollOnce - timeout", this);
#endif
result = ALOOPER\_POLL\_TIMEOUT;
goto Done;
}
//注意 4
// Handle all events.
#if DEBUG\_POLL\_AND\_WAKE
ALOGD("%p ~ pollOnce - handling events from %d fds", this, eventCount);
#endif
for (int i = 0; i < eventCount; i++) {
int fd = eventItems\[i\].data.fd;
uint32\_t epollEvents = eventItems\[i\].events;
if (fd == mWakeReadPipeFd) {
if (epollEvents & EPOLLIN) {
awoken();
} else {
ALOGW("Ignoring unexpected epoll events 0x%x on wake read pipe.", epollEvents);
}
} else {
ssize\_t requestIndex = mRequests.indexOfKey(fd);
if (requestIndex >= 0) {
int events = 0;
if (epollEvents & EPOLLIN) events |= ALOOPER\_EVENT\_INPUT;
if (epollEvents & EPOLLOUT) events |= ALOOPER\_EVENT\_OUTPUT;
if (epollEvents & EPOLLERR) events |= ALOOPER\_EVENT\_ERROR;
if (epollEvents & EPOLLHUP) events |= ALOOPER\_EVENT\_HANGUP;
pushResponse(events, mRequests.valueAt(requestIndex));
} else {
ALOGW("Ignoring unexpected epoll events 0x%x on fd %d that is "
"no longer registered.", epollEvents, fd);
}
}
}
Done: ;
// 注意 5
// Invoke pending message callbacks.
mNextMessageUptime = LLONG\_MAX;
while (mMessageEnvelopes.size() != 0) {
nsecs\_t now = systemTime(SYSTEM\_TIME\_MONOTONIC);
const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(0);
if (messageEnvelope.uptime <= now) {
// Remove the envelope from the list.
// We keep a strong reference to the handler until the call to handleMessage
// finishes. Then we drop it so that the handler can be deleted \*before\*
// we reacquire our lock.
{ // obtain handler
sp<MessageHandler> handler = messageEnvelope.handler;
Message message = messageEnvelope.message;
mMessageEnvelopes.removeAt(0);
mSendingMessage = true;
mLock.unlock();
#if DEBUG\_POLL\_AND\_WAKE || DEBUG\_CALLBACKS
ALOGD("%p ~ pollOnce - sending message: handler=%p, what=%d",
this, handler.get(), message.what);
#endif
handler->handleMessage(message);
} // release handler
mLock.lock();
mSendingMessage = false;
result = ALOOPER\_POLL\_CALLBACK;
} else {
// The last message left at the head of the queue determines the next wakeup time.
mNextMessageUptime = messageEnvelope.uptime;
break;
}
}
// Release lock.
mLock.unlock();
//注意 6
// Invoke all response callbacks.
for (size\_t i = 0; i < mResponses.size(); i++) {
Response& response = mResponses.editItemAt(i);
if (response.request.ident == ALOOPER\_POLL\_CALLBACK) {
int fd = response.request.fd;
int events = response.events;
void\* data = https://www.cnblogs.com/BlueSocks/p/response.request.data;
#if DEBUG/_POLL/_AND/_WAKE || DEBUG/_CALLBACKS
ALOGD("%p ~ pollOnce - invoking fd event callback %p: fd=%d, events=0x%x, data=https://www.cnblogs.com/BlueSocks/p/%p",
this, response.request.callback.get(), fd, events, data);
#endif
int callbackResult = response.request.callback->handleEvent(fd, events, data);
if (callbackResult == 0) {
removeFd(fd);
}
// Clear the callback reference in the response structure promptly because we
// will not clear the response vector itself until the next poll.
response.request.callback.clear();
result = ALOOPER\_POLL\_CALLBACK;
}
}
return result;
}
上面標記了注意點
-
1 epoll機制,等待 mEpollFd 產生事件, 這個等待具有超時時間,
-
2,3,4 是等待的三種結果,goto 陳述句可以直接跳轉到 標記 處
-
2 檢測poll 是否出錯,如果有,跳轉到 Done
-
3 檢測pool 是否超時,如果有,跳轉到 Done
-
4 處理epoll后所有的事件
-
5 處理 pending 訊息的回呼
-
6 處理 所有 Response的回呼
并且我們可以發現回傳的結果有以下幾種:
- ALOOPER_POLL_CALLBACK
有 pending message 或者 request.ident 值為 ALOOPER_POLL_CALLBACK 的 Response被處理了, 如果沒有:
-
ALOOPER_POLL_WAKE 正常喚醒
-
ALOOPER_POLL_ERROR epoll錯誤
-
ALOOPER_POLL_TIMEOUT epoll超時
查找了一下列舉值:
ALOOPER\_POLL\_WAKE = -1,
ALOOPER\_POLL\_CALLBACK = -2,
ALOOPER\_POLL\_TIMEOUT = -3,
ALOOPER\_POLL\_ERROR = -4
階段性小結, 我們對 訊息 和 Native層的pollInner 進行了一次腦暴,引出了epoll機制,
其實Native層的 Looper分發還有不少值得腦暴的點,但我們先緩緩,已經迫不及待的要對 epoll機制進行腦暴了,
腦暴:Linux中的I/O模型
PS:本段中,存在部分圖片直接參考自該文,我偷了個懶,沒有去找原版內容并標記出處
阻塞I/O模型圖:在呼叫recv()函式時,發生在內核中等待資料和復制資料的程序

實作非常的 簡單,但是存在一個問題,阻塞導致執行緒無法執行其他任何計算,如果是在網路編程背景下,需要使用多執行緒提高處理并發的能力,
注意,不要用 Android中的 點擊螢屏等硬體被觸發事件 去對應這里的 網路并發,這是兩碼事,
如果采用了 多行程 或者 多執行緒 實作 并發應答,模型如下:

到這里,我們看的都是 I/O 阻塞 模型,
腦暴,阻塞為呼叫方法后一直在等待回傳值,執行緒內執行的內容就像 卡頓 在這里,
如果要消除這種卡頓,那就不能呼叫方法等待I/O結果,而是要 立即回傳 !舉個例子:
-
去西裝店定制西裝,確定好款式和尺寸后,你坐在店里一直等著,等到做好了拿給你,這就是阻塞型的,這能等死你;
-
去西裝店定制西裝,確定好款式和尺寸后,店員告訴你別干等著,好多天呢,等你有空了來看看,這就是非阻塞型的,
改變為非阻塞模型后,應答模型如下:

不難理解,這種方式需要顧客去 輪詢 ,對客戶不友好,但是對店家可是一點損失都沒有,還讓等候區沒那么擠了,
有些西裝店進行了改革,對客戶更加友好了:
去西裝店定制西裝,確定好款式和尺寸后,留下聯系方式,等西服做好了聯系客戶,讓他來取,
這就變成了 select or poll 模型:

注意:進行改革的西裝店需要增加一個員工,圖中標識的用戶執行緒,他的作業是:
-
在前臺記錄客戶訂單和聯系方式
-
拿記錄著 訂單 的小本子去找制作間,不斷檢查 訂單是否完工,完工的就可以提走并聯系客戶了,
而且,他去看訂單完工時,無法在前臺記錄客戶資訊,這意味他 阻塞 了,其他作業只能先擱置著,
這個做法,對于制作間而言,和 非阻塞模型 并沒有多大區別,還增加了一個店員,但是,用 一個店員 就解決了之前 很多店員 都會跑去 制作間 幫客戶問"訂單好了沒有?" 的問題,
值得一提的是,為了提高服務質量,這個員工每次去制作間詢問一個訂單時,都需要記錄一些資訊:
-
訂單完成度詢問時,是否被應答;
-
應答有沒有說謊;等
有些店對每種不同的考核項均準備了記錄冊,這和 select模型類似
有些店只用一本記錄冊,但是冊子上可以利用表格記錄各種考核項,這和 poll 模型類似
select 模型 和 poll 模型的近似度比較高,
沒多久,老板就發現了,這個店員的作業效率有點低下,他每次都要拿著一本訂單簿,去把訂單都問一遍,倒不是員工不勤快,是這個模式有點問題,
于是老板又進行了改革:
-
在 前臺 和 制作間 之間加一個送信管道,
-
制作間有進度需要匯報了,就送一份信到前臺,信上寫著訂單號,
-
前臺員工直接去問對應的訂單,
這就變成了 epoll模型解決了 select/poll 模型的遍歷效率問題,
這樣改革后,前臺員工就不再需要按著訂單簿從上到下挨個問了,提高了效率,前臺員工只要無事發生,就可以優雅的劃水了,
我們看一下NativeLooper的建構式:
Looper::Looper(bool allowNonCallbacks) :
mAllowNonCallbacks(allowNonCallbacks), mSendingMessage(false),
mResponseIndex(0), mNextMessageUptime(LLONG\_MAX) {
int wakeFds\[2\];
int result = pipe(wakeFds);
LOG\_ALWAYS\_FATAL\_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
mWakeReadPipeFd = wakeFds\[0\];
mWakeWritePipeFd = wakeFds\[1\];
result = fcntl(mWakeReadPipeFd, F\_SETFL, O\_NONBLOCK);
LOG\_ALWAYS\_FATAL\_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
errno);
result = fcntl(mWakeWritePipeFd, F\_SETFL, O\_NONBLOCK);
LOG\_ALWAYS\_FATAL\_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
errno);
// Allocate the epoll instance and register the wake pipe.
mEpollFd = epoll\_create(EPOLL\_SIZE\_HINT);
LOG\_ALWAYS\_FATAL\_IF(mEpollFd < 0, "Could not create epoll instance. errno=%d", errno);
struct epoll\_event eventItem;
memset(& eventItem, 0, sizeof(epoll\_event)); // zero out unused members of data field union
eventItem.events = EPOLLIN;
eventItem.data.fd = mWakeReadPipeFd;
result = epoll\_ctl(mEpollFd, EPOLL\_CTL\_ADD, mWakeReadPipeFd, & eventItem);
LOG\_ALWAYS\_FATAL\_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
errno);
}
總結
相信看到這里,大家已經自己悟透了各種問題,按照慣例,還是要總結下,因為 這篇是腦暴,所以 思緒 是比較 跳躍 的,內容前后關系不太明顯,
我們結合一個問題來點明內容前后關系,
Java層 Looper和MQ 會什么使用了死回圈但是 不會"阻塞"UI執行緒 / 沒造成ANR / 依舊可以回應點擊事件
-
Android是基于 事件驅動 的,并建立了 完善的 訊息機制
-
Java層的訊息機制只是一個區域,其負責的就是面向訊息佇列,處理 訊息佇列管理,訊息分發,訊息處理
-
Looper的死回圈保障了 訊息佇列 的 訊息分發 一直處于有效運行中,不回圈就停止了分發,
-
MessageQueue的 死回圈 保障了 Looper可以獲取有效的訊息,保障了Looper 只要有訊息,就一直運行,發現有效訊息,就跳出了死回圈,
-
而且Java層MessageQueue在 next() 方法中的死回圈中,通過JNI呼叫了 Native層MQ的 pollOnce,驅動了Native層去處理Native層訊息
-
值得一提的是,UI執行緒處理的事情也都是基于訊息的,無論是更新UI還是回應點擊事件等,
所以,正是Looper 進行loop()之后的死回圈,保障了UI執行緒的各項作業正常執行,
再說的ANR,這是Android 確認主執行緒 訊息機制 正常 且 健康 運轉的一種檢測機制,
因為主執行緒Looper需要利用 訊息機制 驅動UI渲染和互動事件處理, 如果某個訊息的執行,或者其衍生出的業務,在主執行緒占用了大量的時間,導致主執行緒長期阻塞,會影響用戶體驗,
所以ANR檢測采用了一種 埋定時炸彈 的機制,必須依靠Looper的高效運轉來消除之前裝的定時炸彈,而這種定時炸彈比較有意思,被發現了才會炸,
在說到 回應點擊事件,類似的事件總是從硬體出發的,在到內核,再行程間通信到用戶空間,這些事件以訊息的形式存在于Native層,經過處理后,表現出:
ViewRootImpl收到了InputManager的輸入,并進行了事件處理
這里我們借用一張圖總結整個訊息機制流程:

最后,喜歡的朋友可以點個關注,覺得本文不錯的朋友可以點個贊,你的支持就是我更新最大的動力,
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/458055.html
標籤:Android
