现在网上关于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源码的