Handler原理解析
Handler的基本创建步骤
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
Handler handler = new Handler();
Looper.loop();
}
}).start();
要创建Handler首先需要looper对象,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));
}
可以看到方法中将当前线程的looper存储到了ThreadLocal中,
而ThreadLocal则是一个存储容器,对应不同的线程它都有独立的存储区间。比如现在有线程1,2,ThreadLocal分别在线程1和2中set不同参数,在对应线程中get是可以看到对应的数据是独立区分的,所以使用ThreadLocal来存储looper可以方便handler在对应线程获取对应looper,而不需要在全局自己维护一个map集合做过多的操作
new Thread("Thread#1") {
public void run() {
threadLocal.set(2);
System.out.println(Thread.currentThread().getName() + "--value:" + threadLocal.get());
}; }.start();
new Thread("Thread#2") {
public void run() {
System.out.println(Thread.currentThread().getName() + "--value:"
+ threadLocal.get())
};}.start();
输出结果:
Thread#1--value:2
Thread#2--value:null
再看looper的构造函数中创建持有了messagequeue和当前线程用于之后的消息处理和线程切换
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
在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;
}
通过sThreadLocal获取了对应线程的looper,如果为空就会抛出异常,并且持有了messagequeue用于后续的sendMessage
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
sendMessage其实就是通过的messagequeue的enqueueMessage方法将消息添加到单链表队列中
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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
//target指向handler本身用于后续looper中的消息分发
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
looper.loop方法无限for循环不停地通过messagequeue.next取出消息,如果messageQueue为空则next方法会进入阻塞从而阻塞looper的for循环,当有消息时就会通过msg.target.dispatchMessage(msg)分发消息(msg.target就是发送该消息的handler,而且该handler执行在创建当前looper的线程中所以完成了线程切换)
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循环
for (;;) {
Message msg = queue.next(); // might block
//为空时直接return退出循环
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();
}
}
那么什么时候能退出该无限循环呢?只有当looper的quit被调用,即messageQueue的quit,并且之后不会再接受新的消息
//looper中的quit
public void quit() {
mQueue.quit(false);
}
//messageQueue中的quit,mQuitting =true
//让next方法直接返回null使looper退出无线for循环
//并且清空了所有的消息
void quit(boolean safe) {
if (!mQuitAllowed) {
throw new IllegalStateException("Main thread not allowed to quit.");
}
synchronized (this) {
if (mQuitting) {
return;
}
mQuitting = true;
if (safe) {
removeAllFutureMessagesLocked();
} else {
removeAllMessagesLocked();
}
// We can assume mPtr != 0 because mQuitting was previously false.
nativeWake(mPtr);
}
}
这里的safe标志位,true针对quitSafely方法,false针对quit方法
当我们调用Looper的quit方法时,实际上执行了MessageQueue中的removeAllMessagesLocked方法,该方法的作用是把MessageQueue消息池中所有的消息全部清空,无论是延迟消息(延迟消息是指通过sendMessageDelayed或通过postDelayed等方法发送的需要延迟执行的消息)还是非延迟消息。
当我们调用Looper的quitSafely方法时,实际上执行了MessageQueue中的removeAllFutureMessagesLocked方法,通过名字就可以看出,该方法只会清空MessageQueue消息池中所有的延迟消息,并将消息池中所有的非延迟消息派发出去让Handler去处理,quitSafely相比于quit方法安全之处在于清空消息之前会派发所有的非延迟消息。
最后看一下dispatchMessage
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
- msg.callback为handler.post中的runnable接口,不为空直接执行该接口run方法;
- mCallback为handler内部接口,Callback源码里面的注释已经做了说明:可以用来创建一个Handler的实例但并不需要派生Handler的子类。在日常开发中,创建Handler最常见的方式就是派生一个Handler的子类并重写其handleMessage方法来处理具体的消息,而Callback给我们提供了另外一种使用Handler的方式,当我们不想派生子类时,就可以通过Callback来实现。
- 如果都为空则实行handler的handleMessage方法
总结
looper创建时会根据当前线程存入ThreadLocal中,并且创建MessageQueue,handler创建时会去ThreadLocal寻找当前线程是否有对应的looper对象没有则抛出异常,初始化成功之后,looper.loop不断从messaegQueue中取出message,通过message中的target引用找到对应的handler,调用该dispatchMessage分发消息并处理