Handler机制主要用于异步消息的处理:当发出一个消息之后,首先进入一个消息队列,发送消息的函数即刻返回,而另外一个部分在消息队列中逐一将消息取出,然后对消息进行处理,也就是发送消息和接收消息不是同步的处理,这种机制适合用来处理相对耗时比较长的操作。
所以在Android中通常用来更新UI,子线程执行任务,任务执行完毕后发送消息:Handler.sendMessage(),然后在UI线程Handler.handleMessage()就会调用,执行相应处理。
Handler机制有几个非常重要的类:
Handler:用来发送消息:sendMessage等多个方法,并实现handleMessage()方法处理回调(还可以使用Message或Handler的Callback进行回调处理)。
Message:消息实体,发送的消息即为Message类型。
MessageQueue:消息队列,用于存储消息。发送消息时,消息入队列,然后Looper会从这个MessageQueen取出消息进行处理。
Looper:与线程绑定,不仅仅局限于主线程,绑定的线程用来处理消息。loop()方法是一个死循环,一直从MessageQueen里取出消息进行处理。
在这里需要注意的是:一个线程里面只会有一个Looper和一个MessageQueue,可以有多个Handler对象,
MessageQueue是在Looper对象创建的时候一起创建的,在Handler创建之前该线程必须先创建好Looper对象,否则将会报以下错误:
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
整个工作流程图如下:
接下来开始工作流程源码的分析:
源码的分析是根据使用步骤进行:
1.先创建一个Handler
/**
* 此处以 匿名内部类 的使用方式为例
*/
private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
}
};
当我们在主线程当中,可以直接进行Handler的创建。如果是在子线程当中,在创建之前必须先初始化Looper,否则会RuntimeException;
public Handler(Callback callback, boolean async) {
// 省略部分的代码
// 那当前线程的Looper,如果为空抛异常
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
// 获得MessageQueue的对象,当Looper创建的时候同时会创建MessageQueue对象
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
在子线程中使用handler除了必须先初始化Looper对象之外,还必须在最后调用Looper.loop()来启动循环,否则Handler仍然无法正常接收。 而我们平时在主线程中创建handler之所以不用再去创建Looper对象是因为主线程在初始化的时候就已经跟着创建了一个Looper,就在ActivityThread的main方法里面
public static void main(String[] args) {
// 省略部分代码
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
// Looper.loop();在这里也是会放到最后才执行,开启一个循环,当Looper.loop();意外退出的时候将会抛异常
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
再点进Looper.prepareMainLooper();里面,接着往下看可以发现其内部也是调用了prepare(false);方法
public static void prepareMainLooper() {
// 在这个方法里面会创建一个Looper,同时quitAllowed传false意思是Looper不允许结束循环
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
// 创建Looper的方法
private static void prepare(boolean quitAllowed) {
// 通过ThreadLocal将Looper与当前的线程绑定,也意味着每个线程都是只有唯一个Looper,当你创建第二个的时候则会报错
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
// 创建Looper时候调用的构造函数
private Looper(boolean quitAllowed) {
// 只有当Looper创建的时候才会同时创建 MessageQueue 对象,所以一个线程里面只会存在一个Looper和一个MessageQueue
// 同时对应多个的Handler和Message,而且Looper和MessageQueue都是在Handler和Message尚未创建之前就已经创建好的
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
2.当我们使用Handler进行发送消息的时候 Handler发送消息的方式有很多种,包括发送延时,即时或空的消息,或者是一个Runnable,查看相关的源码我们会发现最终都是调用了同一个方法MessageQueue的enqueueMessage();
// Handler发送消息最终会走到的方法
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
// 最后调用了MessageQueue#enqueueMessage(msg, uptimeMillis);
return queue.enqueueMessage(msg, uptimeMillis);
}
继续追踪点开查看MessageQueue的enqueueMessage();的全部源码
boolean enqueueMessage(Message msg, long when) {
//Meesage是否可用
//这里的msg.target指的就是发送该Message的Handler
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) {
// 判断是否调用了quit()方法,即取消信息;如果调用了,说明Looper已经停止了,同时所有的消息都已经被取消
// 需要注意的是如果是主线程调用quit()方法将会抛异常
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.
// 如果Looper.loop()是休眠状态,则调用native方法唤醒loop()
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
需要注意的一点是,在MessageQueue中Message的保存是以链表的形式存储的,即只有上一个的Message才知道它的下一个Message是谁,而当前的MessageQueue也是不知道的 然后再从Looper.loop()方法中取出消息,继续追踪源码如下:
public static void loop() {
// 获取当前Looper的消息队列,其中myLooper()作用:返回sThreadLocal存储的Looper实例;若me为null 则抛出异常;
// 即loop()执行前必须执行prepare(),从而创建1个Looper实例
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;
// 省略中间的部分源码。。。
// 开启循环取出消息
for (;;) {
// 从消息队列中取出消息,如果是没有消息的话,在queue.next();阻塞线程
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
// 省略中间部分代码
final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
final long dispatchEnd;
try {
// 将取出的消息派发到对应的Handler
msg.target.dispatchMessage(msg);
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
// 省略部分代码。。。
// 释放消息所占用的资源
msg.recycleUnchecked();
}
}
// 在Looper.loop()中调用了MessageQueue#next()源码如下
Message next() {
// 省略部分的代码。。。
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
// nativePollOnce方法在native层,若是nextPollTimeoutMillis为-1,此时消息队列处于等待状态
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
// 从队列里面取出消息,如果消息为空的话,nextPollTimeoutMillis = -1,则会阻塞线程,此时消息队列进入等待的状态
if (msg != null && msg.target == null) {
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 (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
// 没有消息的时候
nextPollTimeoutMillis = -1;
}
// 省略部分代码。。。
// 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;
}
}
当消息从Looper.loop()中被取出就会分调用了相对应的Handler#dispatchMessage()传递消息
// Handler#dispatchMessage的源码如下,在Looper.loop()中被调用
public void dispatchMessage(Message msg) {
// 先判断了当前的消息类型是否Handler.post()时使用Runnable
if (msg.callback != null) {
// 如果是传入的Runnable则调用此方法,会调用Runnable.run()
handleCallback(msg);
} else {
if (mCallback != null) {
// 如果在创建Handler时候传入自定义Callback,则会调用此方法,并且可以限定Handler#handleMessage()是否执行
if (mCallback.handleMessage(msg)) {
return;
}
}
// 如果都没有则调用Handler#handleMessage()方法
handleMessage(msg);
}
}
到此整个的Handler机制和源码也分析得差不多了!!!
字比较多,写得好累