我们常说的安卓的消息机制其实就是Handler的运行机制。Hanlder的底层是由MessageQueue和looper作为支撑。
ThreadLocal
ThreadLocal不是一个线程,而是在每个线程中存储数据。它可以在不同的线程中互补干扰的获取存储数据,通过ThreadLocal可以获取每个线程的looper。
当我们使用Handler的时候,系统内部会创建一个Looper来构造消息系统,对于我们常提高的UI线程,指的就是ActivityThread,在ActivityThread创建的时候就会初始化一个Looper,当我们使用的时候,可以直接创建一个Handler。
在平常的开发中当在子线程中直接使用Handler时会报错
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.(Handler.java:200)
at android.os.Handler.(Handler.java:114)
at com.example.ljingya.myapplication.MainActivity$1$1.(MainActivity.java:19)
at com.example.ljingya.myapplication.MainActivity$1.run(MainActivity.java:19)
at java.lang.Thread.run(Thread.java:841)
需要在创建Handler之前创建一个Looper
Looper.prepare();
在该方法内部会调用ThreadLocal的set方法创建一个Looper,并保存当前线程。
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));
}
private Looper(boolean quitAllowed) {
//创建一个消息队列
mQueue = new MessageQueue(quitAllowed);
//保存当前线程
mThread = Thread.currentThread();
}
当创建Handler时在时会先获取当前线程的Looper,若Looper为null则抛出异常。
public Handler(Callback callback, boolean async) {
mLooper = Looper.myLooper();
//判断Looper是否为null
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.loop();
在loop方法中主要做这样几件事情:
获取当前的Looper。
从Looper中拿到消息队列
通过循环调用队列的next方法获取Message,当message为空时返回null,并阻塞该队列。
当有消息时调用msg.target.dispatchMessage(msg)及调用Handler的dispatchMessage方法处理该消息
public static void loop() {
//获取当前的Looper。
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
//从Looper中拿到消息队列
final MessageQueue queue = me.mQueue
....省略代码
for (;;) {
//通过循环调用队列的next方法获取Message,当message为空时返回null,并阻塞该队列。
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
...省略代码
//当有消息时调用msg.target.dispatchMessage(msg)及调用Handler的dispatchMessage方法处理该消息
msg.target.dispatchMessage(msg);
...省略代码
}
}
在Handler的dispatchMessage中则最终调用消息的回调处理。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
//消息处理的回调
handleMessage(msg);
}
}
当在使用中调用Handler的sendMessage方法时,只是想消息队列中插入一条消息,当开启轮询时会不断的从队列中处理队列中的消息。
//调用sendMessage
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
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);
}
//在这个方法中最后调用队列的enqueueMessage方法将消息插入队列中。
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
在上面提到在创建Handler时会检查Looper是否为null,若没有初始化Looper对象会抛出异常。
public Handler(Callback callback, boolean async) {
mLooper = Looper.myLooper();
//判断Looper是否为null
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;
}