前言
作为一个android developer,安卓消息机制可谓再熟悉不过了,在平时的开发过程中更是少不了它的存在。我们都知道handler通常用于子线程更新ui,通常情况下,如果主线程有耗时操作,页面有可能会发生卡顿,严重情况下还会出现anr,所以我们会开辟一个新线程来执行耗时操作,执行结束后如果需要进行ui更新就可以利用handler切换到主线程操做ui。本质上说handler机制并不是专门用来更新ui的,更新ui只是handler的一种使用场景。那么为什么主线程不允许子线程更新ui呢,因为安卓ui控件不是线程安全的,如果在多线程并发的情况下访问会导致ui控件处于不可预期的状态,那么为什么不对ui访问进行上锁呢,主要原因就是上锁会导致ui访问逻辑变得复杂,并发访问还会进行等待,大大降低了了ui访问的效率,从而导致性能降低。
源码分析
提到handler机制,少不了Looper,MessageQueue,Message,ThreadLocal。
下面我们将从源码的角度来分析handler的工作流程。
public static void main(String[] args) {
//step 1
Looper.prepareMainLooper();
//step 2
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
//step 3
Looper.loop();
}
当我们打开app之后,首先会运行ActivityThread的main()方法,所以我们从这里开始分析。
1.为主线程创建一个Looper对象。
2.创建一个默认的主线程。
3.调用Looper.loop()开启循环。
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
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();
}
为主线程创建一个Looper对象,我们看到Looper的构造方法中还生成了一个消息队列对象(Messagequeue),此时Looper与Messagequeue绑定,并且Looper被存放在一个专门存放线程变量的ThreadLocal内,ThreadLocal本章暂时不分析。
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;
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
return;
}
msg.target.dispatchMessage(msg);
msg.recycleUnchecked();
}
}
1.首先从ThreadLocal内取出之前存放的Looper对象me,若返回空,则抛出一个异常。
2获取之前创建的消息队列queue。
3.开启无限消息循环,不断遍历消息队列。如果有消息调用Message中的target.dispatchMessage(msg)将消息分发下去,无消息即message为空则返回。
4.释放Message。
这里说明一点,target实际上是一个与Message绑定的Handler对象,下面会有说明。
Message next() {
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
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;
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 (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
}
}
}
我们来看一下消息队列是怎么遍历读取消息的。
从上面代码上可以看到,Messagequeue实际上是一个单链表,且源码中也作了英文注释,nextPollTimeoutMillis该参数用来确定队列中是否还有消息,nativePollOnce(ptr, nextPollTimeoutMillis);从方法名上猜测应该是调用了native方法,没错,这个方法主要作用是在没有消息的情况下进行等待。消息的读取顺序是根据存放的时间来操作的,当消息被取完之后,nextPollTimeoutMillis会被置为-1,下次循环时队列进入等待状态。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
再来看消息分发的方法。
三种情况也对应了handler的三种用法。
1)Message的callback不为空 > handleCallback()> message.callback.run();
2)mCallback不为空 > mCallback.handleMessage();
3)mCallback为空 > handleMessage();
以上为消息的查询处理,接下来看消息是如何插入的,也是我们经常做的。
public Handler() {
this(null, false);
}
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 " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
通常我们会在主线程中Handler handler = new Handler(){}的方式获取Handler实例,我们从上面的源码中可以看到最终调用到Handler的另一个构造方法,构造方法中获取主线程中的Looper,并得到Looper中的消息队列。到此为止Handler,Looper,Messagequeue好像已经发生了关系。
Message message = Message.obtain();
message.what = 0;
message.obj = "hello world";
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();
}
接下来我们会再子线程中用handler发送消息到主线程中。
先用Message.obtain()获取到Message实例,Message内部维护了一个message池
,用于message对象的复用,减少内存分配,若不可复用就用new重新创建。
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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
最终调用到handler.enqueueMessage,msg.target = this,这句代码与上述msg.target.dispatchMessage(msg)相关联。Message和Handler绑定,MessageQueue和Message绑定。
接着我们看Messagequeue.enqueueMessage()方法。
boolean enqueueMessage(Message msg, long when) {
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;
}
到这里handler发送的message就被添加到了消息队列中,之后通过Looper不断的取出Message,并通过与之绑定的handler分发到handler的handlerMessage()。
另一种handler的使用方式handler.post()
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
和sendMessage一样调用到sendMessageDelayed(),只不过需要调用getPostMessage()将其封装成Message,但这个message的callback也被赋值。
最后我们回到
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
至此,就已经很清楚了
1.msg.callback != null 说明使用的handler.post
2.callback ==null 说明使用的handler.sendMessag(等于null有两种情况,一种是匿名类handleMessage,一种是实现handler.callback,这两种方式的本质是一样的)。
总结
大致流程:首先在我们打开app时,在ActivityThread中的main函数里会为我们默认创建一个Looper,并开启一条消息队列,然后Looper.loop开始进行无限循环的消息读取,这时我们用handler.send发送了一个消息到消息队列中,这时消息队列获取Message,并通过Message.target.dispatchMessage(msg),最终被handler.dispatchMessage()分发下去。这也是为什么我们在子线程中无法使用handler的原因,当然如果需要在子线程中使用handler,就可以模仿主线程中的Looper创建方式来开启消息循环,这样就可以在子线程中愉快的使用handler了。
只是简单的根据源码梳理了一下流程。如果有错误,欢迎指出。