原文鏈接:https://yuchao.wang/article?id=42
Android中的Handler機制,每次整理都會有新的發(fā)現(xiàn)。
常見用法
- 方式一:send
查看源碼我們會發(fā)現(xiàn),無論是 handler.sendXXX 還是 message.sendXXX 最后都會調(diào)用
handler.sendMessageAtTime(Message msg, long uptimeMillis)
- 方式二:post
查看源碼我們會發(fā)現(xiàn),所有的 handler.postXXX 方法 都是先通過
handler.getPostMessage(Runnable r)
將 Runnable 封裝為 Message 最后同樣調(diào)用
handler.sendMessageAtTime(Message msg, long uptimeMillis)
- 方式三:looper(官方推薦)
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
Handler
public class Handler{
final MessageQueue mQueue; // 消息隊列
final Looper mLooper; // 消息泵
final Callback mCallback; // 消息回調(diào)
...
public interface Callback {
public boolean handleMessage(Message msg);
}
...
}
通過源碼我們會發(fā)現(xiàn),每個Handler綁定了一個MessageQueue和Looper
Message
public final class Message implements Parcelable {
public Messenger replyTo; // 進程間通信 Reference to a Handler, which others can use to send messages to it.
long when; // 時間
Bundle data; // 數(shù)據(jù)
Handler target; // 綁定的Handler
Runnable callback; // 回調(diào)
Message next; // Message中一直多緩存一個Message對象
}
通過源碼我們會發(fā)現(xiàn),每個Message都會關(guān)聯(lián)到發(fā)送消息的Handler上
MessageQueue
private native static long nativeInit();
private native static void nativeDestroy(long ptr);
private native static void nativePollOnce(long ptr, int timeoutMillis);
private native static void nativeWake(long ptr);
Message next() {
...
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
...
}
}
boolean enqueueMessage(Message msg, long when) {
...
synchronized (this) {
...
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
通過源碼我們發(fā)現(xiàn),如果通過queue.next()獲取消息,方法中用了一個死循環(huán)來處理,這樣一旦MessageQueue中有Message,那么queue.nativeWake(),如果消息為空,那么queue.nativePollOnce()就會阻塞。
Looper
public final class Looper {
// sThreadLocal.get() will return null unless you've called prepare().
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
private static Looper sMainLooper; // guarded by Looper.class
final MessageQueue mQueue;//消息隊列
final Thread mThread;//關(guān)聯(lián)線程
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));
}
public static Looper myLooper() {
return sThreadLocal.get();
}
}
通過源碼我們發(fā)現(xiàn),Looper里面沒有關(guān)聯(lián)Handler,其實Looper的靜態(tài)變量sThreadLocal通過prepare()和myLooper()可以關(guān)聯(lián)Looper和Handler。因為Handler的非Looper構(gòu)造方法如下
public Handler(Callback callback, boolean async) {
...
mLooper = Looper.myLooper();
...
}
通過Looper源碼我們還發(fā)現(xiàn),每個Looper都會關(guān)聯(lián)一個Thread和一個MessageQueue,那么 Handler 到底是怎么處理消息的呢?這里就需要Looper.prepare()和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(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
...
msg.target.dispatchMessage(msg);
...
msg.recycleUnchecked(); // 回收消息
}
}
通過源碼我們了解到,一個Thread中的Handler發(fā)送Message到MessageQueue中,Looper啟動以后,循環(huán)從MessageQueue中取出Message并分發(fā)到對應的handler中進行處理handlerMessage。
UI主線程
我們繼續(xù)查看Looper源碼
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
public static Looper getMainLooper() {
synchronized (Looper.class) {
return sMainLooper;
}
}
上述兩個方法貌似是UI主線程調(diào)用的方法,我們繼續(xù)查看ActivityThread里面的main方法
public static void main(String[] args) {
...
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"));
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
}
通過源碼我們發(fā)現(xiàn),應用在啟動完成后,就已經(jīng)啟動了UI主線程的Looper和Handler,并且啟動了Handler機制的心臟,消息泵Looper.loop(),因此我們可以在UI主線程直接或者使用Handler調(diào)用postXXX方法來更新UI。
總結(jié)
- 每個
Thread只對應一個Looper - 每個
Looper對應一個MessageQueue - 每個
MessageQueue中有N個Message - 每個
Message最多對應一個Handler來處理事件 - 每個
Thread可以對應多個Handler
Handler機制是Android設(shè)計的相當精巧的一個機制,還有很多代碼可以深入研究,比如remove、消息銷毀、消息回收、并發(fā)處理等,這里就不再贅述了。
