在Android中,Handler非常重要,在主线程的main方法中就使用了Handler,并且由于UI只能在UI线程上更新,Handler的使用更广泛了,当然,Handler的使用不止是更新界面,例如:在子线程做一些耗时操作,完成后可能需要更新UI,不更新UI做一些其他事情也是可以的。
一般在多线程里使用Handler都是通过下面的方式。
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case MESSAGE:
Log.d(TAG, "handleMessage: ");
break;
}
}
};
mHandler.sendEmptyMessage(MESSAGE);
Looper.loop();
}
}).start();
但是由于我们在main线程经常用Handler,好多人可能会问,怎么还有Looper?这是什么鬼?
那么接下来,我就从源码的角度来解释这个问题,顺便梳理一下源码。
源码的理解
Handler mHandler = new Handler();这一步,我们进去看一看:
Handler类:
public Handler() {
this(null, false);
}
public Handler(Callback callback, boolean async) {
......
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;
}
上面构造方法中mLooper = Looper.myLooper();,接下来会有个判断,那么什么时候mLooper == null?
进入Looper.myLooper();的源码一探究竟,
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
到这里我们差不多是明白了些,原来Looper.myLooper()是得到该线程的Looper,而looper是存放在了ThreadLocal里面,因此是从ThreadLocal里面取出了Looper。但是ThreadLocal里面会有looper吗?我们把第一段代码里面的Looper.prepare();注释掉运行一下试试看:
抛出的异常正是if语句块里的代码,而加上Looper.prepare();这行代码后就没有该异常出现了,那么Looper.prepare()做了什么呢?进去看一下:
Looper类中:
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));
}
原来是向ThreadLocal中设置looper,设置之后new Handler()的时候也不会抛出异常了。
那么接下来的问题又来了,Handler是怎么发送消息的呢,又是怎么样才能取到消息处理掉?还是看源码!
Handler发送消息
Handler类中:
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 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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
上面的sendEmptyMessage、sendEmptyMessageDelayed和sendMessageDelayed都是我们经常用到的方法,最终都会走sendMessageAtTime方法。我们看一下这个方法,里面有个MessageQueue,这又是什么呢,这就是所谓的消息队列,顾名思义,用来存放消息的。消息队列的对象什么时候创建的呢?
在Looper.prepare()中,会走sThreadLocal.set(new Looper(quitAllowed))这行代码,我们看一看new Looper(quitAllowed)做了什么?
Looper类:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
原来消息队列的对象是再Looper的构造方法中创建的,瞬间就明白了Looper.prepare()的重要性,不光是创建了Looper对象并放入了ThreadLocal,还创建了MessageQueue对象。在enqueueMessage中,有msg.target = this,这句代码是把当前的Handler对象赋值给msg.target。接着看queue.enqueueMessage。这个是MessageQueue类中的方法:
boolean enqueueMessage(Message msg, long when) {
synchronized (this) {
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w(TAG, e.getMessage(), e);
msg.recycle();
return false;
}
msg.markInUse();
msg.when = when;
Message p = mMessages;//当前待处理的消息
boolean needWake;
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// Inserted within the middle of the queue. Usually we don't have to wake
// up the event queue unless there is a barrier at the head of the queue
// and the message is the earliest asynchronous message in the queue.
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {//将所有消息按照时间来排序
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
上述代码是把消息插入到消息队列当中,从上面代码可以知道,消息队列其实就是一个单链表。这个时候消息传到了消息队列,但是我们知道我们是再handler的handlerMessage中把消息处理掉了(不止这一种,还有通过post发送消息,在run方法中处理消息)。
在第一段代码中,还有一行代码没有讲到,我把源代码贴出来看一下。
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 (;;) {
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();
}
}
通过代码,我们看出首先得到当前线程的Looper对象,然后取出消息队列(因为消息队列是在looper中创建的),接着进入了for语句块,这是个无限循环,Message msg = queue.next()就很关键了,我们看一下
Message next() {
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
// Next message is not ready. Set a timeout to wake up when it is ready.
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// Got a message.
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}
// If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
}
}
}
从上面代码中可以看出来,这是从单链表中移除一个节点的操作,而节点就是消息,而且是在一个死循环里面,如果消息队列中没有消息,就会在这里发生阻塞。但是一旦有消息到来,就会把消息从消息队列中移除。
那我们再回到Looper.looper()中。当取到的消息为空的时候,就会退出for循环。如果取到了消息,那么接下来会走msg.target.dispatchMessage(msg),而根据前面的讲述msg.target就是当前的Handler对象,那么dispatchMessage(msg)便是Handler中的方法,接着看源码:
Handler类中:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
上面方法是对消息进行分发,首先判断msg.callback是否为空,msg.callback是Runnable对象,这又是何方神圣,我们有时候还喜欢用post来发送消息,例如下:
同样是在一个子线程中:
Looper.prepare();
Handler mHandler = new Handler();
mHandler.post(new Runnable() {
@Override
public void run() {
}
});
Looper.loop();
接着看post的源码:
public final boolean post(Runnable r){
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
哦!原来msg.callback就是post的Runnable对象,如果不为空,说明采用了post的方式发送消息,那么接下来应该执行run方法了,接着看handleCallback方法:
private static void handleCallback(Message message) {
message.callback.run();
}
果不其然!!在这里执行了run方法。
接着检查mCallBack是不是为空,,如果不为空的话,会执行mCallback.handleMessage(msg)。对应的例子代码:
Looper.prepare();
Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
return false;
}
});
Looper.loop();
因为Callback是个接口,handleMessage是接口中的方法,该方法在上面的例子中实现,那么会执行实现的方法。
如果msg.callback和mCallBack都为空的话,那么就会执行handleMessage(msg),这是Handler中的方法:
Handler类:
public void handleMessage(Message msg) {
}
空的!!!我们在new Handler()的时候覆盖了该方法,那么就会走我们覆盖后的方法。
结尾
终于写完了,有的人可以很诧异,为什么在UI线程中不需要写Looper.prepare()和Looper.loop()?
我凑!UI线程那么重要,当然已经被创建好了,在Looper.prepareMainLooper()方法中一看便知。Looper.loop()在ui线程也已经准备好了,这里就不带着去看了。
又有问题来了,Android中为什么主线程不会因为Looper.loop()里的死循环卡死?
这里有个很好的答案,附上链接如下:
答案链接