前言
相信大家在開發(fā)過(guò)程中都使用過(guò)Handler,其中的原理是否已經(jīng)清楚了呢汁汗?如果沒有的話,看文章來(lái)一起分析一下吧~
源碼解析
首先我們查看Handler的無(wú)參構(gòu)造方法:
public Handler() {
this(null, false);
}
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;
}
在這里調(diào)用了Looper的myLooper方法:
/**
* 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();
}
這里使用了ThreadLocal栗涂,它的功能簡(jiǎn)單來(lái)說(shuō)就是:使用它的get方法時(shí)知牌,它會(huì)返回當(dāng)前線程對(duì)應(yīng)的變量值,在這里斤程,也就是返回當(dāng)前線程對(duì)應(yīng)的Looper角寸,如果當(dāng)前線程沒有關(guān)聯(lián)上Looper的話,就會(huì)返回null,那么扁藕,怎么才能讓線程和Looper關(guān)聯(lián)上呢墨吓?答案是Looper的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));
}
可以看到,這里我們就將一個(gè)Looper和當(dāng)前線程關(guān)聯(lián)了起來(lái)纹磺,這里得到了第一條重要的結(jié)論:
如果要在某一個(gè)線程中創(chuàng)建Handler來(lái)接收消息并處理帖烘,那么首先要調(diào)用Looper的prepare方法來(lái)為當(dāng)前線程創(chuàng)建一個(gè)Looper,然后調(diào)用Looper.loop()開啟消息循環(huán)(下文會(huì)提到loop方法的作用)橄杨。這可能違背大家的開發(fā)經(jīng)驗(yàn):不對(duì)啊秘症,在主線程中使用Handler的時(shí)候我們并不需要調(diào)用Looper的prepare方法。其實(shí)這是因?yàn)槭浇茫骶€程中已經(jīng)為我們調(diào)用過(guò)了prepare:
public static void main(String[] args) {
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());
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
AsyncTask.init();
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
這里的prepareMainLooper方法也就是為主線程創(chuàng)建一個(gè)Looper并關(guān)聯(lián)乡摹,然后調(diào)用Looper.loop開啟了消息循環(huán)。
繼續(xù)看構(gòu)造函數(shù)采转,Looper中的Queue成員變量傳給了Handler聪廉,在下面分析Message入隊(duì)的時(shí)候,會(huì)看到它故慈。
接下來(lái)我們查看發(fā)送Message的方法:
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
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);
}
可以看到板熊,最后都會(huì)轉(zhuǎn)到sendMessageAtTime方法中,跟進(jìn)enqueMessage方法察绷。
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
這里將handler對(duì)象賦給了Message對(duì)象的target成員變量干签,然后將Message加入到了隊(duì)列中,代碼如下:
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;
}
這個(gè)MessageQueue是用鏈表實(shí)現(xiàn)的拆撼,簡(jiǎn)單的說(shuō)容劳,上面的代碼做的事就是:根據(jù)這個(gè)Message的時(shí)間,將它插入到合適的位置闸度,我們知道竭贩,在sendMessage之后,往往handleMessage方法就會(huì)被自動(dòng)調(diào)用莺禁,中間到底發(fā)生了什么留量?
答案就在Looper中,查找發(fā)現(xiàn)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
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();
}
}
相信大家看到這就明白了睁宰,Looper的loop方法執(zhí)行了一個(gè)無(wú)限循環(huán)肪获,每次循環(huán)都從隊(duì)列中取出一個(gè)Message,然后調(diào)用message.target.dispatchMessage方法柒傻,之前分析過(guò)孝赫,這個(gè)target應(yīng)該是一個(gè)handler對(duì)象,接下來(lái)去看看handler的這個(gè)方法:
/**
* 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了红符,到這里流程就大概走完了青柄,畫個(gè)圖總結(jié)一下:
有問題歡迎評(píng)論探討~