1,四个概念
Handler,Looper,Message,MessageQuene
2,消息传递机制的大致流程
Handler调用 sendMessage()发送Message,传递给MessageQuene,Looper不断循环MessageQuene去除Message, 交给Handler的handleMessage()方法处理Message。
3,几个注意点
3.1子线程是不能直接new Hander()的,需要先调用Looper.prepare(),因为每个线程要使用Handler的话都要和Looper一起,Looper.prepare()方法就是用来设置Looper的,即通过ThreadLocal设置Looper,代码:sThreadLocal.set(new Looper()); 设置后会在Handler构造方法里再通过sThreadLocal 获取,不然,从Handler的构造方法中可以看出,没有Looper会抛出Can't create handler inside thread that has not called Looper.prepare()的异常
public Handler() {
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());
}
}
//通过Looper.myLooper()获取Looper,其实调用的就是sThreadLocal.get();
mLooper = Looper.myLooper();
//每个线程都需要有Looper,不然会抛出如下异常
//Can't create handler inside thread that has not called Looper.prepare()
if (mLooper == null) {
throw new RuntimeException(
//抛出异常
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = null;
}
public static final void prepare() {
if (sThreadLocal.get() != null) {
//只能有一个Looper
throw new RuntimeException("Only one Looper may be created per thread");
}
//通过ThreadLocal设置Looper
sThreadLocal.set(new Looper());
}
public static final Looper myLooper() {
//通过ThreadLocal获取Looper
return (Looper)sThreadLocal.get();
}
3.2,通过Handler 的obtain()方法获取Message对象,复用Message,从sPool直接获取
/**
* 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();
}
3.3 handler发送消息的方法内部最终是调用了下面的方法,从这里可以看出MessageQuene并没有真实采用队列去存储Message,而是采用单向链表的数据结构存储Message,用next指向下一个Message。
final boolean enqueueMessage(Message msg, long when) {
if (msg.when != 0) {
throw new AndroidRuntimeException(msg + " This message is already in use.");
}
if (msg.target == null && !mQuitAllowed) {
throw new RuntimeException("Main thread not allowed to quit");
}
synchronized (this) {
if (mQuiting) {
RuntimeException e = new RuntimeException(msg.target + " sending message to a
Handler on a dead thread");
Log.w("MessageQueue", e.getMessage(), e);
return false;
} else if (msg.target == null) {
mQuiting = true;
}
msg.when = when;
Message p = mMessages;
if (p == null || when == 0 || when < p.when) {
msg.next = p;
mMessages = msg;
this.notify();
} else {
Message prev = null;
//采用单向链表的数据结构存储Message,next指向下一个Message
while (p != null && p.when <= when) {
prev = p;
p = p.next;
}
msg.next = prev.next;
prev.next = msg;
this.notify();
}
}
return true;
}
3.4,Message的recycle方法,如果sPoolSize小于最大数量(50),就缓存到这个以sPool打头的单向链表里来,已备Obtain()取用
/**
* 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;
}
recycleUnchecked();
}
/**
* Recycles a Message that may be in-use.
* Used internally by the MessageQueue and Looper when disposing of queued Messages.
*/
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;
//MAX_POOL_SIZE = 50
synchronized (sPoolSync) {
//如果小于最大数量,将当前对象缓存在单向链表的最前端(sPool)
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
参考博客:
https://blog.csdn.net/u013435893/article/details/50854327
https://www.jianshu.com/p/8ecacbb97af4