Handler主要用于線程切換烟瞧,一個典型的應(yīng)用場景是:子線程通過Handler更新主線程UI
本文將從源碼上來介紹Handler的實現(xiàn)原理
CSDN地址:http://blog.csdn.net/myterabithia/article/details/58603639
Handler的工作流程
先看一張圖:
主要流程如下:
- 構(gòu)造Message對象
- 通過Handler將Message發(fā)送到MessageQueue
- Looper從MessageQueue里取出Message對象
- Looper調(diào)用Message對象里保存的Handler對象的dispatchMessage方法將Message的處理移交給Handler
那么Looper和MessageQueue是哪來的呢伞辛?看一下Handler的構(gòu)造方法:
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();//獲取Handler所在線程的Looper币绩。
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;//獲取Looper里的MessageQueue
mCallback = callback;
mAsynchronous = async;
}
如果mLooper為空則直接拋異常了,所以如果不是在主線程創(chuàng)建Handler之前一定要在子線程里調(diào)用Looper.prepare()準(zhǔn)備好一個Looper瘸羡。Looper.prepare()會調(diào)用Looper的構(gòu)造方法創(chuàng)建一個Looper漩仙,在Looper的構(gòu)造方法中又創(chuàng)建了一個MessageQueue。
下面通過源碼來看這幾個步驟是如何實現(xiàn)的
1.構(gòu)造Message對象
或者犹赖,直接
Message message = new Message();
各種方式在使用效果上最后的差別不大队他,任選其一即可。
2.通過Handler將Message發(fā)送到MessageQueue
//Handler
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;//注意這一句峻村,將target對象指向當(dāng)前handler
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);//將Message入消息隊列
}
左右的發(fā)送消息的方法最終都調(diào)用到了這個方法麸折,顧名思義,這個方法將Message對象添加到MessageQueue隊列,在入隊之前,將message的target對象賦值為當(dāng)前handler對象筷频,最后會通過這個target對象來處理這個message。
//MessageQueue
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
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其實是一個單鏈表,所以很多操作都是單鏈表的操作捌浩。如果p==null(當(dāng)前隊列為空)或者when==0(通過sendMessageAtFrontOfQueue方法發(fā)送的消息)或者when<p.when的時就將此消息插入到隊的頭部放刨,否則按時間先后順序入隊,這里的時間是什么時間呢尸饺?看下面代碼,其實是SystemClock.uptimeMillis() + delayMillis助币,也就是當(dāng)前開機時間的毫秒數(shù)加上我們設(shè)置的延時浪听。
//Handler
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
3.Looper從MessageQueue里取出Message對象
當(dāng)創(chuàng)建好Looper后,會調(diào)用Looper.loop()方法不斷的從MessageQueue里讀取Message眉菱,如果是主線程迹栓,那么Looper.loop()方法在系統(tǒng)創(chuàng)建進(jìn)程的時候就已經(jīng)調(diào)用過了,如果在子線程則需要自己調(diào)用俭缓。
//Looper
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;
}
...省略
try {
//將msg的處理移交給Handler
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
...省略
}
}
Message msg = queue.next(); // might block
通過一個無限的for循環(huán)中通過MessageQueue.next()讀消息克伊,如果隊列沒有消息則阻塞酥郭。在next方法中,如果隊首的消息執(zhí)行時間還沒到愿吹,就設(shè)置一個等待時間不从,如果到了就從鏈表里取出來,然后返回犁跪。
//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.
...
for(;;){
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
...
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;
}
...
}
}
}
4.調(diào)用Handler的dispatchMessage方法將Message的處理移交給Handler
在Loopermsg.target.dispatchMessage(msg)
讓Handler去處理椿息,這里的target就是在調(diào)用Handler.的enqueueMessage方法時賦值得,忘記了可以去步驟2里再看一下坷衍。
至此寝优,處理流程又回到了Handler的dispatchMessage方法里,邏輯很簡單枫耳,一個細(xì)節(jié)要注意乏矾,如果mCallback不為空,是不會調(diào)用handleMessage迁杨,這里mCallback是在創(chuàng)建Handler的時候就傳進(jìn)來的妻熊,所以使用Handler處理消息,要么在創(chuàng)建Handler的時候傳入一個Callback仑最,要么重寫handleMessage方法扔役。
//Handler
/**
* 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);
}
}
private static void handleCallback(Message message) {
message.callback.run();
}
/**
* Subclasses must implement this to receive messages.
*/
public void handleMessage(Message msg) {
}