現在網上關於Handler的資料,已經是數不勝數,總歸還是要親自走一遭才能深刻的理解。
在之前,我們先來了解下Handler、Looper、MessageQueue、Message之間的關係
它們的關係就像全家桶Rxjava+RxAndroid+ReTrofit2+okHttp3一樣親密→_→
Handler:用來發送消息,處理消息
Looper:一個消息輪詢器,內部有一個loop()方法,不停的去輪詢MessageQueue
MessageQueue:存放消息的消息池
Message:我們發送、處理的消息對象
問題來了: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 slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
final long end;
try {
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (slowDispatchThresholdMs > 0) {
final long time = end - start;
if (time > slowDispatchThresholdMs) {
Slog.w(TAG, "Dispatch took " + time + "ms on "
+ Thread.currentThread().getName() + ", h=" +
msg.target + " cb=" + msg.callback + " msg=" + msg.what);
}
}
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();
}
}`
這裏我們可以看到在loop()方法裏面,有一個for(;;)死循環,不停的去遍歷消息池裏面的消息,有人肯定會說,如果是個死循環,這裏不是很耗內存嗎,我最初也是這麼想的,後來在MessageQueue源碼發現這樣一句註釋:
Indicates whether next() is blocked waiting in pollOnce() with a non-zero timeout(指示是否阻塞next()在pollOnce()中等待,超時時間不爲零)
原來是有阻塞的,既然如此,那我們得看看next()方法裏面到底做了什麼,繼續挖掘,發現:
在next()裏面同樣有一個死循環,消息阻塞就是發生在nativePollOnce()方法,在native層使用了epoll機制來等待消息的,這下就通了
Message被添加到隊列中時,會根據when的執行時間排序,next()方法會一直等待到下一個消息的執行時間到來然後取出並返回
看明白這裏,我們繼續向下看,看看它們到底怎麼聯繫起來、怎麼工作的
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;
}
在Handler的構造方法裏面通過looper得到了一個Looper、一個MessageQueue,也就是說,Handler裏面的兩個成員都是通過Looper來賦值的
mLooper = Looper.myLooper();
mQueue = mLooper.mQueue;
所以,這裏就有點聯繫了,在初始化Handler的同時,一個looper、queue同樣也被初始化,就是說,一個Handler對應了一個Looper、一個MessageQueue
不過這裏有點疑問mQueue = mLooper.mQueue是通過mLooper賦值的,就是說Handler和Looper持有的是同一個MessageQueue,我們可以看看Looper具體怎麼實例化的
public static Looper myLooper() {
return sThreadLocal.get();
}
這裏竟然直接是從ThreadLocal裏面去獲取,從始至終我們有沒有初始化、或者set過什麼,這裏怎麼能拿到東西呢?
我們直接查找看賦值的地方
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));
}
這裏我們看到了,最後new 了一個Looper對象set到了ThreadLocal裏面,那麼就是說,肯定有地方調用了prepare()方法,初始化了ThreadLocal對象並賦值了,具體在哪兒調用的呢?
經過多方查找資料我們在應用啓動入口ActivityThread找到初始化的地方
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
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());
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("<pre-initialized>");
//準備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"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
終於逮着了,也就是說在我們應用啓動初期,App就自動創建了Looper對象,這個在我之前的文章Application詳解裏面的介紹對應上了:app一旦啓動,就會創建一個Looper對象
就是說,我們每次new Hander的時候,其實獲取到得都是應用啓動時候創建的Looper對象,而構造方法裏面賦值的mLooper、mQueue則是在應用啓動的時候就已經初始化好了
接下來我們看看消息收發sendMessage
我們在調用handler.sendMessage的時候有很多方法,但是根據源碼追查,最終他們都會統一到一個方法處理
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);
}
查看enqueueMessage方法
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
這裏msg直接引用的this,就只是整個流程用的都是同一個Handler,handler.sendMessage,同時也是handler自己來處理這個消息
我們回到消息輪詢那裏,發現只要消息不爲空,就會執行
msg.target.dispatchMessage(msg);
在看看這個方法
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
這裏會有一個回調,回調不爲空,就調用handleCallback,如果爲空就調用了handleMessage,而handleMessage方法是一個空的方法
public void handleMessage(Message msg) {
}
所以,只要我們設置了回到callBack,就能夠接受回調,並處理Message
public class MyHandler extends Handler {
private WeakReference<BaseActivity> mActivity;
protected MyHandler(BaseActivity activity) {
mActivity = new WeakReference<>(activity);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (null != mActivity) {
switch (msg.what) {
case 1:
if (progress + 1 > 100) {
progress = 100;
commonPopup.setProgress(progress);
progress = 0;
} else {
progress += 1;
commonPopup.setProgress(progress);
if (null != mHandler) {
mHandler.sendEmptyMessageDelayed(1, 15);
}
}
break;
}
}
}
}
通過消息的分發dispatchMessage,我們能夠看出來,處理消息,優先還是考慮msg的回調,其次是handler的mCallBack,最後是我們自定義的handleMessage
到這裏Handler、Looper、MessageQueue、Message整個流程,就介紹完了
Handler作爲android UI更新線程,是必不可少的,耗時操作子線程完成,然後通過Handler更新UI,所以有時間還是可以研究下Handler源碼的