有時我們需要在子線程中進(jìn)行耗時的I/O操作,可能是讀取文件或者訪問網(wǎng)絡(luò)等,當(dāng)耗時操作完成后可能需要UI上做一些改變,由于android的開發(fā)規(guī)范限制,我們不能在子線程中訪問UI控件,否則會觸發(fā)異常,這個時候通過Handler就可以將更新UI的操作切換到主線程中。
概述
Handler的運行需要底層的MessageQueue和Looper的支撐。MessageQueue的中文翻譯是消息隊列,它的內(nèi)部存儲了一組消息,以隊列的形式對外提供插入和刪除工作。雖然叫消息隊列,但內(nèi)部存儲結(jié)構(gòu)并不是真正的隊列,而是采用單鏈表的數(shù)據(jù)結(jié)構(gòu)來存儲消息列表。Looper的中文翻譯為循環(huán),由于MessageQueue只是一個消息的存儲器,它不處理消息,而Looper填補了這功能。Looper中還有一個特殊的概念,那就是ThreadLocal,ThreadLocal并不是線程,它的作用是可以在每個線程中存儲數(shù)據(jù)。我們知道Handler創(chuàng)建的時候會采用當(dāng)前線程的Looper來構(gòu)造消息循環(huán)系統(tǒng),那么Handler內(nèi)部如何獲取當(dāng)前線程Looper呢,這就要用到ThreadLocal了,ThreadLocal可以在不同線程中互不干擾地存儲并提供數(shù)據(jù),通過ThreadLocal可以輕松獲得每個線程的Looper。當(dāng)然需要注意的是,線程默認(rèn)沒有Looper,如果需要使用Handler就必須為線程創(chuàng)建Looper。我們的UI線程,它就是ActivityThread,ActivityThread被創(chuàng)建時就會初始化Looper,這也是在主線程中默認(rèn)可以使用Handler的原因。如果需要在子線程中使用Handler,需如下操作: 創(chuàng)建Looper
new Thread(new Runnable() {
public void run() {
Looper.prepare();
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
Toast.makeText(getApplicationContext(), "handler msg", Toast.LENGTH_LONG).show();
}
};
handler.sendEmptyMessage(1);
Looper.loop();
};
}).start();
Handler創(chuàng)建完畢后,這個時候其內(nèi)部的Looper以及MessageQueue就可以和Handler一起協(xié)同工作了,然后通過Handler的Handler的send方法發(fā)送一個消息到Looper中去處理,也可以通過post方法將一個Runnable投遞到Looper中。其實post方法最終也是通過send方法調(diào)用的,它會調(diào)用MessageQueue的enqueueMessage方法將這個消息放入消息隊列中,然后Looper發(fā)現(xiàn)有新消息到來時,就會處理這個消息,最終消息中的Runnable或者Handler的handleMessage方法就會調(diào)用。注意Looper是運行在創(chuàng)建Handler所在的線程中的,這樣一來Handler的業(yè)務(wù)邏輯就被切換到創(chuàng)建Handler所在的線程中去執(zhí)行了,這個過程可以用下圖表示。

相關(guān)概念
關(guān)于 Handler 異步通信機制中的相關(guān)概念如下:
ThreadLocal,Message、Message Queue、Looper,接下來結(jié)合源碼分析它們的工作原理。
ThreadLocal的工作原理
ThreadLocal是一個線程內(nèi)部的數(shù)據(jù)存儲類,通過它可以在指定的線程中存儲數(shù)據(jù),數(shù)據(jù)存儲后,只有在指定的線程中可以獲取存儲的數(shù)據(jù),對于其他線程則無法獲取到數(shù)據(jù)。 在日常開發(fā)中用到ThreadLocal的地方較少, 一般來說,當(dāng)某些數(shù)據(jù)是以線程為作用域并且不同線程具有不同數(shù)據(jù)副本時,可以考慮采用ThreadLocal。比如對于Handler來說,它需要獲取當(dāng)前線程的Looper,很顯然Looper的作用域就是線程并且不同線程具有不同的Looper,這個時候通過ThreadLocal就可以輕松實現(xiàn)Looper在線程中存取。下面通過實際的例子來演示ThreadLocal的真正含義。首先定義一個ThreadLocal對象,選擇Boolean類型,如下所示。
private ThreadLocal<Boolean> mBooleanThreadLocal=new ThreadLocal<Boolean>();
然后分別在主線程,子線程1和子線程2中設(shè)置和訪問它的值,代碼如下:
mBooleanThreadLocal.set(true);
Log.d("ThreadLocal","mainThread="+mBooleanThreadLocal.get());
new Thread("Thread1"){
@Override
public void run() {
mBooleanThreadLocal.set(false);
Log.d("ThreadLocal","thread1="+mBooleanThreadLocal.get());
}
}.start();
new Thread("Thread2"){
@Override
public void run() {
Log.d("ThreadLocal","thread2="+mBooleanThreadLocal.get());
}
}.start();
上述代碼中,子線程設(shè)置為true,子線程1中設(shè)置false,子線程2中不設(shè)置值,日志如下:
ThreadLocal: mainThread=true
ThreadLocal: thread1=false
ThreadLocal: thread2=null
從上面日志看,不同線程中訪問的同一個ThreadLocal對象,獲取值卻不一樣。不同線程訪問同一個ThreadLocal的get方法,ThreadLocal內(nèi)部會從各自線程中取出一個數(shù)組,然后再從數(shù)組中根據(jù)當(dāng)前ThreadLocal的索引去查找對應(yīng)的value值。下面我們來看看set和get方法,首先看ThreadLocal的set方法,如下:
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
從上面的set方法中,首先通過getMap方法獲取當(dāng)前線程中的ThreadLocalMap數(shù)據(jù),如果為空就對其初始化。我們再看看 map.set方法
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)]) {
ThreadLocal<?> k = e.get();
if (k == key) {
e.value = value;
return;
}
if (k == null) {
replaceStaleEntry(key, value, i);
return;
}
}
tab[i] = new Entry(key, value);
int sz = ++size;
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
我們再來看看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();
}
ThreadLocal的get方法,同樣是取出當(dāng)前線程的ThreadLocalMap對象,如果這個對象為null就返回初始值,初始值由ThreadLocal的initialValue方法來描述,默認(rèn)為null。
MessageQueue的工作原理
主要包含插入和讀取操作,對應(yīng)的方法分別為enqueueMessage和next。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;
}
從enqueueMessage的實現(xiàn)來看,主要是單鏈表的插入操作,下面看一下next的源碼:
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();
}
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) {
// 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) {
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;
}
// 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);
}
// 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;
}
}
可以發(fā)現(xiàn)next方法是一個無限循環(huán)的方法,如果消息隊列中沒有消息,那么next方法一直阻塞在這里,當(dāng)有新消息時,next方法會返回這條消息。
Looper的工作原理
Looper會不停地從MessageQueue中查看是否有新消息,如果有新消息就立即處理,否則就一直阻塞在那里,首先看下它的構(gòu)造方法,在構(gòu)造方法中會創(chuàng)建一個MessageQueue,然后將當(dāng)前線程的對象保存起來。
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
我們知道Handler的工作需要Looper,沒有Looper的線程會報錯,上面也講述了如何為線程創(chuàng)建Looper,通過Looper.prepaer()即可為當(dāng)前線程創(chuàng)建一個Looper,通過Looper.loop()來開啟消息循環(huán),如下:
new Thread("Thread1"){
@Override
public void run() {
Looper.prepare();
Handler handler=new Handler();
Looper.loop();
}
}.start();
Looper除了prepare方法外,還提供了prepareMainLooper()方法,這個方法主要是給主線程創(chuàng)建Looper使用的,其本質(zhì)也是通過prepare方法。由于主線程的Looper比較特殊,所以Looper提供了一個getMainLooper()方法,通過它可以在任何地方獲取主線程的Looper。Looper最重要的一個方法是loop方法,只有調(diào)用了loop后,消息循環(huán)系統(tǒng)才會真正起作用,如下:
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
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;
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();
}
}
Looper的loop方法是一個死循環(huán),會調(diào)用MessageQueue的next方法來獲取新消息,而next是一個阻塞操作,當(dāng)沒有消息時,next方法會一直阻塞在那里,這也導(dǎo)致loop方法會一直阻塞。如果MessageQueue的next方法返回了新消息,Looper會處理這條消息: msg.target.dispatchMessage(msg),這里的 msg.target是發(fā)送這條消息的Handler對象,這樣Handler發(fā)送的消息最終又交給它的dispatchMessage方法來處理了,最終回調(diào)復(fù)寫的handleMessage(Message msg)。
Handler的工作原理
Handler的工作主要包含消息的發(fā)送和接收過程。消息的發(fā)送可以通過send,post的一系列方法實現(xiàn)。post的方法最終也是通過send來實現(xiàn),發(fā)送一條消息的典型過程如下:
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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
可以發(fā)現(xiàn),Handler發(fā)送消息就是向消息隊列插入一條消息,MessageQueue的next方法就會返回這條消息給Looper,Looper收到消息后就開始處理,最終消息由Looper交由Handler處理,即上面說的dispatchMessage方法被調(diào)用,代碼如下:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
Handler處理消息的過程如下:
首先檢查Message的callback是否為mCallbacknull,不為null就通過handleCallback來處理消息,Message的callback是一個Runnable對象,實際是Handler的post方法傳遞的Runnable參數(shù),handleCallback邏輯如下:
private static void handleCallback(Message message) {
message.callback.run();
}
其次,檢查mCallback是否為null,不為null就調(diào)用mCallback的handleMessage方法處理消息,mCallback是個接口,定義如下:
/**
* Callback interface you can use when instantiating a Handler to avoid
* having to implement your own subclass of Handler.
*/
public interface Callback {
/**
* @param msg A {@link android.os.Message Message} object
* @return True if no further handling is desired
*/
public boolean handleMessage(Message msg);
}
通過Callback可以采用如下方式來創(chuàng)建Handler對象:Handler handler=new Handler(callback)。那么Callback的意義是什么呢,源碼的注釋說明了,可以用來創(chuàng)建一個Handler的實例但并不需要派生Handler的子類。日常開發(fā)中,創(chuàng)建Handler,最常見是派生一個Handler的子類并重寫handlerMessage方法來處理具體消息,而Callback給我們提供了另一種使用Handler的方式。
最后,調(diào)用Handler的handleMessage方法來處理消息。
Handler還有一個構(gòu)造方法,就是通過一個特定的Looper來構(gòu)造Handler,實現(xiàn)如下:
public Handler(Looper looper) {
this(looper, null, false);
}
下面看下Handler的默認(rèn)構(gòu)造方法
public Handler() {
this(null, false);
}
this(null, false)實現(xiàn)如下,很明顯,如果當(dāng)前線程沒有創(chuàng)建Looper,就會拋出 "Can't create handler inside thread that has not called Looper.prepare()"這個異常。
public Handler(Callback callback, boolean async) {
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;
}
以上就是Handler相關(guān)內(nèi)容