工作的時(shí)候發(fā)現(xiàn)自己對(duì)于很多東西用起來得心應(yīng)手迄埃,原理機(jī)制也背誦的滾瓜爛熟,但是一問到源碼腦子就....瓦特了兑障!所以最近準(zhǔn)備從頭開始學(xué)習(xí)源碼侄非,學(xué)習(xí)大神們優(yōu)秀的思想!
本文是對(duì)Handler機(jī)制的源碼分析流译,目的是為了能夠從源碼角度一點(diǎn)點(diǎn)的理解Handler機(jī)制逞怨,里面會(huì)出現(xiàn)大量的源碼,所以會(huì)比較枯燥福澡,但是只要認(rèn)真看完叠赦,相信你一定會(huì)對(duì)Handler機(jī)制的實(shí)現(xiàn)方法有更加清晰的認(rèn)識(shí)
Handler是用起來非常簡單!
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
//處理接收到的消息
}
};
初始化之后,在子線程進(jìn)行完耗時(shí)操作之后,使用
handler.sendEmptyMessage(what)
好了侧馅,現(xiàn)在就從sendEmptyMessage 方法開始故觅,一步步的解析handler整個(gè)工作流程 — — 注意辣辫,Handler開始向消息隊(duì)列發(fā)送消息了;
點(diǎn)進(jìn)去之后,我們會(huì)發(fā)現(xiàn),sendEmptyMessage 暂吉、sendMessage 最終都是在調(diào)用 sendMessageAtTime 方法,將發(fā)送的消息放入messgeQueue缎患;需要注意的一點(diǎn)是慕的,sendMessageDelayed方法中,已經(jīng)將 delayMillis 延遲時(shí)間轉(zhuǎn)換成了 SystemClock.uptimeMillis() + delayMillis挤渔,指的是該消息被取出來執(zhí)行的時(shí)間肮街,這一點(diǎn)會(huì)在MessageQueue中顯的比較重要
//直接調(diào)用 sendEmptyMessageDelayed 方法
public final boolean sendEmptyMessage(int what){
//直接調(diào)用 sendEmptyMessageDelayed 方法
return sendEmptyMessageDelayed(what, 0);
}
// 被sendEmptyMessage方法調(diào)用,delayMillis 為0蚂蕴,同時(shí)將參數(shù)轉(zhuǎn)換成message后調(diào)用 sendMessageDelayed 此處已經(jīng)和 sendMessage方法調(diào)用同一個(gè)路徑了
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
//將參數(shù)進(jìn)行復(fù)制低散,轉(zhuǎn)換成 Message
Message msg = Message.obtain();
msg.what = what;
return sendMessageDelayed(msg, delayMillis);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
//此處的 SystemClock.uptimeMillis() + delayMillis 用來計(jì)算消息的執(zhí)行時(shí)間
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
//最終,發(fā)送消息的方法都會(huì)走到這里骡楼,將消息放入MessageQueue
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
//mQueue 是從哪里來的熔号?此處先放下,待會(huì)回頭來分析
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);
}
在sendMessageAtTime 方法中鸟整,消息放入了我們熟知的 handler機(jī)制中的MessageQueue引镊;現(xiàn)在我們分析 sendMessageAtTime 方法,這個(gè)方法中主要執(zhí)行了一個(gè) MessageQueue 的非空判斷篮条,然后就直接執(zhí)行了enqueueMessage方法弟头,mQueue 是從哪里來的呢?為了邏輯的連貫性涉茧,此處先不分析赴恨,會(huì)放到下面進(jìn)行分析,這里先接著enqueueMessage進(jìn)行分析伴栓;
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
//將此Hanlder賦值給Message伦连,用來在分發(fā)消息時(shí)候接收消息的hanlder
msg.target = this;
if (mAsynchronous) {//是否是異步,此處為false钳垮,不會(huì)執(zhí)行
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
enqueueMessage方法也很簡單惑淳,主要就是將此Hanlder賦值給Message,用來在分發(fā)消息時(shí)候接收消息的hanlder饺窿,然后將消息交給messageQueue來處理歧焦;
好了,到這里肚医,我們開始進(jìn)入messageQueue 了--
當(dāng)然绢馍,并不是Handler源碼已經(jīng)分析完畢了,只是我按照代碼的腳步一步一步的走下去肠套,目的是為了讓自己能清除的看到Handler機(jī)制走過的所有道路痕貌,以便于最終能夠完整、清晰的理解Handler消息機(jī)制糠排,最后還是會(huì)回到Handler中的舵稠;
現(xiàn)在,我們進(jìn)入MessageQueue — — 注意:Handler發(fā)送的消息入宦,要進(jìn)入消息隊(duì)列了哺徊;
直接找到 Handler中 enqueueMessage方法里面執(zhí)行的MessageQueue方法, enqueueMessage(Message msg, long when)乾闰;
boolean enqueueMessage(Message msg, long when) {
// msg.target 落追,這個(gè)參數(shù)是不是很熟悉,對(duì)的涯肩,就是在Handler進(jìn)入MessageQueue之前的enqueueMessage方法中賦值的轿钠,是當(dāng)前的Handler
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {//此處判斷當(dāng)前Message是否是被執(zhí)行了巢钓,一個(gè)消息不能被執(zhí)行使用兩次
throw new IllegalStateException(msg + " This message is already in use.");
}
synchronized (this) {
if (mQuitting) {//mQuitting默認(rèn)一直是false,只有執(zhí)行quit 方法疗垛,并且該MessageQueue能被安全退出的時(shí)候回被賦值為true症汹,主線程中是不能被退出的,所以一直都是false贷腕,因此不會(huì)被執(zhí)行進(jìn)來背镇,直接跳過去
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;
}
//開始對(duì)傳入進(jìn)來的消息進(jìn)行處理了
msg.markInUse();//將消息標(biāo)記為已經(jīng)放入隊(duì)列
msg.when = when;//消息被執(zhí)行的時(shí)間
Message p = mMessages;
boolean needWake;
//此處進(jìn)行判斷,如果mMessages為Null(p == null)泽裳,則表示現(xiàn)在消息隊(duì)列里面已經(jīng)沒有消息緩存了瞒斩,可以直接放入消息隊(duì)列的最頂端,同時(shí)喚醒正在阻塞的消息隊(duì)列
//when==0涮总,表示該消息需要被立即執(zhí)行
//如果mMessages胸囱!=null,表示目前消息隊(duì)列里面已經(jīng)有消息了,此時(shí)比較消息隊(duì)列里最頂端要被取出來的消息使用時(shí)間瀑梗,如果when < p.when旺矾,表示新傳入的消息執(zhí)行的時(shí)間在消息隊(duì)列中最靠前,所以也放到頂端(注意:mMessages 是一個(gè)鏈表結(jié)構(gòu)夺克,且mMessages是該鏈表中最頂端的消息)
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 {
//如果不滿足以上三個(gè)條件箕宙,就把該消息放到隊(duì)列里對(duì)應(yīng)的位置
//是否需要喚醒此時(shí)的阻塞
//msg.isAsynchronous();這個(gè)是不是很熟悉?沒錯(cuò)铺纽,就是在Handler的enqueueMessage方法中柬帕,有這么一行代碼: msg.setAsynchronous(true);在這里可以看到,如果message是Asynchronous的話狡门,才會(huì)需要喚醒阻塞的線程
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
//下面一個(gè)循環(huán)陷寝,將傳入進(jìn)來的消息根據(jù)執(zhí)行的時(shí)間 when 插入到消息隊(duì)列中指定的位置
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
//此處,(when < p.when)表示最新傳入進(jìn)來等待插入消息隊(duì)列的消息執(zhí)行時(shí)間早于當(dāng)前這個(gè)消息的執(zhí)行時(shí)間其馏,則將最新傳入的消息插入這個(gè)位置凤跑,
//(p==null)當(dāng)隊(duì)列中的消息已經(jīng)遍歷完成,每個(gè)消息的執(zhí)行時(shí)間都早于最新傳入的消息叛复,那就把這個(gè)消息放到最后
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;
}
消息已進(jìn)入隊(duì)列仔引,開始等待被取出消費(fèi)了 — — 注意,Looper開始表演了褐奥;
到這里咖耘,消息隊(duì)列的插入已經(jīng)完成了,根據(jù)我們熟知的Handler機(jī)制撬码,這時(shí)候就要開始等待隊(duì)列中的消息被取出來執(zhí)行了儿倒;但是消息是在哪里被取出來進(jìn)行執(zhí)行的呢,到這里好像代碼已經(jīng)斷掉了呜笑,根本沒有找到下一步調(diào)用的方法胺蚍瘛彻犁!
別著急,Hanlder的使用除了sendEmptyMessage的調(diào)用凰慈,還有初始化操作啊汞幢,我們點(diǎn)進(jìn)去之后,發(fā)現(xiàn)最終會(huì)執(zhí)行到這個(gè)構(gòu)造方法溉瓶;
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 that has not called Looper.prepare()");
}
//此處 mQueue 被賦值,Hanlder和MessageQueue關(guān)聯(lián)起來了
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
還記得我再Handler中為了不打斷邏輯連貫性忽略掉的那一行代碼嗎谤民?
MessageQueue queue = mQueue;
這個(gè)MessageQueue 是從哪里來的呢堰酿,在這里我們已經(jīng)找到了賦值地方,在構(gòu)造方法中张足,mQueue被賦值触创,并且來自Looper,這里为牍,已經(jīng)將Hanlder哼绑、MessageQueue、Looper關(guān)聯(lián)起來了碉咆;
現(xiàn)在開始進(jìn)入Looper了抖韩;
Looper本身是一個(gè)輪詢器,用來從消息隊(duì)列中取出消息疫铜;我們知道茂浮,Handler是在主線程進(jìn)行初始化并執(zhí)行的,因此壳咕,在Handler構(gòu)造方法中的代碼:
mLooper = Looper.myLooper();
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
我們打開 Looper.myLooper()席揽,發(fā)現(xiàn)只有一行代碼,mLooper 來自ThreadLocal谓厘;并且在在sThreadLocal 上發(fā)現(xiàn) 是在prepare()中進(jìn)行的初始化
// sThreadLocal.get() will return null unless you've called prepare().
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
......
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
我們來看一下prepare()方法幌羞;
/** Initialize the current thread as a looper.
* This gives you a chance to create handlers that then reference
* this looper, before actually starting the loop. Be sure to call
* {@link #loop()} after calling this method, and end it by calling
* {@link #quit()}.
*/
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));
}
/**
* Initialize the current thread as a looper, marking it as an
* application's main looper. The main looper for your application
* is created by the Android environment, so you should never need
* to call this function yourself. See also: {@link #prepare()}
*/
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
好了,通過這三個(gè)方法竟稳,我們知道 prepare()和loop()方法是同步出現(xiàn)的属桦,并且prepare()中進(jìn)行了Looper的初始化,此時(shí)也找到了MessageQueue的初始化他爸;
看到這里地啰,對(duì)于不熟悉Looper和Handler機(jī)制的童鞋來說,Handler里面也沒有調(diào)用初始化方法敖补洹?髁摺!U祷臁蔚鸥!
此處線索已掉線惜论,大家散了吧!
恩止喷,我再想想辦法馆类,串起來!
Handler本身是在主線程中初始化的弹谁,并且ThreadLocal只能在當(dāng)前線程中才能獲取到里面的信息乾巧,所以初始化操作肯定是在 主線程完成的;因此预愤,我們?cè)贏ctivityThread 的main方法中沟于,找到了Looper的初始化和啟動(dòng);
還有一個(gè)方法prepareMainLooper()植康,這個(gè)方法同樣是Looper的初始化方法旷太,并且作為Application的主線程中的Looper使用,并且建議我們自己永遠(yuǎn)不要調(diào)用销睁;
ok供璧,這個(gè)意思大概就是我們能在主線程中找到初始化方法prepareMainLooper()吧。冻记。睡毒。。
最后冗栗,確實(shí)是在ActivityThread 的main方法中找到了Looper的初始化操作吕嘀;
public static void main(String[] args) {
//省略掉部分不相關(guān)代碼
//.........
Looper.prepareMainLooper();
//..........
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
到這里,Looper終于開始啟動(dòng)循環(huán)了贞瞒;
喜大普奔偶房,來看看loop是怎么循環(huán)的吧
public static void loop() {
//此處確保已經(jīng)初始化,調(diào)用過prepare方法
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();
//此處開始大家熟知的死循環(huán)军浆,取出消息隊(duì)列中的消息
for (;;) {
//第一步就是從MessageQueue中取出最頂端的消息,next()方法可能會(huì)被阻塞
Message msg = queue.next(); // might block
//如果取出消息為空棕洋,就結(jié)束循環(huán)
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
//僅僅打印log,跳過
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;
//到這里乒融,開始對(duì)取出來的消息進(jìn)行分發(fā)
// msg.target 這個(gè)是不是很熟悉掰盘,沒錯(cuò),就是Handler赞季,在Handler的enqueueMessage方法中進(jìn)行的賦值愧捕,目的就是用來判斷當(dāng)前消息處理的Hanlder,在此處終于顯示出來他的作用了申钩,沒錯(cuò)次绘,就是調(diào)用了Hanlder的dispatchMessage方法,在此處,所有的流程終于又回到了Handler邮偎,分發(fā)完成之后管跺,loop()方法的代碼對(duì)于Hanlder已經(jīng)不是很重要了,可以直接跳過不看
try {
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();
}
}
現(xiàn)在禾进,我們重新回到Handler
繞了半天豁跑,終于回來了
趕緊看看,dispatchMessage(msg)這個(gè)方法泻云;
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
//整了半天艇拍,終于出現(xiàn)了
handleMessage(msg);
}
}
handleMessage(msg);方法終于出現(xiàn)了有木有,這個(gè)就是我們處里Handler方法的地方宠纯;到此卸夕,終于把Handler機(jī)制的源碼過了一遍!
再補(bǔ)充一下:
在Looper.loop()方法中征椒,從消息列表MessageQueue中取出Message的方法 queue.next()是一個(gè)可阻塞的方法娇哆,阻塞也是
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;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
//一個(gè)navtie方法湃累,nextPollTimeoutMillis表示阻塞時(shí)間勃救,0阻塞,-1代表意義阻塞治力,直到被喚醒蒙秒,在消息隊(duì)列里面沒有消息的時(shí)候,就會(huì)一直阻塞下去宵统,直到被喚醒晕讲,這也是loop方法不會(huì)執(zhí)行完的原因,因?yàn)樵谙榭盏臅r(shí)候就被阻塞在這里了马澈,直到有消息進(jìn)來喚醒線程瓢省,調(diào)用nativeWake()喚醒線程才會(huì)繼續(xù)走下去
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// 次數(shù)開始獲取下一條Message,如果有就返回
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {
// 通過循環(huán)痊班,返回當(dāng)前處于隊(duì)列最底部勤婚,需要被取出來的消息
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
//msg.when表示當(dāng)前消息需要被執(zhí)行的時(shí)間,now < msg.when涤伐,表示當(dāng)前時(shí)間還沒到隊(duì)列底部部(最后一條)消息被執(zhí)行的時(shí)間
//隊(duì)列執(zhí)行是先進(jìn)先出馒胆,所以此時(shí)的消息位于隊(duì)列的最底部,會(huì)被首先被取出來的凝果,這個(gè)位置我統(tǒng)一稱為底部(方便理解)
if (now < msg.when) {
// Next message is not ready. Set a timeout to wake up when it is ready.
//此時(shí)消息還沒到執(zhí)行時(shí)間祝迂,計(jì)算出需要等待的時(shí)間,
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// 如果此時(shí)消息應(yīng)該被立即執(zhí)行
mBlocked = false;
if (prevMsg != null) {
//如果消息隊(duì)列不僅僅有一個(gè)消息器净,則此時(shí)將倒數(shù)第二條消息的下一條消息只想meg.next(是null)
prevMsg.next = msg.next;
} else {
//此時(shí)表示僅有一條消息型雳,被取出來后mMessages 就為null
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
//此時(shí)返回被取出來的消息,next()方法結(jié)束
return msg;
}
} else {
// 如果此時(shí)消息隊(duì)列里面已經(jīng)沒有消息了,則等待時(shí)間更為-1
nextPollTimeoutMillis = -1;
}
// 是否是退出狀態(tài)四啰,主線程里面不會(huì)有退出宁玫,mQuitting 恒為false,不會(huì)執(zhí)行
if (mQuitting) {
dispose();
return null;
}
//到這里正常的Message消息已經(jīng)結(jié)束了柑晒,但是google大大巧妙的設(shè)計(jì)了另一種消息類型欧瘪,IdleHandler,這種消息類型并不會(huì)定義執(zhí)行時(shí)間匙赞,而是會(huì)在Message 消息阻塞時(shí)佛掖,利用阻塞的空閑時(shí)間來執(zhí)行
// 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.
//此處獲取IdleHandler的數(shù)量;
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
//如果沒有IdleHandler消息涌庭,則繼續(xù)等待芥被,不再向下執(zhí)行
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);
}
// Run the idle handlers.
// We only ever reach this code block during the first iteration.
//如果有IdleHandler消息,則取出來執(zhí)行了坐榆,并移出已經(jīng)執(zhí)行的消息
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;
//立即執(zhí)行 IdleHandler 不再阻塞線程
nextPollTimeoutMillis = 0;
}
}
最后總結(jié)一下
Handler機(jī)制到這里已經(jīng)完全串聯(lián)起來了拴魄,整個(gè)流程最后總結(jié)起來其實(shí)確實(shí)很簡單:
1、ActivityThread中席镀,初始化Looper匹中,Looper初始化時(shí)候會(huì)創(chuàng)建MessageQueue;Looper初始化完成之后調(diào)用loop()開啟死循環(huán)豪诲,不斷取出MessageQueue中的消息顶捷,并分發(fā)出去
2、Handler初始化后屎篱,將Looper服赎,MessageQueue、Handler關(guān)聯(lián)起來交播,并等待接受來自MessageQueue中的消息
3重虑、Handler通過send相關(guān)方法,發(fā)送消息到MessageQueue秦士,MessageQueue通過Message信息缺厉,將Message放到隊(duì)列中相應(yīng)位置,等待被取出使用伍宦;
4芽死、Looper取出消息,并根據(jù)Message中的信息分發(fā)出去次洼,給相應(yīng)的Handler使用关贵,此時(shí)Hanlder接收到消息,我們開始處理消息卖毁,進(jìn)行更新UI等主線程的操作