一篇文章深入分析Handler源码
首先附上我的几篇其它文章链接感兴趣的可以看看,如果文章有异议的地方欢迎指出,共同进步,顺便点赞谢谢!!!
Android framework 源码分析之Activity启动流程(android 8.0)
Android studio编写第一个NDK工程的过程详解(附Demo下载地址)
面试必备1:HashMap(JDK1.8)原理以及源码分析
面试必备2:JDK1.8LinkedHashMap实现原理及源码分析
Android事件分发机制原理及源码分析
View事件的滑动冲突以及解决方案
Android三级缓存原理及用LruCache、DiskLruCache实现一个三级缓存的ImageLoader
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()方法源码 :