一篇文章深入分析Handler源码
Handler概述
Handler是一种通信机制,只不过在Android我们常用来更新UI,接下来我将分别从Message、MessageQueue、Looper、handler以及ThreadLocal的源码去深入理解handler的执行流程。
Message :消息对象
Message消息对象,它是数据的载体,内部有几个属性,可以让我们携带数据;而Message通过内部有一个池机制,可以让我们复用Message对象 ,而这个消息池的最大容量 MAX_POOL_SIZE = 50,消息池是通过链表数据结构来组织起来的。
消息池:想要了解池机制我们需要从Message的 obtain() 和 recycle()两个核心方法入手了池机制,首先我们要先看看Message中的几个重要的成员变量,next;存的是我们当前个消息对象的下一个消息对象的地址,同过next属性构建出一个链表结果的消息池。
/**
* 此处我只是沾出Message的几个常用的重要属性,其他属性我们不常用在这里没贴出来有需要的大家可以去源码看
*/
public int what;
public int arg1;
public int arg2;
public Object obj;//上面四个我们常用携带数据标识
long when; //标识当前消息的触发时间
Handler target;//存储发送消息的hanndler
Message next;//存的是我们当前消息对象的下一个消息对象的地址,通过next属性构建出一个链表结果的消息池
private static Message sPool; //sPool属性:我们当前池的头指针位置 ,即只存出链表的第一个消息地址
private static final Object sPoolSync = new Object();//同步锁防止线程污染
private static int sPoolSize = 0;//消息池大小
private static final int MAX_POOL_SIZE = 50;//消息池最大容量
接下来我们看看obtain()方法的源码:
/**
* Return a new Message instance from the global pool. Allows us to
* avoid allocating new objects in many cases.
* if (sPool为空){
* return; new Message(); //无可复用的消息,消息池为空
*}else {
* return 从消息池中获取; }
*/
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;//取出表头的Message对象返回
sPool = m.next;//讲链表后移,记录新的表头消息
m.next = null;//移除第一个
m.flags = 0; // clear in-use清除标记
sPoolSize--;//链表长度减去1
return m;
}
}
return new Message();
}
接下来我们看看recycle()方法的源码:
先判断当前消息对象是否在使用中,如果在使用中,则该消息对象无法回收 直接return, 否则调用recycleUnchecked()方法回收消息。需要注意的是recycle方法不需要我们手动调用,它的调用实在Looper的loop()方法中自动调用,详细过程将在Looper源码中进行分析
/**
* Return a Message instance to the global pool.
* <p>
* You MUST NOT touch the Message after calling this function because it has
* effectively been freed. It is an error to recycle a message that is currently
* enqueued or that is in the process of being delivered to a Handler.
* </p>
*/
public void recycle() {
if (isInUse()) {
if (gCheckRecycle) {
throw new IllegalStateException("This message cannot be recycled because it "
+ "is still in use.");
}//在使用中的消息对象无法回收 直接return
return;
}
recycleUnchecked();
}
/**
* Recycles a Message that may be in-use.
* Used internally by the MessageQueue and Looper when disposing of queued Messages.
* recycleUnchecked回收未在使用中的消息对象,实现链表加1
*/
void recycleUnchecked() {
// Mark the message as in use while it remains in the recycled object pool.
// Clear out all other details.
flags = FLAG_IN_USE;
what = 0;
arg1 = 0;
arg2 = 0;
obj = null;
replyTo = null;
sendingUid = -1;
when = 0;
target = null;
callback = null;
data = null;//以上操作把要回收的message对象的成员变量回归初始值
//以下是重点:实现链表连接池的加1,将message存入消息池中,
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;//先把当前回收的message的next指向消息池的链表头
sPool = this;//再将自己当做新的表头
sPoolSize++;//长度加1
}
}
}
通过以上分析,我们可以知道Mesage是消息对象handler中消息数据的载体,只是它内置消息池实现消息对象的复用以避免new 对象时造成的内存让费。
MessageQueue:消息队列的源码分析
MessageQueue消息队列用于存储handler发送的Message对象,本质上还是通过Message对象的next属性组织起一个链表双向链表,具有先进先出的特性。接下来我将从它的存储(入队)enqueueMessage()方法和取出(出队)next() 两个方法进行分析,需要注意的是出队和入队操作都是按照Message的when属性进行。
首先我们先分析next()方法源码 :
- 调用时机是在Looper.loop()方法的死循环中获取消息,根据触发时间(Message.when属性)判断。
- 如果触发时间到了,那么就将当前消息取出return给Looper进行处理, 如果触发时间没到,那么就运算出一个时间的差值 ——我们此刻距离消息触发还需要多久(nextPollTimeoutMillis)
- 在下一次循环的时候,会调用netive方法——nativePollOnce(nextPollTimeoutMillis),nativePollOnce方法中有一个wait动作,让线程暂停nextPollTimeoutMillis时间值,等到nextPollTimeoutMillis时间达到以后,循环继续执行
/**
*取出下一个消息的动作
*/
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();
}
//调用本地native的nativePollOnce(ptr, nextPollTimeoutMillis)方法休眠
//nextPollTimeoutMillis=msg.when-当前系统时间
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.
//如果当前系统时间< msg.when计算时间差值,在上面调用
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// Got a message.否则取出当前消息返回给Looper
//消息队列中移除当前消息并更新相关状态,链表的移除即prevMsg 当前的消息直接指向它
//的下一个消息的下一个msg.next
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;//否则取出当前消息返回给Looper
}
} 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(TAG, "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;
}
}
enqueueMessage()方法的源码 调用时机:是在Handler中enqueueMessage()方法调用,至于详细的调用过程我将在Handler的源码中进行分析,这里不再赘述。
/**
*MessageQueue中
*enqueueMessage方法源码
*/
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {//msg.target在message源码中说过他是用来存储发送当前消息的Handler对象
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;
}//上面是对Message使用的异常情况的判断(非核心代码)
msg.markInUse();//更新当前message的使用状态
msg.when = when;//取出入队消息的触发时间
Message p = mMessages;//表头消息
//是否需要唤醒。因为在next中nativePollOnce
//(nextPollTimeoutMillis)中有一个wait动作 ,线程会暂停运行nextPollTimeoutMillis时间值
boolean needWake;
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.队列为空时把当前Message作为新表头
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;//记入上一个Message
for (;;) {//死循环前后比较时间 根据when去确定要插入的位置
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) {
//唤醒线程,调用native方法
nativeWake(mPtr);
}
}
return true;
}
到此MessageQueue的enqueueMessage()和next()入队和出队分析完成。
Looper :消息轮询器
Looper :消息轮询器:
- 作用: 不停的从MessageQueue中获取未处理的消息交给handler去处理
- Looper 通过prepare()方法 获取和实例化Looper对象,本身是一个单例模式只能通过prepare()实例化
- Looper 的loop()方法是通过一个死循环不断的从MessageQueue中读取未处理的消息,其实就是在不停对MessageQueue进行next()动作,不断的拿到我们需要处理的下一个消息进行处理
- 每一个Looper都自带一个自己的MessageQueue,在自己的构造器中就已经进行了实例化
- next()方法取出消息后将消息交给当前消息的msg.target. dispatchMessage ()方法处理,在上面Message的源码中分析过msg.target存储的是发送该消息的handler对象,即调用handler. dispatchMessage ()方法处理消息
- 在next方法的最后调用msg.recycleUnchecked()方法处理回收该消息对象
以上便是Looer的大致流程,接下来分析prepare()和loop()方法的源码
prepare()方法源码分析
/** Initialize the current thread as a looper. prepare方法源码
* 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);
}
/**
*借助ThreadLoacl来帮我们进行Looper对象的存和取,实现线程之间数据的隔离存储,在handler中通过ThreadLocal.get();取出looper对象,详细内容将会在Handler源码中进行分析
*/
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {//线程有且只有一个Looper对象
throw new RuntimeException("Only one Looper may be created per thread");
}
//实例化Looper对象并存储到 sThreadLocal
sThreadLocal.set(new Looper(quitAllowed));
}
loop()方法源码分析:
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
* 去除部分代码看主流程
* final Looper me = myLooper();//通过 myLooper()获取Looper对象
* final MessageQueue queue = me.mQueue;//通过Looper获取消息队列
* for (;;) {//开启死循环
* Message msg = queue.next(); // Messagequeue.next()取出消息
* try {
* msg.target.dispatchMessage(msg);//交给Handler处理
* }
* msg.recycleUnchecked();//回收消息对象
*/
public static void loop() {
final Looper me = myLooper();//通过 myLooper()获取Looper对象
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;//通过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();
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);//);//交给Handler处理
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();//;//回收消息对象
}
}
myLooper()方法源码:
/**
* 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();//从sThreadLocal中获取Looper对象
}
到此Looper的工作流程完毕,至于使用ThreadLocal去存储获取Looper对象的原因有:
- 帮我们实现一个线程有且只有一个Looper对象
- 数据隔离:可以让我们在当前线程的任意地方获取到Looper对象,并保证处于同一个线程中的类,取到的是同一个Looper对象,进而操作同一个MessageQueue。只有当我们能够保证发送消息和接收消息所操作的MessageQueue是同一个消息队列的时候,程序才能运转正常。
Handler:消息的发送者 和 消息的最终处理者
Handler的发送和处理分别是通过Handler的enqueueMessage()和dispatchMessage()两个核心方法进行的。结下来将从“构造起”和以上两个方法的源码入手
Handler的构造方法初始化数据:
- 通过 Looper.myLooper()实例化了当前线程的Looper对象 mLooper
- 并且通过looper对象获取MessageQueue mQueue
- 从构造器中可以看出初始化Handler必须先初始化Looper对象,而在我们平时使用过程中主线程并没有先调用 Looper.myLooper()实例化Looper对象的原因是:在应用程序启动时ActivityThread主线程的main()方法中实例化了主线程中的Looper对象,具体源码稍后分析。
构造器有重载但是最终都会调用如下方法:
/**
* @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();//获取当前线程的Looper对象
if (mLooper == null) {
throw new RuntimeException(
//从此处可以看出初始化Handler必须先初始化Looper对象
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;//通过Looper对象获取Looper中的消息队列MessageQueue
mCallback = callback;
mAsynchronous = async;
}
消息的发送: 最终是通过调用MessageQueue调用消息队列的enqueueMessage()方法进行存储消息,即入队操作。我们无论是通过调用handler的sendMessage(Message msg)、sendEmptyMessage(int what)、sendMessageDelayed(msg, delayMillis)等方法还是调用post(Runnable r)、postDelayed( )等post相关方法最终都会调用sendMessageAtTime()方法,即handler发送消息无论通过send相关方法还是post相关方法,最终都是调用sendMessageAtTime()方法发送消息。
至于如何调用到endMessageAtTime方法,非常简单,就是通过方法重载。该过程源码在这里不再赘述,我们直接看sendMessageAtTime()方法的源码:
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
MessageQueue queue = mQueue;//step1获取构造器中初始化的MessageQueue
if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
return false;
}//调用enqueueMessage方法
return enqueueMessage(queue, msg, uptimeMillis);
}
由上面看出sendMessageAtTime最终掉用了handler的enqueueMessage()方法发送消息,enqueueMessage()源码如下:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
/**
注意: msg.target = this;将当前Handler对象存储到当前消息的 msg.target中,照应了Looper.loop()方法中拿到消息后通过msg.target获取当前handler.调用msg.target.dispatchMessage()方法处理消息,即最终又交给了当前handler处理消息*/
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
//最终调用MessageQueue的enqueueMessage(msg, uptimeMillis);进行消息入队操作
//queue.enqueueMessage方法在上面已经分析
return queue.enqueueMessage(msg, uptimeMillis);
}
用dispatchMessage()方法处理消息, 是在Looper的loop()方法中调用处理消息,源码如下:
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
//处理消息时判断是否拦截消息mCallback.handleMessage(msg),返回true则不会执行下面的
//handleMessage(msg),即拦截了消息
return;
}
}
//如果不拦截,回掉handleMessage方法处理消息
handleMessage(msg);
}
}
到此handler的发送和处理的源码分析完成。
为什么在主线程中初始化Handler对象不需要先初始化Looper
简单分析一下ActivityThread主线程中的main方法的源码:
//此方法是应用程序的主入口
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
SamplingProfilerIntegration.start();
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
// Set the reporter for event logging in libcore
EventLogger.setReporter(new EventLoggingReporter());
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("<pre-initialized>");
//在应用程序启动时就初始化了主线程的Looper对象
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
//开启死循环轮询查询消息
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
总结
到此为止handler的源码分析完毕。总结一下,我们通过handler发送消息的过程就是通过Looper获取MessageQueue调用eqeueMessage方法入队的过程,而处理消息的过程就是通过Looper的loop方法不断的从当前线程的MessagQueue中取出消息交给发送消息的handler对象调用dispatchMessage方法处理消息,因此handler在哪个线程实例化就在哪个线程处理消息。
这是第一次写博客,希望这篇文章对大家有所帮助,里面的不足之处请大家留言指正。我后续也会继续分享和编写更多干货,请大家多多支持和点赞!!!谢谢