handler对于开发者绝对不陌生,我也一样,之前读过相关的源码,但是发现记得貌似不是很牢靠,所以写篇博客记录下来,梳理巩固一下,其实我觉得的阅读的终极目的就是理解作者的用心,领悟出自己的东西(或是心得)读码也是同样。
关于这四者的关系(Handler,Message,MessageQueue,Loop)我觉得就好像物流一样,handler扮演的角色就是快递员,把买的商品(Msg)从商家拿到菜鸟驿站(MessageQueue),然后呢,菜鸟驿站的工作人员(Looper)在告诉那个快递员把商品送到指定目的地。这样就ok了。
ok,下面开始根据代码来分析:
一,Handler
一般使用Handler就是直接New一个,然后在dispatchMessage方法内写对应的操作,比如这样
private Handler handler = new Handler() {
public void dispatchMessage(@SuppressWarnings("NullableProblems") android.os.Message msg) {
}
};
ok,跟进Handler看构造
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;
}
可以看到主要操作是获取Looper,MessageQueue的实例,这里可以看到这么一行代码
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
在Handler内获取Looper实例,并且下面还做了一个判断非空的操作,字面意思就是,不能再未执行Looper.prepare()的线程内创建Looper。ok,跟进到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));
}
可以看到,这里有一个sThreadLocal,这个类的作用概括来说就是线程用来存储数据的,并且只能在之前指定的线程内才能拿到存的数据。看到这里就应该明白了为什么一个一个线程只能有一个Looper了,往下走,如果get不到东西,就new一个Looper对象,set到sThreadLocal里面,这样再进到Looper.myLooper方法里就懂了,代码就不贴了,进去看一下就懂了。
ok,但是这是会发现,有时handler就直接new了啊,也没做Looper.prepare();这个操作啊,其实是因为这是直接在主线程(Ui线程)创建的Handler,可以直接进入到ActivityThread这个类当中,就会发现如下代码
Looper.prepareMainLooper();
原来是在主线程当中执行了了这个东西,so,在自己创建的子线程当中还是要prepare();Looper的构建就先到这里了。
通过mQueue = mLooper.mQueue;可以知道,MssageQueue是在Looper当中构建的,并且由他维护,那么就看看这个Looper都干了什么吧
二.Looper
看源码可知主要的方法就是两个,一个是prepare,另一个就是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
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
msg.target.dispatchMessage(msg);
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();
}
}
可以看到现实做了个null判断,然后
final MessageQueue queue = me.mQueue;
这行代码获取Looper对应的维护的线程内的Messagequeue。当然这个MessageQueue肯定就是用来存放Msg的了,这个后面在看,之后的Binder.clearCallingIdentity();我也不是很懂,跟进去发现是一个调用C层的方法,获取了个long值,并在下面进行了个判断,根据注释猜测是保护线程安全的(Binder通信的知识2018/3/12)?如果有哪位知道麻烦告诉我一声,小弟非常感激,在之后就是一个死循环,不断的从queue中取到Message
msg.target.dispatchMessage(msg);
在loop方法内分发消息的就是这句了,target就是handler,obtain时会传入,sendEmptyMessage时会在Handler的enqueueMessage方法内指定为该handler.
下一步就看
msg.target.dispatchMessage(msg);
target(handler)的dispatchMessage方法了,看代码如下
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
可知这个方法的作用就是回调数据。那么到此Looper的主要代码就分析完了