Handler一直是面试很热的话题,最近又看了好多文章,下面结合源码来总结一下。
Handler 是Android 消息机制的上层接口,Handler的运行需要底层的MessageQueue和Looper的支撑,他们是Handler的好基友。Handler的运行机制也就是Android的消息机制。
我们都知道Handler是用来更新UI的,其实更新UI只是开发者最常用的场景。概括来讲:有时候需要在子线中进行耗时较长的I/O操纵,而I/O操作完成后需要在UI上做一些改变,这个时候可以通过Handler将更新UI的操作切换到主线程中去执行。这就是Handler的意义。
那么问题来了,主线程中可以使用Handler嘛?
查看源码发现 在ActivityThread中是默认创建了主线程的Handler。
回想一下,在第一次学习java时,我们都知道java需要Main方法才可以执行。 其实Main方法就在ActivityThread类中,
它是Android程序的启动入口,也就是常说道的UI主线程。
static Handler sMainThreadHandler; // set once in main()
public static void main(String[] args) {
........省略部分代码.......
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
AsyncTask.init();
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
可以发现
sMainThreadHandler是主线程的Handler。
sMainThreadHandler = thread.getHandler();
继续查看getHandler()方法定义。
final H mH = new H(); final Handler getHandler() { return mH; }
而H是ActivityThread的一个内部类,是Handler的子类。
源码是这样定义的:
private class H extends Handler { 。。。。省略内部代码。。。。。 }
所以主线程有自己的Handler,而且创建的时候通过调用 Looper.prepareMainLooper()初始化了Looper,这就是主线程中默认可以使用Handler的原因。
初步认识完了Handler,下面再介绍一遍他的小伙伴们。
MessageQueue的中文翻译是消息队列,顾名思义他的内部存储了一组消息。以队列的形式对外提供插入和删除的工作。虽然叫消息对垒,但其实他的内部结构并不是真正的队列,而是采用单链表的数据结构来存储消息列表。
Looper的中文翻译是循环,这里可以理解问消息循环。由于MassageQueue只是一个消息的存储单元,他不能处理消息,而Looper正好填补了这个功能。Looper会以无限循环的形式在MessageQueue中查找是否有新消息。
ThreadLocal是Looper中的一个特殊概念。它并不是线程,它的作用是可以在每个线程中存储数据。我们知道Handler创建时会采用当前线程的Looper来构造消息循环系统。那么Handler内部如何获取当前线程的Looper呢?这就是使用了ThreadLocal了,ThreadLocal可以在不同的线程中互不干扰的存储并获取数据。通过ThreadLocal可以轻松获取每个线程的Looper。
当然需要注意,线程是默认没有Looper的,如果需要使用Handler就必须为线程创建Looper,我们上面提到的主线程使用 Looper.prepareMainLooper()也创建了自己Looper。在非UI线程中我们使用 Looper.prepareLooper()来创建当前线程的Looper。
我们顺便分析一下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));
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
通过上面的源码我们可以清晰的发现,Looper.prepareLooper()方法是创建了一个新的Looper,而且是依附当前对应的线程上。
同样Looper.prepareMainLooper()是跟主线相对的Looper,也是创建了一个Looper实例。
在Context类中可以通过getMainLooper方法得到主线程的Looper。
public abstract Looper getMainLooper();
那么问题又来了,我在子线程中使用使用Looper.prepareLooper()创建Looper后能更新主线程的UI嘛?
比如:
public void run(){
Looper.prepareLooper();
Toast.makeText(MainActivity.this,"提示信息",TOAST.LENGTH_SHORT).show();
Message msg=new Message();
loginHandler=new LoginHandler();
loginHandler.sendMessage(msg);
Looper.loop();
}
答案是不可以!会提示:
Only the original thread that created a view hierarchy can touch its views.
原因:Looper.prepareLooper()方法会以当前线程为依附创建其Looper,如果换成另一种方式创建Handler
new Handler(Looper.getMainLooper()) ;
这种方式是依附主线程上,是可以正常更新UI的。
接下来再来解释一下MessageQueue。为什么说它是单链表的数据结构?
MessageQueue主要包含两个操作:插入和读取。读取操作本身会伴随着删除操作,
插入和读取操作分别对应的方法为:(Message msg, long when)和next();
插入消息操作:
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
synchronized (this) {
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w("MessageQueue", 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;
}
从enqueueMessage的实现来看,他的主要操作其实就是单链表的插入操作,就不做过多解释了。
查询消息方法:
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
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 (false) Log.v("MessageQueue", "Returning message: " + msg);
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;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
// Run the idle handlers.
// We only ever reach this code block during the first iteration.
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf("MessageQueue", "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
// Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0;
// While calling an idle handler, a new message could have been delivered
// so go back and look again for a pending message without waiting.
nextPollTimeoutMillis = 0;
}
}
上面代码比较长,但是你只要注意到 for (;;) ,应该已经明白next()方法是一个无限循环的方法。如果消息队列中没有消息那么next()方法就会一直阻塞在这里。当消息到来时,next方法会返回这条消息并且将其从单链表中删除。
现在MessageQueue中有数据了,那么Looper是怎么来操作MessageQueue的呢?
在Android的消息机制中Looper主要扮演的是消息循环的角色,具体来说就是它会不停的从MessageQueue中查找是否有新的消息。在Looper的构造方法中它会创建一个MessageQueue 即消息队列,并且将当前线程的对象保存起来。
代码如下:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
通过Looper.prepareLooper()创建了当前线程的Looper后,通过调用Looper.loop()来开启消息循环。也是Looper最重要的一个方法,只有调用了loop(),消息循环系统才真正开始。
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the 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();
}
}
上面的loop()方法的工作工程也比较好理解,loop方法是一个死循环,唯一跳出循环的方式是MessageQueue的next方法返回了null。
当Looper调用quit方式时
/**
* Quits the looper.
* <p>
* Causes the {@link #loop} method to terminate without processing any
* more messages in the message queue.
* </p><p>
* Any attempt to post messages to the queue after the looper is asked to quit will fail.
* For example, the {@link Handler#sendMessage(Message)} method will return false.
* </p><p class="note">
* Using this method may be unsafe because some messages may not be delivered
* before the looper terminates. Consider using {@link #quitSafely} instead to ensure
* that all pending work is completed in an orderly manner.
* </p>
*
* @see #quitSafely
*/
public void quit() {
mQueue.quit(false);
}
mQueue就是MessageQueue的实例。所以Looper.quit()是让MessageQueue清空数据。
另外还有
public void quitSafely() {
mQueue.quit(true);
}
这里传入的boolean值是用来控制是否将当前状态下消息队列中的方法执行完毕后再清空操作的。quitSafely就是在消息要求执行完当前队列中的所有消息后,再做清空操作。从而Looper退出。
而一般情况下不会调用quit方法。这个时候由于 MessageQueue.next(); // might block 在没有消息时处于阻塞状态,从而Looper.loop()也处于阻塞状态,等待消息的到来。
回过头来,我们再从原点出发,Handler的主要工作过程是怎样的?结合源码我们来看一下。
Handler 的主要工作包含,消息的发送和接收过程。消息的发送,可以通过post的一系列方法以及send的一系列方法来实现,post的一系列方法最终是通过send方法来实现的。
先看发送过程吧。
比如:
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
public final boolean postAtTime(Runnable r, long uptimeMillis)
{
return sendMessageAtTime(getPostMessage(r), uptimeMillis);
}
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
可以看到了post方法里面调用了相关的send方法。
所有的send方法最终会调用enqueueMessage(queue, msg, uptimeMillis)方法。
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);
}
enqueueMessage(queue, msg, uptimeMillis)是在最新创建的消息队列中的索引中中添加消息,但是索引指向的地址mQueue块是统一的,实际上说明一个Handler 对应一对MessageQueue、Looper。MessageQueue和Looper才是真爱,他们才是穿一个裤腿的好基友。而MessageQueue又是跟随Looper而来的。换句话说MessageQueue是通过
mLooper = Looper.myLooper();
mQueue = mLooper.mQueue;
或者mQueue = looper.mQueue;而来的。
所以排位有了,大哥Handler,二哥Looper,三弟MessageQueue。任务就是把消息这个唐僧送到西天去。
可以发现,Handler发送消息的过程仅仅是向消息队列中插入了一条消息。
接下来MessageQueue的next方法就会返回这条消息给Looper,Looper收到消息后就开始处理了,最终消息由Looper交由Handler处理,即Handler的dispatchMessage方法会被调用,这时Handler就进入了处理消息的阶段。
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
这里handleMessage(msg)分两种情况
mCallback不是null,mCallback就是前面传过来的Ruannable方法。那么调用
/**
* Callback interface you can use when instantiating a Handler to avoid
* having to implement your own subclass of Handler.
*
* @param msg A {@link android.os.Message Message} object
* @return True if no further handling is desired
*/
public interface Callback {
public boolean handleMessage(Message msg);
}
如果mCallback为null,则调用
/**
* Subclasses must implement this to receive messages.
*/
public void handleMessage(Message msg) {
}
除此之外还有handleCallback
private static void handleCallback(Message message) {
message.callback.run();
}
Message类中callback是这样定义的:/*package*/ Runnable callback;
怎么这么多Callback,我都凌乱了,请再次详细查看上面黑色斜体加粗字体。分清一个是方法一个是变量。mCallback实际上是一个接口。
/**
* Callback interface you can use when instantiating a Handler to avoid
* having to implement your own subclass of Handler.
*
* @param msg A {@link android.os.Message Message} object
* @return True if no further handling is desired
*/
public interface Callback {
public boolean handleMessage(Message msg);
}
通过Callback可以采用如下方式来创建Handler对象:
Handler handler=new Handler(callback)。
那么callback的意义是什么?
通过Callback可以采用如下方式来创建Handler对象:
Handler handler=new Handler(callback);
源码里面的注释已经做了说明:可以用来创建一个Handler的实例但并不需要派生Handler的子类。在日常开发中,创建Handler最常见的方法是派生一个Handler的子类并重写其handlerMessage方法来处理具体的消息,而Callback给我们提供了另外一种使用Handler的方法,当我们不想派生子类时,就可以通过Callback来实现。
前面我们提到ThreadLocal,日常开发中很少用到,但是在特殊情况下可以通过ThreadLocal轻松实现一些看起来比较复杂的功能。比如Looper、ActivityThread以及AMS(ActivityManagerService),研究ThreadLocal有助于我们更加深入的理解Handler。比如Handler需要获取当前线程的Looper,很显然Looper的作用域就是线程并且不同线程具有不同的Looper,这个时候通过ThreadLocal就可以轻松实现Looper在线程中的存取。概括来说:当某些数据是以线程为作用域并且不同线程需要获取不同数据的副本的时候,就可以考虑使用ThreadLocal。
如果Handler中不使用ThreadLocal,那么系统就必须提供一个全局的哈希表供Handler查找指定线程的Looper,这样一来就必须提供一个类似LooperManager的类,但是系统并没有这样做而是选择了ThreadLocal,这就是ThreadLocal的好处。