前言
Handler
是什么?我們都知道秘蛇,Handler
是Android
內(nèi)部消息機(jī)制其做,它可以幫我們方便的實(shí)現(xiàn)線程間的通訊顶考。它在Android
系統(tǒng)中是非常重要的,所以明白其內(nèi)部實(shí)現(xiàn)原理是非常有必要的妖泄。
使用
要了解Handler
的內(nèi)部實(shí)現(xiàn)原理驹沿,我們可以從日常使用入手,一步一步來(lái)學(xué)習(xí)其內(nèi)部實(shí)現(xiàn)原理蹈胡。
我們平常使用Handler
渊季,一般都有以下幾步:
- 為
Handler
創(chuàng)建一個(gè)靜態(tài)類,內(nèi)部以弱引用的方式來(lái)持有對(duì)象的引用。這樣主要是為了防止Hnadler
出現(xiàn)內(nèi)存泄漏的問題罚渐。 - 構(gòu)建一個(gè)
Message
對(duì)象并通過Handler
的sendMessage(Message msg)
方法發(fā)送這個(gè)Message
對(duì)象却汉。 - 在
Handler
的handleMessage(msg: Message)
回調(diào)方法中處理。
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Handler mHandler=new MyHandler(this);
Message m=Message.obtain();
m.what=1;
mHandler.sendMessage(m);
}
private static class MyHandler extends Handler {
WeakReference<Activity> mWeakReference;
public MyHandler(Activity activity) {
mWeakReference = new WeakReference<Activity>(activity);
}
@Override
public void handleMessage(Message msg) {
final Activity activity = mWeakReference.get();
if (activity == null) {
return;
}
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(activity, String.valueOf(msg.what), Toast.LENGTH_SHORT).show();
}
});
}
}
-
Handler
在我們?nèi)粘J褂弥泻刹ⅲ畈欢嗑褪且陨蠋讉€(gè)步驟合砂,只不過Handler
除了可以通過sendMessage(Message msg)
方法發(fā)送Meesage
,Handler
也還有很多別的方法可以發(fā)送Message
璧坟,比如還可以post
一個(gè)Runnable
等等既穆,但其實(shí)它們本質(zhì)上是一樣的,最終都會(huì)調(diào)用Handler
的sendMessageAtTime(Message msg, long uptimeMillis)
方法雀鹃。
Handler的構(gòu)造方法
要明白Handler
的內(nèi)部原理幻工,第一步我們就需要看看Handler
的構(gòu)造方法。
private static final boolean FIND_POTENTIAL_LEAKS = false;
final Looper mLooper;
final MessageQueue mQueue;
final Callback mCallback;
final boolean mAsynchronous;
public Handler() {
this(null, false);
}
public Handler(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;
}
- 可以看出黎茎,我們調(diào)用
Handler
的無(wú)參構(gòu)造方法囊颅,實(shí)際上Handler
內(nèi)部會(huì)調(diào)用其兩個(gè)參數(shù)的構(gòu)造方法。 - 在
Handler
兩個(gè)參數(shù)構(gòu)造方法中傅瞻,會(huì)通過Looper.myLooper()
拿到一個(gè)Looper
對(duì)象踢代,如果這個(gè)Looper
對(duì)象為null
則會(huì)拋出異常。 - 然后就是一系列變量賦值操作嗅骄。
- 通過
Handler
構(gòu)造方法胳挎,我們可以知道,在我們新建Handler
對(duì)象時(shí)溺森,Looper.myLooper()
一定不能為null
慕爬,那么Looper.myLooper()
是怎么得到Looper
對(duì)象的呢?屏积,我們需要先把這個(gè)搞清楚医窿,我們來(lái)看下Looper.myLooper()
方法:
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
- 可以看出,
Looper.myLooper()
方法很簡(jiǎn)單炊林,就是調(diào)用了ThreadLocal
對(duì)象的get()
方法姥卢,我們看下ThreadLocal
對(duì)象的get()
方法:
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
private T setInitialValue() {
T value = initialValue();
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
}
protected T initialValue() {
return null;
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
-
ThreadLocal
內(nèi)部是通過ThreadLocalMap
對(duì)象取值的。 -
ThreadLocalMap
,看起來(lái)和Map
類似独榴,暫時(shí)可以當(dāng)成Map
結(jié)構(gòu)來(lái)處理僧叉,稍后再分析。 - 來(lái)看
get()
方法,首先得到當(dāng)前線程對(duì)象的ThreadLocalMap
對(duì)象:
1.如果ThreadLocalMap
對(duì)象不為null
括眠,就以當(dāng)前ThreadLocal
對(duì)象為key
彪标,得到ThreadLocalMap
的Entry
對(duì)象,如果Entry
對(duì)象不為null
掷豺,Entry
對(duì)象的value
就是我們想要的Looper
對(duì)象。
2.如果ThreadLocalMap
對(duì)象為null
薄声,就返回一個(gè)初始值当船,默認(rèn)初始值為null
。 - 也就是說(shuō)默辨,要保證
Looper.myLooper()
不為null
德频,得符合上述1
中的條件。所以我們需要看看Thread
中的threadLocals
變量在哪賦值:
//Thread
ThreadLocal.ThreadLocalMap threadLocals = null;
// ThreadLocal
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
-
Thread
中的threadLocals
初始為null
缩幸,而且在Thread
中沒有賦值的地方壹置,但是ThreadLocal
中set(T value)
方法是會(huì)初始化一個(gè)ThreadLocalMap
對(duì)象,也就是說(shuō)表谊,如果不調(diào)用钞护,ThreadLocal
中set(T value)
方法,Looper.myLooper()
為null
爆办,是沒法創(chuàng)建Handler
對(duì)象的∧压荆現(xiàn)在思路很明確了,我們要找到ThreadLocal
中set(T value)
方法調(diào)用時(shí)機(jī)距辆,Looper.myLooper()
會(huì)得到一個(gè)Looper
對(duì)象余佃,那么Looper
中應(yīng)該有個(gè)類似set
的方法,把Looper
對(duì)象跨算,通過ThreadLocal
中set(T value)
方法爆土,設(shè)置給ThreadLocalMap
的Entry
對(duì)象的value
:
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));
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
- 可以發(fā)現(xiàn)是
Looper
的prepare()
方法,將一個(gè)Looper
對(duì)象通過ThreadLocal
中set(T value)
方法诸蚕,設(shè)置給ThreadLocalMap
的Entry
對(duì)象的value
步势。初始化Looper
對(duì)象同時(shí)會(huì)初始化MessageQueue
對(duì)象。 -
Looper
的prepare()
方法只能在同一個(gè)線程調(diào)用一次挫望,否則會(huì)拋出異常立润,為什么說(shuō)是同一個(gè)線程呢?因?yàn)?code>ThreadLocal的get()
方法是獲取了當(dāng)前線程的ThreadLocalMap
對(duì)象媳板,通過這個(gè)ThreadLocalMap
對(duì)象獲取數(shù)據(jù)桑腮。 - 問題:我們平常使用過程中,并沒有調(diào)用
Looper
的prepare()
蛉幸,也沒有拋出異常破讨,這是為什么呢丛晦?實(shí)際上
UI線程啟動(dòng)時(shí),就調(diào)用了Looper
的prepare()
提陶,所以不需要我們手動(dòng)調(diào)用烫沙,所以準(zhǔn)確來(lái)說(shuō),在UI線程可以直接創(chuàng)建Handler
對(duì)象隙笆,子線程必須調(diào)用Looper
的prepare()
才能創(chuàng)建Handler
對(duì)象锌蓄。
總結(jié)
- 在UI線程可以直接創(chuàng)建
Handler
對(duì)象,子線程必須調(diào)用Looper
的prepare()
才能創(chuàng)建Handler
對(duì)象撑柔。 - 一個(gè)線程瘸爽,只有一個(gè)
Looper
對(duì)象。這是通過ThreadLocal
實(shí)現(xiàn)的铅忿,ThreadLocal
是一個(gè)線程相關(guān)的類剪决,通過ThreadLocal
存儲(chǔ)的數(shù)據(jù),不同線程之間的數(shù)據(jù)是相互獨(dú)立的檀训。
Message入列
- 通過上文柑潦,我們了解了
Handler
的創(chuàng)建過程,接下來(lái)我們?cè)倏纯?code>Handler發(fā)送的消息是如何一步步被分發(fā)的峻凫。 - 我們很容易知道渗鬼,無(wú)論調(diào)用
Handler
發(fā)送消息的哪個(gè)方法,最終都是調(diào)用了sendMessageAtTime(Message msg, long uptimeMillis)
方法蔚晨,這個(gè)方法如下:
// Handler
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);
}
//MessageQueue
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
添加到MessageQueue
的過程乍钻,MessageQueue
我們可以理解為消息隊(duì)列,用來(lái)存放Message
對(duì)象铭腕。下面我們來(lái)一步一步看看Message
是如何添加到MessageQueue
的银择。
- 首先,會(huì)判斷
Message
的target
是不是null
累舷,是null
則拋出異常浩考,這個(gè)target
是當(dāng)前Handler
對(duì)象,通過上面代碼可以知道被盈,target
是在enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis)
方法里面賦值的析孽。 - 會(huì)判斷
Message
是不是已經(jīng)添加過了,如果是一個(gè)已經(jīng)添加過的Message
也會(huì)拋出異常只怎。 - 通過
synchronize
來(lái)進(jìn)行線程同步袜瞬,準(zhǔn)備將Message
添加到MessageQueue
。 - 判斷
Thread
是否處于dead
狀態(tài)身堡,如果處于dead
狀態(tài)則不再繼續(xù)執(zhí)行添加邓尤,直接返回false
。 - 開始添加,把
Message
標(biāo)記為use
狀態(tài),同時(shí)給Message
設(shè)置期望執(zhí)行時(shí)間汞扎,也就是when
,注意這個(gè)期望執(zhí)行時(shí)間是用的SystemClock.uptimeMillis()
和delayMillis
之和季稳,是一個(gè)相對(duì)時(shí)間,其實(shí)想想這里最主要的就是需要一個(gè)相對(duì)時(shí)間澈魄。
6.判斷當(dāng)前有沒有正在執(zhí)行的任務(wù)景鼠,或者當(dāng)前Message
是不是需要立刻執(zhí)行,或者當(dāng)前Message
的期望執(zhí)行時(shí)間是不是比將要執(zhí)行的Message
得期望執(zhí)行時(shí)間要早痹扇,如果滿足铛漓,就將這個(gè)Message'插入到
MessageQueue的最前面,否則鲫构,根據(jù)
when的大小票渠,順序插入
MessageQueue。然后根據(jù)
needWake`參數(shù)芬迄,決定是否需要喚醒執(zhí)行任務(wù)。
- 經(jīng)過上面的步驟昂秃,
Message
就被插入MessageQueue
等待執(zhí)行了禀梳。也就是說(shuō)Message
是要添加到MessageQueue
,然后等待被取出執(zhí)行的肠骆。那么算途,Message
如何被取出執(zhí)行,然后分發(fā)給Handler
的呢?
Looper.loop()
- 通過上文蚀腿,我們已經(jīng)把
Message
添加到MessageQueue
的過程梳理清楚了嘴瓤,那么Message
是如何被取出執(zhí)行的呢?其實(shí)是通過Looper.loop()
來(lái)取出執(zhí)行莉钙,并分發(fā)給發(fā)送Message
的Handler
廓脆。下面來(lái)看下Looper.loop()
方法。
//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;
// 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);
}
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;
try {
msg.target.dispatchMessage(msg);
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} finally {
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();
}
}
// Handler
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
private static void handleCallback(Message message) {
message.callback.run();
}
//Message
public static Message obtain(Handler h, Runnable callback) {
Message m = obtain();
m.target = h;
m.callback = callback;
return m;
}
- 大體一看磁玉,這個(gè)方法比較復(fù)雜停忿,我們來(lái)梳理一下。
- 首先蚊伞,判斷當(dāng)前
Thread
的Looper
對(duì)象是否為null
席赂,為null
則拋出異常。 - 開啟死循環(huán)时迫,不斷通過
MessageQueue
的next()
方法颅停,取出要執(zhí)行的Message
,如果MessageQueue
沒有Message
了,則方法退出掠拳。 - 通過
msg.target.dispatchMessage(msg)
方法癞揉,進(jìn)行消息的分發(fā)。期間會(huì)進(jìn)行一些列判斷,先判斷msg.callback
是不是null
,若果是null
烧董,直接調(diào)用callback.run()
毁靶,那么這個(gè)callback
是什么時(shí)候被賦值的呢?其實(shí)是在上述代碼中Message obtain(Handler h, Runnable callback)
里面被賦值的逊移,如果msg.callback
是null
,則判斷mCallback
,如果mCallback
是null
预吆,則會(huì)回調(diào)handleMessage(Message msg)
方法,也就是我們非常熟悉的方法。如果mCallback
不是null
胳泉,則調(diào)用mCallback.handleMessage(Message msg)
方法拐叉,還記得Handler
兩個(gè)參數(shù)的構(gòu)造方法嗎?mCallback
就是在那里賦值的扇商。 - 分發(fā)完畢凤瘦,通過
msg.recycleUnchecked()
將Message
回收,整個(gè)分發(fā)流程就結(jié)束了案铺。
總結(jié)
- 一個(gè)線程只有一個(gè)
Looper
蔬芥,一個(gè)MessageQueue
,可以有很多個(gè)Handler
控汉。 - 在子線程創(chuàng)建
Handler
笔诵,必須要先調(diào)用looper.prepare
方法,同時(shí)需要調(diào)用looper.loop
方法姑子,開啟死循環(huán)乎婿,不斷從MessageQueue
取出Message
并進(jìn)行分發(fā)。