Android消息機(jī)制是比較重要的一塊,必須要掌握信轿,消息機(jī)制主要是指Handler的運(yùn)行機(jī)制晃痴,Handler的運(yùn)行需要MessageQueue和Looper的支撐,MessageQueue表示消息隊(duì)列虏两,內(nèi)部存儲了一組消息愧旦,采用單鏈表的數(shù)據(jù)結(jié)構(gòu)來實(shí)現(xiàn),不過MessageQueue也只是一個存儲單元定罢,它并不具備處理消息的功能笤虫,Looper就是來干這事的,它會無限循環(huán)是否有新消息祖凫,有就處理琼蚯,沒有就等著。
Handler創(chuàng)建的時候會默認(rèn)采用當(dāng)前線程的Looper來構(gòu)造消息循環(huán)系統(tǒng)惠况,但線程默認(rèn)是沒有Looper的遭庶,如果要使用消息機(jī)制,必要要為線程創(chuàng)建Looper稠屠,但UI線程比較特殊峦睡,它會創(chuàng)建默認(rèn)的Looper對象,所以Android中主線程是可以直接使用handler权埠。
1.Looper和MessageQueue那些事
第一次使用Handler好緊張榨了,聽說在Android中更新UI必須要在主線程,我這暴脾氣就不在攘蔽,于是我在onCreate中寫下了如下代碼:
new Thread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "我是一個toast消息", Toast.LENGTH_SHORT).show();
}
}).start();
嗯龙屉,這段代碼對于我來說就是小菜一碟,于是我一個后空翻满俗,然后點(diǎn)擊了運(yùn)行按鈕转捕,尷尬的一腿,果然崩潰了:
這個錯誤我想大多數(shù)Androider都見過吧唆垃,看著真是親啊五芝,都不想清除它,但是問題還是要解決的辕万,那么如何解決呢与柑?崩潰日志里說的很清楚谤辜,要我們調(diào)用下Looper.prepare(),那我就不客氣了价捧!于是有了如下的代碼:
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(MainActivity.this, "我是一個toast消息", Toast.LENGTH_SHORT).show();
}
}).start();
話不多說丑念,運(yùn)行一波,果然app成功啟動结蟋,但是我的Toast消息并沒有彈出啊脯倚,媽個雞,看來問題并不是這么簡單嵌屎,于是我靈機(jī)一動推正,記得好像Looper.prepare()要和Looper.loop()方法一起使用,于是乎:
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(MainActivity.this, "我是一個toast消息", Toast.LENGTH_SHORT).show();
Looper.loop();
}
}).start();
你終于彈出來了宝惰,不容易爸查拧:
這倆東西這么神奇,加上Looper.prepare()不崩潰了尼夺,加上Looper.loop()之后我的toast就彈出來了尊残,來看看它們的真面目,先看看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));
}
從sThreadLocal.get()里的異常信息可以看出淤堵,sThreadLocal.get()是獲取當(dāng)前線程Looper的寝衫,如果已經(jīng)存在,則拋出異常:每個線程僅可以創(chuàng)建一個Looper拐邪,如果sThreadLocal.get() == null慰毅,那就sThreadLocal.set(new Looper(quitAllowed))創(chuàng)建一個.
ThreadLocal類允許我們創(chuàng)建只能被同一個線程讀寫的變量。因此扎阶,如果一段代碼含有一個ThreadLocal變量的引用汹胃,即使兩個線程同時執(zhí)行這段代碼,它們也無法訪問到對方的ThreadLocal變量东臀,有點(diǎn)抽象着饥,具體后面會介紹。
下面我們來看看Looper的構(gòu)造方法:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
也很簡單啡邑,但是卻很關(guān)鍵贱勃,在創(chuàng)建Looper的時候井赌,默認(rèn)創(chuàng)建了一個MessageQueue谤逼,MessageQueue消息隊(duì)列就是存放消息的地方,此時Looper就有了一個消息倉庫MessageQueue仇穗,存儲消息的地方也就有了流部。
那什么時候往倉庫里放東西呢?具體是怎么放的呢纹坐,咱們下面再說枝冀,先來看下Looper.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;
for (;;) {
Message msg = queue.next();
if (msg == null) {
return;
}
try {
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
msg.recycleUnchecked();
}
}
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
首先通過myLooper()方法獲取當(dāng)前線程的looper對象,如果為null,則拋出異常:趕緊去調(diào)用Looper.prepare()去創(chuàng)建looper去果漾,然后for(;;)球切,簡單粗暴,開啟一個死循環(huán)绒障,然后通過queue.next()從隊(duì)列中取出一條消息吨凑,如果此時消息隊(duì)列中有Message,那么next方法會立即返回該Message户辱,如果此時消息隊(duì)列中沒有Message鸵钝,那么next方法就會阻塞式地等待獲取Message。
取出了message之后呢庐镐,當(dāng)然是找人處理掉它恩商,于是執(zhí)行msg.target.dispatchMessage(msg)開始分發(fā)消息,msg.target其實(shí)就是Handler實(shí)例必逆,它是在消息入隊(duì)列的時候被賦值的怠堪,下面會說到,看看dispatchMessage的代碼:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
嗯末患,代碼還挺簡單研叫,msg.callback != null就去執(zhí)行handleCallback(msg),msg.callback其實(shí)是Runnable callback類型璧针,也就是我們平時調(diào)用Handler.post(Runnable r)里的r參數(shù)嚷炉,handleCallback代碼如下:
private static void handleCallback(Message message) {
message.callback.run();
}
直接去調(diào)用Runnable的run方法去了,else分支判斷了下mCallback != null探橱,mCallback哪來的呢申屹,其實(shí)是我們創(chuàng)建Handler的時候可以選擇傳入的參數(shù):
public Handler() {
this(null, false);
}
public Handler(Callback callback) {
this(callback, false);
}
public Handler(Looper looper) {
this(looper, null, false);
}
public Handler(Looper looper, Callback callback) {
this(looper, callback, false);
}
看到了吧,就是幾個構(gòu)造函數(shù)里的callback隧膏,接著如果mCallback != null就會調(diào)用mCallback.handleMessage(msg)哗讥,去處理消息,如果以上兩個callback都沒有設(shè)置的話胞枕,那就調(diào)用默認(rèn)的handleMessage(msg)去處理消息杆煞,嗯,沒錯腐泻,還是它决乎。
這個時候我們腦子里是不是已經(jīng)很清晰了,當(dāng)我們調(diào)用sendMessage發(fā)送消息的時候派桩,消息就會被存入消息隊(duì)列MessageQueue构诚,在合適的時候就會被Looper取出來,通過dispatchMessage方法去調(diào)用handleMessage(msg)去處理該消息铆惑。
2.消息如何被存入消息隊(duì)列MessageQueue中的范嘱?
說了半天送膳,還不知道這個,莫慌丑蛤,我們來追蹤一下叠聋,就從Handler的sendMessage方法開始:
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);
}
經(jīng)過層層調(diào)用,最終發(fā)現(xiàn)了enqueueMessage方法受裹,沒錯晒奕,就是它了,它就是最終負(fù)責(zé)把消息放入MessageQueue中的名斟,讓我們來一睹它的尊榮:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
//注意這里注意這里:上面我們說了msg.target就是當(dāng)前的Handler實(shí)例脑慧,看到了吧,在這里賦值的砰盐。
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
boolean enqueueMessage(Message msg, long when) {
//handler都沒有你發(fā)個鬼的消息
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
//我是一次性的闷袒,被用過了(QAQ)
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
synchronized (this) {
//終于輪到我了,我的身份標(biāo)識為被使用
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
//p為null表示MessageQueue里還沒有消息岩梳,或者msg的觸發(fā)時間是隊(duì)列中最早的囊骤, 則進(jìn)入該分支。
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;
//把msg加入到鏈表中冀值,按時間順序從小到大排序
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
msg.next = p;
prev.next = msg;
}
//判斷是否需要喚醒也物,如果需要喚醒則調(diào)用nativeWake(mPtr)來喚醒之前等待的線程。
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
mMessages其實(shí)代表消息隊(duì)列的頭部列疗,如果mMessages為空滑蚯,說明還沒有消息,如果當(dāng)前插入的消息不需要延時抵栈,或者說延時比mMessages頭消息的延時要小告材,那么當(dāng)前要插入的消息就需要放在頭部,我們發(fā)送的message消息經(jīng)過enqueueMessage過程后就被加入到了消息隊(duì)列MessageQueue中古劲。
3.Looper中next()方法分析
Looper通過loop()方法中的死循環(huán)不斷的點(diǎn)用queue.next()獲取MessageQueue中的消息斥赋,如果當(dāng)前消息隊(duì)列中沒有消息,Loop線程就會阻塞产艾,當(dāng)其他線程插入消息時疤剑,就會喚醒當(dāng)前線程,queue.next()源碼如下:
Message next() {
int pendingIdleHandlerCount = -1;
int nextPollTimeoutMillis = 0;
for (;;) {
//是否需要阻塞等待闷堡,第一次一定不阻塞隘膘,當(dāng)?shù)却齨extPollTimeoutMillis時長,或者消息隊(duì)列被喚醒缚窿,都會返回
//nextPollTimeoutMillis =0 :無需睡眠棘幸,直接返回
//nextPollTimeoutMillis >0 :睡眠如果超過timeoutMillis焰扳,就返回
//nextPollTimeoutMillis =-1:一直睡眠倦零,直到其他線程喚醒它
nativePollOnce(ptr, nextPollTimeoutMillis);
//同步
synchronized (this) {
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
//是否存在barrier误续,android中定義了一個Barrier的概念,當(dāng)View在繪制和布局時會向Looper中添加了Barrier(監(jiān)控器)扫茅,這樣后續(xù)的消息隊(duì)列中的同步的消息將不會被執(zhí)行蹋嵌,以免會影響到UI繪制,此時只有異步消息才能被執(zhí)行葫隙。
if (msg != null && msg.target == null) {
//do while循環(huán)遍歷消息鏈表栽烂,跳出循環(huán)時,msg指向離表頭最近的一個異步消息
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
//看取到的消息是不是需要立即執(zhí)行恋脚,需要立即執(zhí)行的就返回當(dāng)前消息腺办,如果需要等待,計算出等待時間
if (now < msg.when) {
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;
}
//沒有可以即刻執(zhí)行的Message,查看是否存在需要處理的IdleHandler船响,如果不存在躬拢,則返回,阻塞等待见间,如果存在則執(zhí)行IdleHandler
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
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);
}
}
}
//重置idle handler個數(shù)為0聊闯,以保證不會再次重復(fù)運(yùn)行
pendingIdleHandlerCount = 0;
nextPollTimeoutMillis = 0;
}
}
next函數(shù)中,nextPollTimeoutMillis初始值=0 米诉,所以for循環(huán)第一次是一定不會阻塞的菱蔬,如果能找到一個Delay倒計時結(jié)束的消息,就返回該消息史侣,否則汗销,執(zhí)行第二次循環(huán),睡眠等待抵窒,直到頭部第一個消息Delay時間結(jié)束弛针,所以next函數(shù)一定會返回一個Message對象。
接著會去查看是否存在barrier李皇,存在就取出此異步消息削茁,否則繼續(xù)處理同步消息,然后會判斷取到的消息是不是需要立即執(zhí)行掉房,需要立即執(zhí)行的就返回當(dāng)前消息茧跋,如果需要等待,計算出等待時間卓囚。最后瘾杭,如果需要等待,還要查看哪亿,IdleHandler列表是否為空粥烁,不為空的話贤笆,需要處理IdleHandler列表,最后重新計算一遍讨阻。
nativePollOnce是阻塞操作芥永,其中nextPollTimeoutMillis代表下一個消息到來前,還需要等待的時長钝吮;當(dāng)nextPollTimeoutMillis = -1時埋涧,表示消息隊(duì)列中無消息,會一直等待下去奇瘦,當(dāng)處于空閑時棘催,往往會執(zhí)行IdleHandler中的方法,當(dāng)nativePollOnce()返回后耳标,next()從mMessages中提取一個消息巧鸭。
1.nativePollOnce更詳細(xì)的解釋點(diǎn)此處查看!
2.barrier相關(guān)知識點(diǎn)擊此處查看麻捻!
3. IdleHandler相關(guān)知識點(diǎn)擊此處查看纲仍!
4.ThreadLocal詳解
ThreadLocal是一個線程內(nèi)部的數(shù)據(jù)存儲類,通過它可以在指定的線程中存儲數(shù)據(jù)贸毕,數(shù)據(jù)存儲以后郑叠,只有在指定線程中可以獲取到存儲的數(shù)據(jù),對于其它線程來說無法獲取到數(shù)據(jù)明棍,下面來看一個例子:
private ThreadLocal<Boolean> mBooleanThreadLocal = new ThreadLocal<>();
mBooleanThreadLocal.set(true);
Log.e("handler","main----value = "+mBooleanThreadLocal.get());
new Thread("Thread1"){
@Override
public void run() {
mBooleanThreadLocal.set(false);
Log.e("handler","Thread1----value = "+mBooleanThreadLocal.get());
}
}.start();
new Thread("Thread2"){
@Override
public void run() {
Log.e("handler","Thread2----value = "+mBooleanThreadLocal.get());
}
}.start();
代碼很簡單乡革,我們定義了一個ThreadLocal對象,在onCreate里設(shè)置為true摊腋,然后啟動了兩個子線程沸版,一個設(shè)置false直接打印其值,一個不設(shè)置直接打印兴蒸,看看運(yùn)行結(jié)果:
我的天视粮,這么神奇,主線程里為true沒毛病橙凳,Thread1中為false看起來也像那么回事蕾殴,Thread2中為null就有點(diǎn)過分了吧,但其實(shí)這正是ThreadLocal的神奇之處岛啸,我們來看看它為何可以這么吊钓觉,其實(shí)ThrealLocal 是一個泛型類,它的定義為 public class ThrealLocal坚踩,弄清楚 ThrealLocal 的 set() 和 get() 方法就可以明白它的工作原理了荡灾。
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
static class ThreadLocalMap {
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
private Entry[] table;
}
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();
}
Threadlocal的set方法以當(dāng)前線程this為key,存儲在一個ThreadLocalMap中,ThreadLocalMap內(nèi)部存儲其實(shí)使用的是一個Entry數(shù)組批幌,數(shù)組的每一個值都是一個弱引用的ThreadLocal础锐,里面保存著具體的value值,通過get方法逼裆,以當(dāng)前線程為key,取出相應(yīng)的value赦政,各個線程之間互不影響胜宇。
5.如何正確使用Handler
我們知道顷窒,在Java中內(nèi)部類的定義與使用一般為成員內(nèi)部類與匿名內(nèi)部類淹父,他們的對象都會隱式持有外部類對象的引用染乌,影響外部類對象的回收煎源。所以我們平時這樣的代碼:
private Handler meHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
AS都看不下去了联喘,會給我們一個警告:
當(dāng)我們發(fā)送一個延時消息纳鼎,此時如果在消息還沒執(zhí)行的時候就退出了Activity果元,此時就會內(nèi)存泄露契耿,下面給出一種解決方式:
private static class MyHandler extends Handler {
private WeakReference<MainActivity> weakReference;
MyHandler(MainActivity activity) {
weakReference = new WeakReference<>(activity);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
MainActivity activity = weakReference.get();
if (null != activity) {
//dosomething
}
}
}
private MyHandler handler = new MyHandler(this);
6.子線程真的不能更新UI嗎靡羡?
先看個例子系洛,我在onCrete中執(zhí)行如下代碼:
tvShow = findViewById(R.id.tv_show);
new Thread(new Runnable() {
@Override
public void run() {
tvShow.setText("我胖虎在子線程中···");
}
}).start();
運(yùn)行結(jié)果:
這不是見鬼了吧,在子線程中竟然更新UI成功了B圆健C璩丁!不要慌趟薄,基本操作绽诚,大家都坐下!我們來稍微該下代碼:
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
tvShow.setText("我胖虎在子線程中···");
}
}).start();
運(yùn)行結(jié)果如下:
嗯杭煎,這個才是我們想要的樣子嘛恩够,那么為啥呢,為啥呢羡铲,一路追蹤源碼:setText-->checkForRelayout-->requestLayout-->mParent.requestLayout()蜂桶,此處的mParent是ViewParent類型,它是一個接口public interface ViewParent也切,它的實(shí)現(xiàn)類是ViewRootImpl屎飘,所以看下ViewRootImpl的requestLayout()方法:
@Override
public void requestLayout() {
if (!mHandlingLayoutInLayoutRequest) {
checkThread();
mLayoutRequested = true;
scheduleTraversals();
}
}
void checkThread() {
if (mThread != Thread.currentThread()) {
throw new CalledFromWrongThreadException(
"Only the original thread that created a view hierarchy can touch its views.");
}
}
終于找到你了,這個異常就是判斷當(dāng)前線程是否是主線程贾费,此時如果不是主線程就會拋出這個異常钦购,那么看來看去ViewRootImpl很關(guān)鍵,那么ViewRootImpl是在什么時候創(chuàng)建的呢褂萧?
你如果對Activity的啟動流程有所了解押桃,那么ActivityThread中的handleResumeActivity方法你一定不會陌生:
final void handleResumeActivity(IBinder token,
boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
r = performResumeActivity(token, clearHide, reason);
r.activity.mVisibleFromServer = true;
mNumVisibleActivities++;
if (r.activity.mVisibleFromClient) {
r.activity.makeVisible();
}
ActivityManager.getService().finishActivity(token, Activity.RESULT_CANCELED, null,Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
}
r.activity.makeVisible()這里調(diào)用了Activity的makeVisible():
void makeVisible() {
if (!mWindowAdded) {
ViewManager wm = getWindowManager();
wm.addView(mDecor, getWindow().getAttributes());
mWindowAdded = true;
}
mDecor.setVisibility(View.VISIBLE);
}
@Override
public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
applyDefaultToken(params);
mGlobal.addView(view, params, mContext.getDisplay(), mParentWindow);
}
接著調(diào)用了WindowManagerImpl的addView方法,然后最終調(diào)用了WindowManagerGlobal的addView方法:
public void addView(View view, ViewGroup.LayoutParams params,
Display display, Window parentWindow) {
final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams) params;
ViewRootImpl root;
synchronized (mLock) {
······
//ViewRootImpl最終是在這里初始化的
root = new ViewRootImpl(view.getContext(), display);
view.setLayoutParams(wparams);
mViews.add(view);
mRoots.add(root);
mParams.add(wparams);
·····
}
}
繞來繞去終于發(fā)現(xiàn)ViewRootImpl最終是在WindowManagerGlobal的addView方法中初始化的导犹,回到最初其實(shí)之所以onCreate可以更新Ui是因?yàn)閂iewRootImpl尚未初始化成功唱凯,一旦ViewRootImpl初始化完成羡忘,checkThread開始工作,子線程就不能在進(jìn)行Ui操作了磕昼。
7.總結(jié)
1.主線程默認(rèn)創(chuàng)建Looper卷雕,直接使用handler不會出錯,子線程必須要調(diào)用Looper.prepare()創(chuàng)建Looper票从,創(chuàng)建Looper的同時會創(chuàng)建MessageQueue漫雕,然后調(diào)用Looper.loop()開啟消息循環(huán)。
2.Looper.loop()會讓當(dāng)前線程進(jìn)入一個死循環(huán)峰鄙,不斷從MessageQueue中讀取消息浸间,然后回調(diào)msg.target.dispatchMessage(msg)方法。
3.平時我們使用Handler.post(runnable r)吟榴,runnable執(zhí)行的線程就是調(diào)用其handler創(chuàng)建所在的線程魁蒜,主線程handler.post就會在主線程執(zhí)行,子線程創(chuàng)建的handler就會在子線程執(zhí)行吩翻。
4.Looper死循環(huán)為什么不會把線程卡死:因?yàn)?a target="_blank" rel="nofollow">epoll和管道pipe兜看,有消息就取出依次執(zhí)行,沒消息就阻塞等待狭瞎,讓出CPU铣减,等有消息了,epoll會往pipe中寫一個字符脚作,把主線程喚起葫哗,主線程就繼續(xù)開始循環(huán)消息。
參考資料:
1.Android Handler與Looper原理簡析.
2.Android子線程真的不可以更新UI嗎.
3.深入源碼解析Android中的Handler,Message,MessageQueue,Looper.