Handler常用來更新UI。網上有很多講解Handler的東西,我這就不多講了,這裡主要從源碼入手講一點更深的原理。
簡單來講,Handler的用法就是,用handler發出一個Message,然後handler的handleMessage()就會被調用,處理該Message。典型的使用場景就是子線程裡做耗時操作(如下載下傳圖檔),操作完成後,在子線程裡用handler發出一個消息,在handleMessage()裡更新UI。
handler發出的Message會被存進一個MessageQueue,有一個叫Looper的對象,不停的周遊這個Queue,取出裡面的Message,然後交給發出這個Message的Handler,handler收到後就用handleMessage()來處理。而MessageQueue正是在Looper的構造方法裡生成的,也就是---MessageQueue是Looper對象的一個執行個體變量
public final class Looper {
... ...
final MessageQueue mQueue;
final Thread mThread;
............
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
/**
* 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
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
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();
}
}
........
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
每條線程,可以沒有Looper對象,但最多隻能有一個。主線程已經預設有一個,是以我們可以在主線程裡直接自定義Handler來處理消息。如果在子線程裡又該怎麼使用Handler?
class MyHandlerThread1 extends Thread{
Handler handler;
@Override
public void run() {
Looper.prepare();
handler=new Handler()
{
@Override
public void handleMessage(Message msg) {
//處理msg
}
};
Looper.loop();
}
}
實際Looper對象是通過調用Looper類的靜态方法prepare()生成的,因為Looper的構造方法是private的。最終prepare()方法是這樣的
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就是一個Looper對象。不明白ThreadLocal的可以先去看看。Looper.loop()的作用就是開啟對MessageQueue的周遊。周遊如下
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 traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
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();
}
}
通過for( ; ; )不停周遊。這麼看來,那豈不要永遠周遊下去了,沒關系,關鍵在這裡:
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
當queue傳回null時,周遊也就結束了。什麼情況下傳回null呢?看MessageQueue源碼:
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;
}
...............
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}
........
}
當ptr==0或者mQuitting的時候,沿着源碼一步步分析,就會知道,能産生這兩個效果的是程式退出或者直接調用looper的quit()方法。handler.getLooper().quit()之後,周遊也就終止了。
那麼,消息又是怎麼到達發出這個消息的Handler的呢?
注意:loop( )方法裡的一句
msg.target.dispatchMessage(msg);
這個target正是發送這個msg的Handler,繼續往下看就會發現,dispatchMessage最終調用了handler(或handler的callback)的handleMessage()。更詳細的用法可以自己去看源碼了。
不禁想到一個問題,就是延時發送
handler.sendEmptyMessageDelayed(what,delayMillis)
究竟是消息先發送了出去等着時機到了再執行,還是等着時機到了才發送消息?
可以看到,是等着時機到了才發送消息。
由于是周遊一個Queue,然後調用handler的handleMessage()去執行,是以對于同一個handler來說,它的消息都是串行執行的,而且handleMassge()是在handler所在的線程裡執行的。
HandlerThread是已經包裝好了可以使用Handler的子線程。自己百度去吧。