Handler机制学习记录
说明:源码分析基于Android 8.0.0,实例代码基于Android studio,源码通过source insight查看
写这个博客的目的主要还是为了学习的更扎实,感觉瞎学没啥效果,不如记录下来。
Handler基础用法
首先来看一下Handler的基础用法
private void testHandler(){
MHandler mHandler = new MHandler();
Message message = mHandler.obtainMessage();
message.what = 1;
mHandler.sendMessage(message);
}
private static class MHandler extends Handler{
private static final int DO_WHAT = 0;
private static final int DO_NOTHING = 1;
@Override
public void handleMessage(Message msg) {
Log.d("test","" + msg.what);
}
}
先写一个MHandler的静态内部类,继承Handler,并重写handlerMessage(Message msg)方法,根据msg的不同进行不同的操作,然后在需要传递消息的地方申请一个该类的实例,并且通过obtainMessage()方法获取Message实例,给message的参数赋值,最后调用handler的sendMessage对象。
当然,以上的是在主线程中使用Handler的步骤,在其他线程如何使用Handler后面再说。
注意:如果要在handleMessage方法中更新UI,可以改变Handler的构造方法,传入当前activity的引用,但是只能申请弱引用,否则Handler会一直持有activity的引用导致activity引用无法被gc回收造成内存泄漏。
Handler基础用法源码分析
首先看看官方对Handler的介绍。
* A Handler allows you to send and process {@link Message} and Runnable
* objects associated with a thread's {@link MessageQueue}. Each Handler
* instance is associated with a single thread and that thread's message
* queue. When you create a new Handler, it is bound to the thread /
* message queue of the thread that is creating it -- from that point on,
* it will deliver messages and runnables to that message queue and execute
* them as they come out of the message queue.
*
* <p>There are two main uses for a Handler: (1) to schedule messages and
* runnables to be executed as some point in the future; and (2) to enqueue
* an action to be performed on a different thread than your own.
大概意思为,Handler可以发送并处理Message和与线程持有的MessageQueue(消息队列)关联的Runnable对象,每个Hanlder实例之和一个线程以及这个线程的消息队列关联(不是一一对应的关系,一个线程可以持有多个Handler对象,但一个Handler对象只从属于一个线程),当Handler实例被创建,这个实例将会被绑定到创建这个实例的线程。Handler发送的Messages和Runnable对象将会被加入进当前线程的消息队列,当它们从队列出来时会被处理。Handler主要有两种用法,其一是调度消息(Messages)和将来某个时间点需要被执行的可执行项,其二是异步实现一个操作。
官方的介绍把Handler的作用说的很清楚,之前给出的简单示例就是调度消息的用法。
下面从重写Handler的handlerMessage方法开始分析。
从名字上看,显然handlerMessage就是处理消息的方法,那么为什么要重写这个方法呢?下面是Handler源码
/**
* Subclasses must implement this to receive messages.
*/
public void handleMessage(Message msg) {
}
可以看到,这个方法是一个空方法,所以加不加super.handleMessage(msg)是无所谓的。注释说明子类必须实现这个方法来接收消息,所以如果要使用Handler处理消息,必须重写该方法,否则传入的消息被传入一个空方法,不会有任何反应。
下面来看看实现消息传递机制的过程。首先是创建了一个Handler实例。下面是构造方法的源码。
/**
* Default constructor associates this handler with the {@link Looper} for the
* current thread.
*
* If this thread does not have a looper, this handler won't be able to receive messages
* so an exception is thrown.
*/
public Handler() {
this(null, false);
}
构造方法调用了两个参数的另一个构造方法,注释的大致意思是,默认的构造方法将当前线程的Looper和该handler对象联系起来,如果该线程没有looper,handler对象将无法接收对象并抛出异常。
下面看看这个两参数的构造方法
/**
* Use the {@link Looper} for the current thread with the specified callback interface
* and set whether the handler should be asynchronous.
*
* Handlers are synchronous by default unless this constructor is used to make
* one that is strictly asynchronous.
*
* Asynchronous messages represent interrupts or events that do not require global ordering
* with respect to synchronous messages. Asynchronous messages are not subject to
* the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
*
* @param callback The callback interface in which to handle messages, or null.
* @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
* each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
*
* @hide
*/
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,并设置handler是否是异步的。Handler默认是同步执行的。
该构造方法先进行了一个内存泄漏的判断,如果发现了内存泄漏,打印出警告,继续执行,如果没发现,也继续执行。
然后将Looper.myLooper()赋予给成员变量mLooper。如果获取的值是null,抛出异常,如果不是null,继续给其它成员变量赋值。
显然,关键在于从Looper.myLooper()获取的这个Looper实例。我们跑到Looper去看看。
先看Looper的官方介绍
* Class used to run a message loop for a thread. Threads by default do
* not have a message loop associated with them; to create one, call
* {@link #prepare} in the thread that is to run the loop, and then
* {@link #loop} to have it process messages until the loop is stopped.
Looper用于为线程执行消息循环,线程一般没有消息循环,需要使用Looper.prepare()和Looper.loop()才能处理消息。
所以如果要在其他线程使用Handler,需要先调用Looper.prepare()和Looper.loop()才可以,注意,一个线程只能有一个Looper实例。例子后面再说。而主线程,在初始化时已经创建了Looper实例,并且执行了以上的初始化,所以在主线程可以直接使用Handler。
/**
* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
*/
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
myLooper方法返回当前线程有用的Looper实例,如果当前线程没有,则返回null。
下面来说说这个sThreadLocal,Looper中是这样定义的。
// sThreadLocal.get() will return null unless you've called prepare().
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
除非你调用了prepare(),否则调用sThreadLocal.get()将会返回null。
ThreadLocal一般称为线程本地变量,它是一种特殊的线程绑定机制,将变量与线程绑定在一起,为每一个线程维护一个独立的变量副本。通过ThreadLocal可以将对象的可见范围限制在同一个线程内。
出处:http://www.cnblogs.com/chengxiao/p/6152824.html
正因为是“线程级”的变量,所以如果当前线程没有Looper变量,是无法使用Handler的。
prepare()方法就比较简单了,就是新建了一个Looper变量。
/** Initialize the current thread as a looper.
* This gives you a chance to create handlers that then reference
* this looper, before actually starting the loop. Be sure to call
* {@link #loop()} after calling this method, and end it by calling
* {@link #quit()}.
*/
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的构造方法也比较简单,就是创建了一个新的MessageQueue对象,以及将当前线程赋值给Looper的mThread变量。
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
现在暂时回到我们的初步调用的流程,讲完了Handler的初始化,然后就是创建新的Message了。上代码。
/**
* Returns a new {@link android.os.Message Message} from the global message pool. More efficient than
* creating and allocating new instances. The retrieved message has its handler set to this instance (Message.target == this).
* If you don't want that facility, just call Message.obtain() instead.
*/
public final Message obtainMessage()
{
return Message.obtain(this);
}
该方法从全局的message pool中返回一个新的message变量,这种方式比创建和分配新的实例效率更高。取到的消息将会和该Handler实例绑定。
如果不需要该功能,直接调用Message.obtain()也可以。
好,去Message看看。老规矩,上介绍
* Defines a message containing a description and arbitrary data object that can be
* sent to a {@link Handler}. This object contains two extra int fields and an
* extra object field that allow you to not do allocations in many cases.
*
* <p class="note">While the constructor of Message is public, the best way to get
* one of these is to call {@link #obtain Message.obtain()} or one of the
* {@link Handler#obtainMessage Handler.obtainMessage()} methods, which will pull
* them from a pool of recycled objects.</p>
定义一条能被发送给Handler的包含描述和任意数据对象的消息。这个对象包含两个int类型的变量和一个额外的object类型的变量,保证你在大多数情况下不需要分配新的内存。
虽然Message的构造方法是公共的,但是最好的获取对象的方法是使用Message.obtain()或Handler.obtainMessage()从回收的对象池中获取对象。
然后看看obtain方法
/**
* Return a new Message instance from the global pool. Allows us to
* avoid allocating new objects in many cases.
*/
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
该方法是一个同步方法,因为message的获取是可能多线程出现的,所以给关键的代码块加了锁。
Message有一个成员变量Next,而这个sPool变量也是Message类型的,加锁代码块内的逻辑是这样的:
先将sPool赋给m,然后sPool赋值为m.next,再将m.next置为null。
显然,这个所谓的消息池,是一个链式结构(单向链表)。这部分的逻辑意思是把链表的首位赋给新申请的Message,避免了new操作,然后sPoolSize减一,清除标记,返回这个获取的Message实例。
虽然还有一些问题没解释清楚,比如说这个消息池是怎么来的,但获取Message的分析到这里就先告一段落,其他问题留后再说,现在重新回到Handler,Handler实例创建好了,消息创建好了,剩下的就是发送消息了。
/**
* Pushes a message onto the end of the message queue after all pending messages
* before the current time. It will be received in {@link #handleMessage},
* in the thread attached to this handler.
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*/
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
方法注释,将在当前时间之前已经挂起的所有消息之后,将该消息加入消息队列的末尾(有点绕,其实就是等之前要加入消息队列的消息加入完毕后,该消息才能加入消息队列的末尾)。这个消息将会被handleMessage方法,也就是我们之前重写的方法,接收到。
返回值表示这个消息是否被成功加入队列,通常失败的原因是因为处理消息的looper正在退出。
这个方法内部又调用了sendMessageDelayed(msg,0)。显然是0延迟立刻发送消息的意思。
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
如果延迟为赋值,重新定义为0,然后再调用sendMessageAtTime。
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);
}
这个mQueue就是之前在构造方法中从Looper实例获取的MessageQueue成员变量。检查是否还存在MessageQueue,如果存在,将消息入队。
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
将message.target赋值为当前handler实例,message绑定到当前handler,如果该消息是异步的,将message也定义为异步的,如果不是,MessageQueue调用方法使message入队。
将异步代码放到一边,我们去MessageQueue看看。
* Low-level class holding the list of messages to be dispatched by a
* {@link Looper}. Messages are not added directly to a MessageQueue,
* but rather through {@link Handler} objects associated with the Looper.
*
* <p>You can retrieve the MessageQueue for the current thread with
* {@link Looper#myQueue() Looper.myQueue()}.
*/
持有Looper需要分发的消息列表的底层类。消息不会被直接加入该类,而是通过和Looper绑定的Handler实例加入。你可以从当前线程的Looper实例通过myQueue()方法获取MessageQueue。
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(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;
}
首先当然是进行判断,如果target为null,抛出异常。然后判断是否正在使用(FLAG_IN_USE值为1,之前在Message.obtain()方法中,需要将msg的flag置0,就是因为如果正在使用,值为1,而这个isInUse方法就是判断msg.flag是否为FLAG_IN_USE),如果正在使用抛出异常。如果该线程已经结束,抛出异常,并调用msg的回收方法(这里就是之前说的回收池哪来的,调用msg.recycle()方法后,msg进入回收池,回收池大小加一)。
基本的判断完成后,将msg标记为正在使用(markInUse),将消息处理的时间赋给msg,然后开始入队。
mMessages是一个Message变量,和Message中的sPool是同样的道理,以链表的形式,将mMessages的next置为新加入的msg就可以了,如果队列出现了阻塞,置为需要唤醒。最后如果需要唤醒,调用nativeWake方法。
需要注意的是,else代码块中,是延迟处理消息的操作,它通过一个中止条件为线程结束(直观表现为mMessages == null)或者处理时间小于当前p这个节点(when<p.when))的for循环,使prev记录的是前面一个节点,p记录的是用于比较的节点,直到前面的节点执行时间比msg小,后面的节点执行时间比msg大,跳出循环,将msg的next置为p,prev.next置为msg,就将msg插入了这个队列中。
本来想画个图的,但是感觉画图会让问题更复杂(也可能实锤了我不会画图),我就把逻辑简化一下。
总结一下,立刻处理的msg直接插入这个链表的头部执行,延迟处理的msg则根据时间顺序插入链表,最后得到的链表是一个按时间排序的链表,消息的处理从链表头部开始。
看到这里,我们还是没有找到哪里调用了Handler.handleMessage方法,回想一下,我们已经将Handler基本使用步骤里的方法全部走了一遍,并没有找到哪里调用了这个方法,也没有找到队列出队处理消息的方法。
前面说过,在Handler实例创建的线程中必须调用Looper.prepare()和Looper.loop()。虽然我们在主线程调用Handler完全没有提到Looper这个类,但是很显然,loop()方法是处理消息的关键。现在我们重新回到Looper
/**
* 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 (;;) {
//等下看
}
}
一看注释,成了,在这个线程中运行消息队列。
前面的赋值操作已经说过很多次,这些变量都说过,就不赘述了,我们直接到核心步骤。
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
msg.recycleUnchecked();
}
去掉关于线程安全和打印各种信息等等代码,核心就只有两句话。
Message msg = queue.next(); // might block
msg.target.dispatchMessage(msg);
在MessageQueue.next()方法中执行的是一个出队操作,对阻塞和各种异常进行了处理,最终的结果就是队列出队。
msg.target之前说过,是和它绑定的handler,现在去看看Handler的dispatchMessage(msg)方法
/**
* 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就知道都结束了。
主要还是分析了一下源码的逻辑和实现过程。