寫在前面

圖片來源
源碼分析
首先創(chuàng)建Handler
Handler handler = new Handler();
查看Handler.java$handler()構(gòu)造方法的核心源碼
public Handler() {
this(null, false);
}
public Handler(Callback callback, boolean async) {
...... //代碼省略
// mLooper是一個(gè)Looper對(duì)象,獲取Looper
mLooper = Looper.myLooper();
//在主線程中可以直接創(chuàng)建Handler,原因下面會(huì)分析,
//在子線程中需要先初始化Looper也就是調(diào)用Looper.prepare()方法,否則就會(huì)報(bào)下面異常
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
//mQueue是一個(gè)MessageQueue對(duì)象
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
上面說到在主線程中可以直接創(chuàng)建Handler,其原因是因?yàn)閼?yīng)用程序的入口為ActivityThread類的main方法。
查看ActivityThread.java$main方法的核心源碼
public static void main(String[] args) {
...... //代碼省略
//創(chuàng)建主線程的Looper
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"));
}
//對(duì)MessageQueue消息進(jìn)行循環(huán)將取出的Message交付給相應(yīng)的Handler ,后面會(huì)對(duì)其源碼進(jìn)行分析
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
上面解釋了在主線程創(chuàng)建Handler是因?yàn)樵诔绦騽?chuàng)建的時(shí)候已經(jīng)創(chuàng)建了主線程的Looper 。
我們知道Handler要發(fā)送消息的話需要調(diào)用sendMessage方法
那我們接著查看Handler.java$sendMessage方法源碼
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
//繼續(xù)查看
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
//繼續(xù)查看
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);
}
//繼續(xù)查看
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
//msg.target是一個(gè)Handler對(duì)象,this指的就是Handler因?yàn)樵摲椒ㄔ贖andler類中
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
//這里調(diào)用的是MessageQueue消息隊(duì)列的enqueueMessage方法
return queue.enqueueMessage(msg, uptimeMillis);
}
上面說到msg.target是handler 我們查看Message.target源碼
Handler target;
發(fā)現(xiàn)target確實(shí)是Handler對(duì)象,其作用是為了記錄所發(fā)消息對(duì)應(yīng)的handler,也是為了把消息分發(fā)到對(duì)應(yīng)的Handler
繼續(xù)分析MessageQueue消息隊(duì)列enqueueMessage方法源碼
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) {
//判斷是否調(diào)用了quit()方法如果調(diào)用了則無法發(fā)送消息
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w("MessageQueue", e.getMessage(), e);
msg.recycle();
return false;
}
msg.markInUse();
msg.when = when;
// 把傳進(jìn)來的message按照延遲時(shí)間的先后添加到mMessage中
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;
}
//如果Looper.loop()是休眠狀態(tài)則執(zhí)行nativeWake方法喚醒Looper
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
在Looper.prepare()的同時(shí),總會(huì)執(zhí)行l(wèi)ooper.loop()語句與之對(duì)應(yīng)。
接著查看Looper.java$loop方法的源碼
public static void loop() {
//獲取looper對(duì)象確保Looper的唯一性
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();
//循環(huán)并分發(fā)message
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 {
//分發(fā)msg給給對(duì)應(yīng)的Handler msg.target為handler對(duì)象
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);
}
//message數(shù)據(jù)回收
msg.recycleUnchecked();
}
}
Looper.loop()方法作用主要是 for循環(huán)不斷從MessageQueue隊(duì)列中獲取Message,并分發(fā)給對(duì)應(yīng)target的Handler。
先查看MessageQueue$next方法的核心代碼
Message next() {
......//代碼省略
//0為出隊(duì)狀態(tài),-1為等待狀態(tài)
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());
}
//按時(shí)間順序?qū)essage取出
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 {
// 消息隊(duì)列中沒有信息,則將nextPollTimeoutMillis 設(shè)置為1,下次循環(huán)時(shí)消息隊(duì)列則處于等待狀態(tài)
nextPollTimeoutMillis = -1;
}
...... //代碼省略
}
接著查看Handler.java$dispatchMessage方法源碼
public void dispatchMessage(Message msg) {
//Message對(duì)象的callback不為空(runnable),交給callback處理,
//這種大多使用post方法傳入runnable對(duì)象時(shí)會(huì)調(diào)用
if (msg.callback != null) {
handleCallback(msg);
} else {
//handler的callback不為空,交給callback處理,callback
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
//前兩種都沒有的情況下交給handlerMessage處理
//也就是我們?cè)诖a中重寫的handlerMessage方法
handleMessage(msg);
}
}
以上就是我對(duì)handler消息傳遞機(jī)制的理解。
最后如果有理解錯(cuò)誤之處歡迎指正。