本文以Handler對象的創建和消息發送爲切入點,講述背後的實現原理。
一. Handler對象創建的背後過程
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;
}
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
返回當前線程的Looper實例化對象
/**
* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
*/
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
從Handler構造方法來看,每個Handler對象,都擁有成員變量looper對象mLooper,消息隊列對象mQueue,而這種消息隊列對象也是mLooper成員變量,這個Looper對象要麼是使用者直接傳進來的,要麼是通過Looper.myLooper()得到的。
下面再來看看Looper的創建,Looper對象對外提供靜態方法prepare() 創建,但構造方法是私有的,不能直接實例化。
每個線程至多有一個Looper對象,否則會拋運行時異常。創建Looper對象時,會創建一個MessageQueue對象作爲其成員變量。
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();
}
MessageQueue是由Message對象組織成鏈表結構的消息隊列,Message對象是序列化對象,除了通信的數據外,一個很關鍵的是成員變量就是target用來存儲通信Handler對象。
由上面的代碼片段可知,要實現Handler線程間通信,必須要首先通過Looper的prepare()實例化對象,但是有些同學可能平時使用Handler時都沒有操作過Looper,那Looper初始化在哪裏進行的呢。
其實在app啓動的時候,ActivityThread main方法裏都已經通過prepareMainLooper()創建了,它是主線程的Looper實例,相比子線程的初始化稍有不同。具體參看如下代碼:
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
SamplingProfilerIntegration.start();
// CloseGuard defaults to true and can be quite spammy. We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
// Set the reporter for event logging in libcore
EventLogger.setReporter(new EventLoggingReporter());
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
二. Handler對象觸發線程通信的背後過程
當子線程通過Handler的sendMessage觸發消息時,是怎麼和主線程通信的呢,這個時候Looper就真正起作用了,看Looper的loop()方法:
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the 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();
}
}
通過上面的代碼可知:這個是死循環代碼,一直從MessageQueue裏取msg,通過拿到msg的target對象,上面有特意強調過這個就是我們的Handler對象,調用它的dispatchMessage方法,具體實現看源代碼:
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
看到handleMessage方法估計大家都熟悉了,這就是我們經常重寫Handler類的handleMessage方法,那麼loop()方法又在哪裏調用的呢,其實細心的同學在上面的ActivityThread main方法裏都已經發現了,在Looper初始化成功後,就會調用loop()方法一直檢查是否有消息,有消息就調用這個handler對象的dispatchMessage方法,至此子線程和主線程通信過程結束了。
聰明的同學可能會有疑問,Android中爲什麼主線程不會因爲Looper.loop()裏的死循環卡死?
其實主線程確實會一直卡在loop()循環裏,只是因爲主線程又開闢了其它Binder子線程來處理,你沒有感覺到而已,具體分析參看知乎牛人的回答:http://www.zhihu.com/question/34652589
總結:Thread ,Looper,MessageQueue,Message,Handler的之間關係
一個Thread至多有一個Looper,需要通過Looper.prepare()初始化和Looper.loop()處理分發給對應的Handler對象處理
一個Looper有且有一個MessageQueue,通過Looper.loop()取出MessageQueue的Message進行處理,但是可以服務於多個Handler對象。
MessageQueue是由Message對象組織成鏈表結構的消息隊列,而每個Message對象都唯一對應一個Handler對象。