Handler + Looper + Message + Message Queue关系
基本概念
-
Message
:消息对象 -
MessageQueue
:存储消息对象的队列 -
Looper
:负责循环读取MessageQueen中的消息,读到消息之后就把消息交给Handler去处理。 -
Handler
:发送消息和处理消息
下面从源码角度分别看下各个对象的作用。
Looper
要想使用Handler
,首先要保证当前所在线程存在Looper
对象。主线程不需要主动创建Looper
对象是因为主线程已经为你准备好了,详见android.app.ActivityThread
->Looper.prepareMainLooper()
我们创建的子线程如果想用Handler
接收数据,需要先通过Looper.prepare()
创建Looper
Looper.prepare();
// 创建Handler并传入
Looper.loop()
Looper构造方法
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
创建Looper
对象的时候,同时创建了MessageQueue
,并让Looper
绑定当前线程。但我们从来不直接调用构造方法获取Looper
对象,而是使用Looper
的prepare()
方法。prepare()
使用ThreadLocal
保存当前Looper
对象,ThreadLocal
类可以对数据进行线程隔离,保证了在当前线程只能获取当前线程的Looper
对象,同时prepare()
保证当前线程有且只有一个Looper
对象,间接保证了一个线程只有一个MessageQueue
对象。
MessageQueue
只是一个消息的存储单元,它不能去处理消息,Looper
填补了这个功能,Looper
会以无限循环
的模式去查看Message
中是否有新消息,否则就一直等待。
Looper的prepare()
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开启循环
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;
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
for (;;) {
// might block 也许会堵塞,一会在next方法中解析
Message msg = queue.next();
if (msg == null) {
return;
}
try {
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
msg.recycleUnchecked();
}
}
Lopper
通过loop()
开启无限循环,通过MessageQueue
的next()
获取message
对象。一旦获取就调用msg.target.dispatchMEssage(msg)
将msg
交给Handler
对象处理(msg.target
是Handler
对象),最后回收。
Handler
Hanlder实例化
public Handler(Callback callback, boolean async) {
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;
}
实例化过程中获取当前线程的MessageQueue
对象,以便于将消息加入MessageQueue
发送消息
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);
}
将消息加入队列
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
enqueueMessage()
中首先为msg.target
赋值为this
,为发送消息出队列交给Handler
处理埋下伏笔。
处理消息
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
前面我们提到Looper.loop()
获取到消息时会调用Handler
的dispatchMessage()
方法进行处理,Handler
处理消息就是调用我们重写的handleMessage()
方法,或者我们可以在创建Handler
实例时实现Callback
接口,一样可以处理从MessageQueue
出来的消息.
MessageQueue
MessageQueue 构造方法
MessageQueue(boolean quitAllowed) {
mQuitAllowed = quitAllowed;
mPtr = nativeInit();
}
MessageQueue
初始化过程同时初始化底层的NativeMessageQueue对
象,并且持有NativeMessageQueue
的内存地址(long)。
MessageQueue
它内部存储了一组消息,以队列的形式对外提供插入和删除的工作。内部结构不是真正的队列,而是采用单链表
的数据结构来存储消息列表。
MessageQueue的next()
Message next() {
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(); // 刷一下,就当是Android系统的一种性能优化操作
}
nativePollOnce(ptr, nextPollTimeoutMillis); // native底层实现堵塞,堵塞状态可被新消息唤醒,头一次进来不会延迟
synchronized (this) {
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;//获取头节点消息
if (msg != null && msg.target == null) {
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);//获取堵塞时间
} else {
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 {
nextPollTimeoutMillis = -1; // 队列已无消息,一直堵塞
}
if (mQuitting) {
dispose();
return null;
}
pendingIdleHandlerCount = 0;
nextPollTimeoutMillis = 0;
}
}
}
虽然looper
也开启了循环,但是到了真正干活的时候它却调用了MessageQueue
的next()
,要想搞明白怎么个堵塞,先看这三个对应的条件:
-
nextPollTimeoutMillis
=0 不堵塞 -
nextPollTimeoutMillis
<0 一直堵塞 -
nextPollTimeoutMillis
>0 堵塞对应时长,可被新消息唤醒
next()
中,因为消息队列是按照延迟时间排序的,所以先考虑延迟最小的也就是头消息。当头消息为空,说明队列中没有消息了,nextPollTimeoutMIllis
就被赋值为-1,当头消息延迟时间大于当前时间,堵塞消息要到延迟时间和当前时间的差值
当消息延迟时间小于等于0,直接返回msg
给Handler
处理
nativePollOnce(ptr, nextPollTimeoutMillis)
方法是native
底层实现堵塞逻辑,堵塞状态会到时间唤醒,也可被新消息唤醒,一旦唤醒会重新获取头消息,重新评估是否堵塞或者直接返回消息
消息入栈enqueueMessage()
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;
}
消息入栈时,首先会判断新消息如果是第一个消息 或者 新消息没有延迟 或者 新消息延迟时间小于队列第一个消息的,都会立刻对这个消息进行处理。只有当消息延迟大于队列头消息时,才会依次遍历消息队列,将消息按延迟时间插入消息队列响应位置。
Message
Message 初始化
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();
}
建议使用obtain()
获取Message
对象,因为Message
维护着一个消息池,这个消息池的数据结构是单向链表,优先从池子里拿数据,如果池子里没有再创建对象。如果Message
对象已存在,可以使用obtain(msg)
方法,最终也会调用obtain()
。
消息的回收
void recycleUnchecked() {
flags = FLAG_IN_USE;
what = 0;
arg1 = 0;
arg2 = 0;
obj = null;
replyTo = null;
sendingUid = -1;
when = 0;
target = null;
callback = null;
data = null;
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
消息的回收不是将Message
对象销毁,而是将Message
对象的值恢复初始值然后放回池子,等待使用
因为android
会频繁的使用Message
的对象,使用“池”这种机制可以减少创建对象开辟内存的时间,更加高效的利用内存,因此"池"这种机制被应用于频繁大量使用的类对象的情况,我们常说的“线程池”也是基于同样的原理。
总结
- 要想在当前线程使用
Handler
机制,首先确保当前线程存在Looper
-
Looper.parper()
创建一个 当前线程的Looper
对象,同时创建一个MessageQueue
对象 - 每个线程只有一个
Looper
对象和一个MessageQueue
对象 -
Looper.loop()
开始循环,没有msg
情况下进入堵塞状态(-1) -
Message
对象最好通过Message.obtain()
获得 -
Handler
发送消息进入队列,如果没有延迟唤醒堵塞Looper
获得msg
,调用msg.targe.dispachMessage
处理消息 - 关闭
Activity
时如果栈中有未出栈的message
,需清除handler.removeMessage(int)
- 子线程不再使用
Handler
时,要调用loop.quit()
,loop.quitSafely()
- 虽然表面上看是
Looper
循环队列,并将message
给Handler
,但实际上是MessageQueue
的next()
去完成的,MessageQueue
同时还承担消息的入队列,并对消息按照延迟时间从小到大进行了排序。鉴于MessageQueue
如此大的工作量,在Android 2.3版本后,MessageQueue
中next()
方法的堵塞机制转移到native层去处理,也就是我们使用的nativePollOnce(ptr, nextPollTimeoutMillis)
方法
异常Can't create handler inside thread that has not called Looper.prepare()
示例代码:
new Thread(new Runnable() {
@Override
public void run() {
timer = new Timer(mTotalTime, TimeSetted.SECOND_TO_MILL);
timer.start();
Log.d(TAG,"Countdown start");
}
}).start();
- 出现异常:
java.lang.RuntimeException: Can't create handler inside thread Thread that has not called Looper.prepare()
崩溃 - 报错原因:
Timer
底层采用的是Handler
+Message
实现,非主线程中没有开启Looper
,而Handler
对象必须绑定Looper
对象需要调用Looper.prepare()
来给线程创建一个消息循环,调用Looper.loop()
来使消息循环起作用。 - 修复方法
- 方案一:即在具体逻辑的前后加入
Looper.perpare()
和Looper.loop()
方法。 - 方案二:通过
Looper.getMainLooper()
,获得主线程的Looper
,将其绑定到此Handler
对象上。
- 方案一:即在具体逻辑的前后加入
修复代码:
new Thread(new Runnable() {
@Override
public void run() {
Looper.perpare(); // 增加部分
timer = new Timer(mTotalTime, TimeSetted.SECOND_TO_MILL);
timer.start();
Log.d(TAG,"Countdown start");
Looper.loop(); // 增加部分
}
}).start();
结论:
-
Can't create handler inside thread Thread that has not called Looper.prepare()
通常是在子线程中使用没有绑定Looper
的handler
时出现,只需在handler
语句的前后加Looper.prepare()
和Looper.loop()
方法即可。 - 创建子线程
Thread
和使用AsyncTask
的doInBackground
时,若没有new一个handler
对象,通常不会出现这个错误。本人是由于在调用其他方法时用了handler
导致报错。