说到Android的Handler,我们用到最多的就是用来在子线程中通知主线程更新UI,但是,我们有思考过它们内部是怎么实现的吗,现在就带大家一步一步来揭开它的神秘面纱吧。
要说Handler,当然得先从它的构造函数说起:
public Handler() {
this(null, false);
}
public Handler(Callback callback) {
this(callback, false);
}
public Handler(Looper looper) {
this(looper, null, false);
}
public Handler(Looper looper, Callback callback) {
this(looper, callback, false);
}
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
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、looper.mQueue、callback、async,针对这几个参数,这里稍微做下介绍:
looper::一个循环工具,用来循环取出消息队列中的消息;
looper.mQueue: looper当中的消息队列,用来存放消息的;
callback:handler中用来对handleMessage方法进行拦截的回调(后面的分析中大家可以看到);
async:是否异步,默认都是同步;
看到这里,我们先停下对上面几个类的进一步分析,先按照正常的使用流程来说,一般我们定义好一个handler后,在使用的时候一般是调用相关sendMeassge方法:
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public final boolean sendEmptyMessage(int what)
{
return sendEmptyMessageDelayed(what, 0);
}
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageDelayed(msg, delayMillis);
}
public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageAtTime(msg, uptimeMillis);
}
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);
}
我们看到,最终都是调用了enqueueMessage方法,那就进去一探究竟:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
好了, 关键点来了,这里有一个关键的赋值,后面要用到,那就是把handler本身赋值给了message.target,然后把消息存入了消息队列MessageQueue,handler发送消息也就到此结束了。
那么handler的handleMessage方法究竟是怎么触发的呢,说到这里,我们就来扒一扒上面提到的几个类:
Looper:
打开API文档,我们看到有这样一段注释:
* <pre>
* class LooperThread extends Thread {
* public Handler mHandler;
*
* public void run() {
* Looper.prepare();
*
* mHandler = new Handler() {
* public void handleMessage(Message msg) {
* // process incoming messages here
* }
* };
*
* Looper.loop();
* }
* }</pre>
我们看到,在new Handler之前,要先调用Looper.prepare(),那么这个方法里面做了什么呢?
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));
}
可以看到,这里最后调用到了sThreadLocal.set()方法,把创建好的looper对象存入sThreadLocal中,sThreadLocal可以看作一个全局静态容器(具体代码分析就不在这里做继续展开了),用来存放looper的,并且一个线程当中只能存在一个looper,也就是说,一个线程当中只能调用一次prepare方法。
再来看看Looper的构造函数中做了什么事情呢:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
我们看到 这里最主要做了两件事情,new出来消息队列,由单个线程中looper的唯一,可以知道messageQueue也是唯一的,该构造函数做的第二件事情就是把当前线程的ID赋值到一个变量,后续用来做是否在当前线程的判断。
好了 Looper.prepare()方法我们我们分析过了,new Handler我们也分析过来,接下来就是Looper.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();
}
}
方法比较长,我们慢慢分析:
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
这里获取当前线程的looper,如果为null,则会抛出异常,所以在一开始的时候,我们要调用Looper.prepare()方法创建looper对象。
// 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();
确定当前的线程是否是创建looper的线程,并继续跟踪
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
关键代码到了,我们看到,这是一个死循环,目的就是循环从消息队列当中取出消息,如果消息为null,则跳出循环了。
try {
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
省去了部代码的分析,到了这里就是我们整篇文章的关键了,看看,msg.target这个是什么,如果不记得了,看看本文之前提到的,msg.target就是消息message在创建的时候赋值的handler对象,这里就直接调用了handler的dispachMessage()方法分发消息了。
那么我们来分析下handler的dispachMessage()方法中做了什么:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
这个方法很简单,大家自行分析哈。(前面提到的handler中callback对handleMesage的拦截也是在这里实现的)。
好了,到了这里,整个Handler之谜,我们已经理清了基本流程了,下面就做一下基本的总结:
1、Looper.prepare():创建当前线程的looper,且一个线程只能调用一次
2、new Handler():创建handler,用来发送和接受消息,在构造函数中,关联了looper和looper中的消息队列管理器MessageQueue。
3、Looper.loop():开始死循环,循环从消息管理队列MessageQueue当中取出消息,取出消息后调用message.target(也就是handler)的dispachMessage()方法分发消息。
4、总体来说就是:在线程A当中创建一个消息队列,并开启一个死循环,不停读取消息队列中的消息,然后在B线程中调用A线程创建的handler往A线程的消息队列中存入消息,这时A的死循环Looper对象就能取到这个消息了。
本文写的比较粗糙,如有错误欢迎留言指出