概述
Android應(yīng)用啟動時就會為應(yīng)用創(chuàng)建一個主線程钧敞,由于UI操作都是在主線程中進行的,所以主線程也稱為 UI 線程。在單線程模式下资柔,UI線程執(zhí)行耗時很長的操作(例如,網(wǎng)絡(luò)訪問或數(shù)據(jù)庫查詢)將會阻塞UI線程撵割,一旦UI線程被阻塞贿堰,將無法進行UI操作,從用戶的角度來看應(yīng)用卡住了睁枕。 如果 UI 線程被阻塞超過幾秒鐘時間(目前大約是 5 秒鐘)官边,就會導(dǎo)致ANR。
Android UI工具包并非是線程安全的外遇。因此不能通過工作線程操作UI,而只能通過UI線程操作UI契吉。
綜上所述 Android的單線程模式必須遵守以下兩條規(guī)則:
1 不要阻塞 UI 線程
2 不要在 UI 線程之外操作UI
由于不能阻塞 UI 線程所以我們將耗時的操作放到工作線程中跳仿,如果在工作線程處理耗時操作的過程中需要更新UI界面,但是由于不可以在工作線程中操作UI的限制捐晶,這時我們就需要用Android消息機制(即Handler機制)來將更新UI界面的操作切換到UI線程中執(zhí)行菲语,這也是Google設(shè)計Handler機制的初衷。
預(yù)備知識
1 ThreadLocal
當(dāng)某些數(shù)據(jù)以線程做為作用域并且不同線程具有不同數(shù)據(jù)副本的時候惑灵,就可以考慮使用ThreadLocal山上。在Handler機制中,Looper對象就是以線程做為作用域并且不同的線程中Looper對象是不同的英支,Android系統(tǒng)中是通過ThreadLocal實現(xiàn)Looper對象的存取佩憾。
下面舉例說明一下ThreadLocal使用方法:
final ThreadLocal<Integer> threadLocal1 = new ThreadLocal<Integer>();
final ThreadLocal<String> threadLocal2 = new ThreadLocal<String>();
threadLocal1.set(5);
threadLocal2.set("one");
Log.d(TAG, "Thread1 threadLocal1.get() = " + threadLocal1.get());
Log.d(TAG, "Thread1 threadLocal2.get() = " + threadLocal2.get());
new Thread(new Runnable() {
@Override
public void run() {
threadLocal1.set(9);
threadLocal2.set("two");
Log.d(TAG, "Thread2 threadLocal1.get() = " + threadLocal1.get());
Log.d(TAG, "Thread2 threadLocal2.get() = " + threadLocal2.get());
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
Log.d(TAG, "Thread3 threadLocal1.get() = " + threadLocal1.get());
Log.d(TAG, "Thread3 threadLocal2.get() = " + threadLocal2.get());
}
}).start();
運行結(jié)果如下:
D/com.cytmxk.test.thread.ThreadLocalFragment: Thread1 threadLocal1.get() = 5
D/com.cytmxk.test.thread.ThreadLocalFragment: Thread1 threadLocal2.get() = one
D/com.cytmxk.test.thread.ThreadLocalFragment: Thread2 threadLocal1.get() = 9
D/com.cytmxk.test.thread.ThreadLocalFragment: Thread2 threadLocal2.get() = two
D/com.cytmxk.test.thread.ThreadLocalFragment: Thread3 threadLocal1.get() = null
D/com.cytmxk.test.thread.ThreadLocalFragment: Thread3 threadLocal2.get() = null
從上面的運行結(jié)果就可以得出結(jié)論:
通過ThreadLocal對象保存的數(shù)據(jù)是以線程作為作用域并且不同線程具有不同的數(shù)據(jù)副本。
下面分析源碼時會說明干花,對于ThreadLocal這種數(shù)據(jù)獲取和保存的類妄帘,只要了解獲取和保存數(shù)據(jù)的邏輯就可以明白其工作原理。下面我們就先來看一下ThreadLocal保存數(shù)據(jù)的邏輯:
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);
}
有上面的代碼可知池凄,set方法中先會獲取執(zhí)行set方法線程的實例currentThread抡驼,然后執(zhí)行g(shù)etMap方法獲取currentThread的成員變量threadLocals(ThreadLocalMap類型);如果map為null(說明是第一次在currentThread線程中使用ThreadLocal的set方法)肿仑,就會調(diào)用createMap方法為currentThread線程的成員變量threadLocals進行初始化(threadLocals的成員變量table被初始化為長度為16的數(shù)組):
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
// INITIAL_CAPACITY的值是16致盟,即table初始化的長度為16,ThreadLocalMap具有擴容的能力
table = new Entry[INITIAL_CAPACITY];
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
table[i] = new Entry(firstKey, firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}
private void set(ThreadLocal<?> key, Object value) {
// We don't use a fast path as with get() because it is at
// least as common to use set() to create new entries as
// it is to replace existing ones, in which case, a fast
// path would fail more often than not.
Entry[] tab = table;
int len = tab.length;
int i = key.threadLocalHashCode & (len-1);
for (Entry e = tab[i];
e != null;
e = tab[i = nextIndex(i, len)]) {
// Android-changed: Use refersTo() (twice).
// ThreadLocal<?> k = e.get();
// if (k == key) { ... } if (k == null) { ... }
if (e.refersTo(key)) {
e.value = value;
return;
}
if (e.refersTo(null)) {
replaceStaleEntry(key, value, i);
return;
}
}
tab[i] = new Entry(key, value);
int sz = ++size;
if (!cleanSomeSlots(i, sz) && sz >= threshold)
// 對應(yīng)擴容的能力
rehash();
}
通過調(diào)用ThreadLocal對象的set方法最終將ThreadLocal對象和數(shù)據(jù)保存到了threadLocals的成員變量table中尤慰。
接下來我們來看一下ThreadLocal獲取數(shù)據(jù)的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();
}
首先獲取執(zhí)行g(shù)et方法線程實例的成員變量localValues的值并且賦值給threadLocals馏锡;如果threadLocals不為null,則調(diào)用threadLocals的getEntry方法:
private Entry getEntry(ThreadLocal<?> key) {
int i = key.threadLocalHashCode & (table.length - 1);
Entry e = table[i];
// Android-changed: Use refersTo().
if (e != null && e.refersTo(key))
return e;
else
return getEntryAfterMiss(key, i, e);
}
ThreadLocal保存和獲取的數(shù)據(jù)是保存在線程的成員變量threadLocals中割择,所以通過ThreadLocal保存的數(shù)據(jù)是以線程作為作用域并且不同線程具有不同的數(shù)據(jù)副本眷篇。
2 同步消息/異步消息、同步屏障
Message msg = Message.obtain();
msg.what = 1000;
msg.setAsynchronous(true);
上面是創(chuàng)建消息的代碼荔泳,默認情況下消息都是同步消息蕉饼,只有執(zhí)行上面的第三行代碼該消息就是異步消息虐杯,一般情況下這兩種消息沒什么區(qū)別,只有消息隊列(MessageQueue)設(shè)置了同步屏障情況下異步消息才會被優(yōu)先執(zhí)行昧港。設(shè)置和取消同步屏障的方法如下:
// 消息隊列是按照消息執(zhí)行的時間增序排列的擎椰,同步屏障是一個沒有target并且arg1設(shè)置為token的特殊消息,
// 根據(jù)參數(shù)when插入消息屏障创肥,在消息屏障之后的消息中的同步消息不會被執(zhí)行达舒,異步消息會優(yōu)先執(zhí)行,這一點后續(xù)消息處理邏輯中會詳細講解叹侄。
private int postSyncBarrier(long when) {
// Enqueue a new sync barrier token.
// We don't need to wake the queue because the purpose of a barrier is to stall it.
synchronized (this) {
final int token = mNextBarrierToken++;
final Message msg = Message.obtain();
msg.markInUse();
msg.when = when;
msg.arg1 = token;
Message prev = null;
Message p = mMessages;
if (when != 0) {
while (p != null && p.when <= when) {
prev = p;
p = p.next;
}
}
// 將消息屏障插入到when對應(yīng)的位置
if (prev != null) { // invariant: p == prev.next
msg.next = p;
prev.next = msg;
} else {
msg.next = p;
mMessages = msg;
}
return token;
}
}
// 根據(jù)postSyncBarrier方法的返回值移除消息屏障
public void removeSyncBarrier(int token) {
// Remove a sync barrier token from the queue.
// If the queue is no longer stalled by a barrier then wake it.
synchronized (this) {
Message prev = null;
Message p = mMessages;
while (p != null && (p.target != null || p.arg1 != token)) {
prev = p;
p = p.next;
}
if (p == null) {
throw new IllegalStateException("The specified message queue synchronization "
+ " barrier token has not been posted or has already been removed.");
}
final boolean needWake;
if (prev != null) {
prev.next = p.next;
needWake = false;
} else {
mMessages = p.next;
needWake = mMessages == null || mMessages.target != null;
}
p.recycleUnchecked();
// If the loop is quitting then it is already awake.
// We can assume mPtr != 0 when mQuitting is false.
if (needWake && !mQuitting) {
nativeWake(mPtr);
}
}
}
postSyncBarrier和removeSyncBarrier是隱藏的方法巩搏,應(yīng)用想要使用的話只有通過反射的方式。
源碼分析
Android消息機制(Handler機制)的核心就是Handler趾代、消息隊列(MessageQueue)和 消息循環(huán)(Looper)贯底,消息隊列負責(zé)存放消息;消息循環(huán)負責(zé)不斷從消息隊列中獲取消息并且將獲取到的消息交給Handler處理撒强;Handler負責(zé)將消息發(fā)送給消息隊列和處理消息循環(huán)獲取的消息禽捆。
接下來看一下Android消息機制中創(chuàng)建消息循環(huán)、發(fā)送消息和處理消息的邏輯
1 創(chuàng)建消息循環(huán)的邏輯
主線程默認是具有Android消息機制的飘哨,所以開發(fā)中只需要在需要時給子線程創(chuàng)建消息循環(huán)胚想,創(chuàng)建消息循環(huán)的模板代碼如下:
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
}
};
Looper.loop();
}
}).start();
上面run方法的3句代碼就是用來創(chuàng)建消息循環(huán)的,首先我們來看一下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類的prepare方法會先判斷當(dāng)前線程中是否保存了Looper實例芽隆,如果已經(jīng)保存了浊服,就會拋出一個運行時異常,否者就會創(chuàng)建一個Looper實例并且將其保存到當(dāng)前線程中摆马。所以Looper以線程作為作用域并且不同線程具有不同的數(shù)據(jù)副本臼闻。下面接著分析Looper實例的創(chuàng)建過程:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
Looper的構(gòu)造方法一共做了兩件事情:
1> 創(chuàng)建一個允許退出的MessageQueue的實例(因為quitAllowed為true),并且將其賦值給成員變量mQueue囤采,在子線程中創(chuàng)建的消息循環(huán)都是允許退出的述呐,并且當(dāng)所有的事情都完成以后應(yīng)該調(diào)用消息循環(huán)Looper中的quit或者quitSafely方法來退出消息循環(huán),否者線程會一直處于空閑等待狀態(tài)蕉毯。
2> 將當(dāng)前線程的實例賦值給成員變量mThread乓搬。
下面接著分析創(chuàng)建一個允許退出的MessageQueue的實例的過程:
MessageQueue(boolean quitAllowed) {
mQuitAllowed = quitAllowed;
mPtr = nativeInit();
}
MessageQueue的構(gòu)造方法一共做了兩件事情:
1> 保存允許退出的標(biāo)記
2> 通過調(diào)用native層的方法nativeInit來初始化MessageQueue實例。
到此Looper類的prepare方法分析完畢代虾,該方法會創(chuàng)建一個持有一個允許退出的消息隊列(即MessageQueue實例)的消息循環(huán)(即Looper實例)进肯,并且將該Looper實例保存到當(dāng)前線程的threadLocals中,但是此時的消息循環(huán)還沒有運行起來棉磨。
run方法的第2句代碼創(chuàng)建是用來創(chuàng)建一個Handler實例江掩,接下來我們分析一下Handler實例的創(chuàng)建過程:
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 that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
上面的代碼主要邏輯如下:
1 獲取當(dāng)前線程中的Looper實例,并且將其賦值給成員變量mLooper,如果當(dāng)前線程沒有Looper實例环形,就會拋出一個運行時異常策泣,相信這個異常提示大家都見過了,因此run方法的第2句必須在第1句的后面抬吟。
2 獲取Looper實例中的MessageQueue實例萨咕,并且將其賦值給成員變量mQueue。
3 成員變量mAsynchronous被設(shè)置為false火本。
run方法的第3句代碼是用來驅(qū)動消息循環(huán)的危队,在消息循環(huán)不退出的情況下run方法第3句代碼后面的代碼不會被執(zhí)行,繼而run方法的3句代碼的順序必須是上面模板代碼中的順序钙畔。
2 發(fā)送消息的邏輯
先通過如下的流程圖茫陆,整體的看一下發(fā)送消息的流程:
由上圖可知,Handler發(fā)送消息的方式有兩種刃鳄,分別是通過sendMessagexxx(以sendMessage方法為例)方法發(fā)送消息和通過postxxx(以post方法為例)方法發(fā)送消息盅弛,其實這兩種方式最終會調(diào)用enqueueMessage方法來發(fā)送消息, 先來看一Handler類的post方法:
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
可以看到post方法有一個Runnable類型的參數(shù)r叔锐,getPostMessage方法會創(chuàng)建一個callback為r的Message對象并且將其返回,源碼如下:
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
繼續(xù)看Handler類的sendMessage方法:
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
sendMessage方法也會調(diào)用sendMessageDelayed方法见秽,并且延遲時間也設(shè)置為0愉烙。
繼續(xù)看sendMessageDelayed方法:
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
sendMessageDelayed方法會先判斷延遲時間是否小于零,如果小于0解取,就將延遲時間設(shè)置為0步责,也就是要求消息的處理時間必須在消息發(fā)送時間之后,接著就會獲取當(dāng)前時間與延遲時間的和禀苦,也就是消息處理的準(zhǔn)確時間蔓肯,最后調(diào)用sendMessageAtTime方法并且將消息處理的準(zhǔn)確時間作為參數(shù)。sendMessageAtTime方法的源碼如下:
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);
}
sendMessageAtTime方法最終會調(diào)用Handler類的enqueueMessage方法振乏,Handler類的enqueueMessage方法首先會將消息msg的target設(shè)置為當(dāng)前的Handler實例蔗包,最后會調(diào)用MessageQueue類的enqueueMessage方法:
boolean enqueueMessage(Message msg, long when) {
......
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;
}
由上面的代碼可知,MessageQueue類的enqueueMessage方法首先會判斷消息隊列是否正在退出(mQuitting為true代表消息隊列正在退出)慧邮,如果消息隊列正在退出调限,則發(fā)送消息失敗,最終post和sendMessage方法也會返回false误澳。
在工作線程中如果手動為其創(chuàng)建了消息循環(huán)耻矮,那么當(dāng)所有的事情都完成以后應(yīng)該通過調(diào)用Looper類中的quit或者quitSafely方法來退出消息循環(huán),否者工作線程不會終止并且會一直處于空閑等待狀態(tài)忆谓,Looper類中的quit和quitSafely方法源碼如下:
public void quit() {
mQueue.quit(false);
}
public void quitSafely() {
mQueue.quit(true);
}
可以看到quit和quitSafely方法都會調(diào)用MessageQueue類中的quit方法來設(shè)置消息隊列正在被退出(即設(shè)置mQuitting為true)裆装,只不過調(diào)用MessageQueue類中的quit方法傳遞的參數(shù)分別是false和true(代表是否安全退出消息隊列),MessageQueue類的quit方法如下所示:
void quit(boolean safe) {
if (!mQuitAllowed) {
throw new IllegalStateException("Main thread not allowed to quit.");
}
synchronized (this) {
if (mQuitting) {
return;
}
mQuitting = true;
if (safe) {
removeAllFutureMessagesLocked();
} else {
removeAllMessagesLocked();
}
// We can assume mPtr != 0 because mQuitting was previously false.
nativeWake(mPtr);
}
}
由上面的代碼可知,是否安全退出消息循環(huán)的區(qū)別在于處理當(dāng)前消息隊列中未處理的消息的方式不同哨免,直接退出消息循環(huán)的處理方式對應(yīng)與MessageQueue 類的removeAllMessagesLocked方法茎活,安全退出消息循環(huán)的處理方式對應(yīng)與MessageQueue 類的removeAllFutureMessagesLocked方法,源碼如下:
private void removeAllMessagesLocked() {
Message p = mMessages;
while (p != null) {
Message n = p.next;
p.recycleUnchecked();
p = n;
}
mMessages = null;
}
private void removeAllFutureMessagesLocked() {
final long now = SystemClock.uptimeMillis();
Message p = mMessages;
if (p != null) {
if (p.when > now) {
removeAllMessagesLocked();
} else {
Message n;
for (;;) {
n = p.next;
if (n == null) {
return;
}
if (n.when > now) {
break;
}
p = n;
}
p.next = null;
do {
p = n;
n = p.next;
p.recycleUnchecked();
} while (n != null);
}
}
}
由上面的代碼可知铁瞒,removeAllMessagesLocked方法會將消息隊列中未處理的消息直接銷毀掉妙色,而removeAllFutureMessagesLocked方法會將消息隊列中比當(dāng)前時間靠后的消息銷毀掉并且其他消息正常處理掉。
繼續(xù)分析MessageQueue類的enqueueMessage方法接下來的源碼慧耍,從代碼中可以看出消息隊列就是一個按照消息執(zhí)行時間的先后順序存放消息的單向鏈表身辨,當(dāng)此時的消息隊列為空或者發(fā)送過來的消息執(zhí)行時間為0或者發(fā)送過來的消息執(zhí)行時間小于消息隊列中第一個消息的執(zhí)行時間時,就將消息作為消息隊列的頭并且設(shè)置needWake為mBlocked(即當(dāng)前消息隊列是阻塞狀態(tài)時需要被喚醒)芍碧;否者的話煌珊,就會遍歷整個消息隊列,按照時間先后的順序?qū)⑾⒉迦氲较㈥犃兄胁⑶以O(shè)置needWake為false(代表不需要喚醒)泌豆。
3 處理消息流程
先通過如下的流程圖定庵,整體的看一下處理消息流程:
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;
// 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();
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
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
msg.target.dispatchMessage(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();
}
}
Looper類的loop方法首先會獲取當(dāng)前線程的Looper實例,如果當(dāng)前線程沒有Looper實例踪危,就會拋出一個運行時異常蔬浙。接著通過一個無限循環(huán)來獲取消息隊列中需要被處理的消息,這樣消息循環(huán)就被驅(qū)動起來了贞远;無限循環(huán)中通過MessageQueue類的next方法來獲取即將需要被處理的消息畴博,消息循環(huán)退出的唯一條件是MessageQueue類的next方法返回null,MessageQueue類的next方法源碼如下:
Message next() {
...
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
...
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) {
// 遇到消息屏障蓝仲,找到消息屏障后面第一個異步消息
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
// 最近的消息還沒有到執(zhí)行的時間. 計算線程休眠的時間并且超時后喚醒線程
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// 最近的消息可以被執(zhí)行俱病,直接從消息隊列中移除并且返回該消息
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 {
// 消息隊列中沒有消息時,nextPollTimeoutMillis設(shè)置為-1袱结,即永久休眠線程
nextPollTimeoutMillis = -1;
}
// 當(dāng)前的消息隊列正在退出中亮隙,如果消息隊列中已經(jīng)沒有消息則退出消息循環(huán)
if (mQuitting) {
dispose();
return null;
}
// 當(dāng)消息隊列為空或者第一條消息還沒有到執(zhí)行的時間,即此時處于空閑狀態(tài)垢夹,獲取空閑時需要執(zhí)行的 idle handlers 的數(shù)量
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);
}
// 執(zhí)行 idle handlers
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;
}
}
上面代碼中的nativePollOnce方法是一個JNI方法溢吻,該方法作用是使線程進入休眠狀態(tài),以節(jié)省CPU資源棚饵,休眠時長為傳入該方法的第二個參數(shù)nextPollTimeoutMillis的值煤裙,在此期間可以通過JNI方法nativeWake喚醒該線程或者超時后線程自動會被喚醒;無限for循環(huán)開始時傳入的值為0噪漾,表示不等待硼砰;當(dāng)消息隊列的頭消息的執(zhí)行時間比當(dāng)前時間靠后,就會將消息隊列的頭消息的執(zhí)行時間和當(dāng)前時間的差值保存到nextPollTimeoutMillis變量中欣硼,當(dāng)消息隊列中為null時题翰,將-1(-1代表永久處于休眠狀態(tài))保存到nextPollTimeoutMillis變量中。
所以MessageQueue類的next方法返回null只有一種可能:mQuitting的值為true(退出消息循環(huán)會將mQuitting的值設(shè)置為true)并且消息隊列為空。
在Looper類的loop方法中豹障,MessageQueue類的next方法獲取即將需要被處理的消息后冯事,接著調(diào)用消息的target(target就是發(fā)送消息的Handler實例)的dispatchMessage方法來處理消息,Handler類的dispatchMessage方法如下所示:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
上面的代碼邏輯很簡單血公,就是Handler處理消息的流程昵仅,可以對照上面的Handler 處理消息流程圖 進行理解;sendMessagexxx方法發(fā)送的消息最終會被Handler類handleMessage方法處理累魔,postxxx方法發(fā)送的消息最終會被Handler類handleCallback方法處理摔笤;如果通過包含Callback接口類型參數(shù)的構(gòu)造方法創(chuàng)建Handler實例,例如public Handler(Callback callback)垦写,那么sendMessagexxx方法發(fā)送的消息最終會被Callback接口的handleMessage方法處理吕世。
實例講解
對于消息循環(huán)模型的使用可以分為兩種情況:
1> 工作線程向UI線程發(fā)送消息
2> UI線程向工作線程發(fā)送消息
1 工作線程向UI線程發(fā)送消息的常見實現(xiàn)方式有4種,
1> 第一種實現(xiàn)方式的實例代碼如下:
mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if(1 == msg.what){
android.util.Log.i(TAG,"msg.what = " + msg.what);
}
}
};
new Thread(new Runnable() {
@Override
public void run() {
mHandler.sendEmptyMessage(1);
}
}).start();
代碼邏輯很簡單梯投,這里就不再解析了命辖。
2> 通過Activity的runOnUiThread方法,該方法的源碼如下:
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
該方法實現(xiàn)邏輯很簡單分蓖,如果當(dāng)前線程不是UI線程尔艇,就通過Handler的post向UI線程發(fā)送消息,否者的話么鹤,就直接執(zhí)行action(Runnable類型的實例)的run方法漓帚。
3> 通過View的post方法,這種方式簡單方便午磁。
4> 由于工作線程向UI線程發(fā)送消息的場景在日常開發(fā)經(jīng)常被用到,所以Google為我們提供了HandlerThread類來實現(xiàn)該場景毡们。
2 UI線程向工作線程發(fā)送消息的常見實現(xiàn)方式有2種迅皇,
1> 第一種實現(xiàn)方式的實例代碼如下:
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Looper.prepare();
mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if(1 == msg.what){
android.util.Log.i(TAG,"msg.what = " + msg.what);
}
}
};
Looper.loop();
}
}).start();
mHandler.sendEmptyMessage(1);
對上面的代碼進行分析:按照一種的模板代碼創(chuàng)建消息循環(huán),然后通過mHandler向工作線程發(fā)送消息衙熔。
2> 由于UI線程向工作線程發(fā)送消息的場景在日常開發(fā)經(jīng)常被用到登颓,所以Google為我們提供了AsyncTask類來實現(xiàn)該場景,關(guān)于AsyncTask類的使用可以參考Android 線程與進程红氯。