handler消息机制
一、looper和meesageQueue的创建
主线程不需要程序员创建Looper和MessageQueue 由系统调用Looper.prepareMainLooper();
其实调用的就是Looper.prepare();方法,通过一个线程级单例 threadLocal 把创建的looper保存起来。
在调用Looper.prepare()的时候先通过 threadLocal 去获取当前线程的looper,如果能获取到直接抛异常,这样就保证了一个线程对应一个Looper,Looper在创建的过程中 调用了MessageQueue的构造创建了一个MessageQueue ,通过一个final类型成员变量保存起来,这样一个Looper对应一个MessageQueue ,一个线程对应一个Looper对应一个MessageQueue 。
MessageQueue在创建的时候 有创建了一个NativeMessageQueue NativeMessageQueue在创建的时候有创建了一个C++的looper,MessageQueue通过一个int类型的成员变量“mptr”保存了NativeMessageQueue 的指针, 可以随时通过jni的调用找到NativeMessageQueue、进而找到looper。消息循环的过程中阻塞的机制就是通过NativeMessageQueue和C++的Looper 在底层实现的,用到了linux的管道和epoll机制。
二、Looper让消息队列循环起来
Looper.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 可能会阻塞 阻塞实际上是通过nativeMessageQueu和c++looper实现的
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);// msg.target 是一个handler对象 dispatchMessage分发消息
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.recycle();
}
}
MessageQueue next方法
final Message next() {
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(mPtr, nextPollTimeoutMillis);//传入一个消息超时的时间,如果超时时间没到会阻塞,时间到了会继续执行,用到了linux的pipe和epoll机制
synchronized (this) {
if (mQuiting) {
return null;
}
// 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);
msg.markInUse();
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
// 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;
}
}
handler的dispatchMessage方法
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {//如果Message的callback(Runnable)对象 不为空 会执行 handleCallback方法 实际上就是执行了Runnable的run方法
handleCallback(msg);
} else {
if (mCallback != null) { //如果当前handler传递了一个mCallback(实现了Callback接口) 会走CallBack接口的handlerMessage方法
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);//如果前面两个都为空才会走到handleMessage
}
}
三、handler的创建
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;
}
如果在子线程使用handler 需要手动调用Looper.prepare()方法 之后调用了Looper.prepare()方法之后才能够new Handler
再通过Looper.loop()让消息队列循环起来
四、handler发消息
handler、sendMessage、sendEmptyMessage、sendMessgeDelayed、sendEmptyMessageDelayed 实际上执行的都是sendMessageAtTime,sendMessageAtTime执行的是enqueueMessage
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;//首先把消息.target赋值为当前的handler。这样,由哪个handler发的消息就由这个handler来处理消息。
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
调用MessageQueue的enqueueMessage方法,实际上就是消息放到消息队列的过程
final boolean enqueueMessage(Message msg, long when) {
if (msg.isInUse()) {
throw new AndroidRuntimeException(msg + " This message is already in use.");
}
if (msg.target == null) {
throw new AndroidRuntimeException("Message must have a target.");
}
boolean needWake;
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;
}
msg.when = when;
Message p = mMessages;
if (p == null || when == 0 || when < p.when) {//说明当前传入的消息是第一条消息 用消息队列的mMessage来保存
// 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 (;;) {//说明当前的消息不是第一条 通过第一条消息向后找 通过比较msg.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;
}
}
if (needWake) {
nativeWake(mPtr);
}
return true;
}
messageQueue实际上只保存了所有消息中的第一条消息,每一个消息都有一个next成员变量指向下一条消息,消息在消息队列的先后顺序,就是通过消息要执行的时间来排序的,先执行的排在前面
如果刚放到消息队列里的消息需要立即执行,会通过nativeWake 往文件标识符里面写个'W'来唤醒Looper,就可以把消息取出来通知handler处理
五、Message的创建和回收
创建消息要使用消息池 Message.obtain()方法
Message 类有几个全局变量
1. private static Message sPool; //消息池的第一条消息
2. private static int sPoolSize = 0; //消息池消息的数量
3. private static final int MAX_POOL_SIZE = 50; //消息池最多缓存50条消息
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {//如果消息池不为空 取出消息池的第一条消息
Message m = sPool; //把它的下一条消息作为消息池的第一条
sPool = m.next;
m.next = null;
sPoolSize--;//消息池大小-1
return m;//返回消息
}
}
return new Message();
}
当消息处理完毕之后 会调用Message的recycle方法回收消息
/**
* Return a Message instance to the global pool. You MUST NOT touch
* the Message after calling this function -- it has effectively been
* freed.
*/
public void recycle() {
clearForRecycle();//先把消息所有的成员变量变为刚new出来的状态
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {//如果当前消息池不够50个对象
next = sPool; //把这一条消息放到消息池中的第一条
sPool = this;
sPoolSize++;//消息池大小+1
}
}
}
void clearForRecycle() {
flags = 0;
what = 0;
arg1 = 0;
arg2 = 0;
obj = null;
replyTo = null;
when = 0;
target = null;
callback = null;
data = null;
}