之前一篇文章(Handler)略微分析了Android中的消息机制,然后今天贴出runOnUiThread方法的分析(笔记早就整理好了,只是一直没有整理成博客):
先对消息机制的四大对象进行一个大致的总结吧
1. MessageQueue:消息队列,它的内部存储了一组消息,以队列的形式对外提供插入和删除的工作。采用单链表的数据结构来存储消息列表。请看此类中的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("MessageQueue", 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;
}
注意:它只是一个消息的存储单元,它不能处理消息。
2. Looper:会以无限循环的形式去查找是否有新消息,如果有的话就处理消息,否则就一直等待。Looper中有一个ThreadLocal的概念,注意他不是线程,它的作用是可以在每个线程中存储数据。谨记一点:线程默认是没有Looper的,如果需要使用Handler就必须为线程创建Looper。
3. Handler:Handler创建时会采用当前线程的Looper来构建内部的消息循环系统,如果当前线程没有Looper,那么我们必须为当前线程创建Looper即可。Each Handler instance is associated with a single thread and that thread’s message queue. When you create a new Handler, it is bound to the thread /message queue of the thread that is creating it- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.
4. runOnUiThread()方法分析:先看怎么用这个方法吧。这个方法接收一个Runnable型的参数。例如可以这么写:
runOnUiThread(new Runnable(){
public void run(){
//执行更新ui的操作
}
});
记住此时传入了一个Runnable对象。还有一点切记:这段代码中没有开启线程,只是new了一个Runnable接口的子类的对象。
在Activity类中找到这个方法的源码:
/**
* Runs the specified action on the UI thread. If the current thread is the UI
* thread, then the action is executed immediately. If the current thread is
* not the UI thread, the action is posted to the event queue of the UI thread.
*
* @param action the action to run on the UI thread
*/
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
在if条件判断中,如果当前线程不是主线程的话,调用mHandler.post()方法。先看mHandler是什么东西:
private Thread mUiThread;
final Handler mHandler = new Handler();
就是个Handler对象。然后调用Handler的post实例方法,去Handler类的源代码中找到post方法的实现:
/**
* Causes the Runnable r to be added to the message queue.
* The runnable will be run on the thread to which this handler is
* attached.
*
* @param r The Runnable that will be executed.
*
* @return Returns true if the Runnable was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*/
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
看sendMessageDelayed方法中第一个参数传入的是:
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
通过Message.obtain()方法从消息池中返回一个Message对象,并将r(也就是我们在)调用runOnUiThread()时创建的Runnable子类的对象赋给了callback(记住这个操作,后面会用到),然后将这个Messge对象返回。再回到post()方法,进入sendMessgeDelayed()方法:
/**
* Enqueue a message into the message queue after all pending messages
* before (current time + delayMillis). You will receive it in
* {@link #handleMessage}, in the thread attached to this handler.
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting. Note that a
* result of true does not mean the message will be processed -- if
* the looper is quit before the delivery time of the message
* occurs then the message will be dropped.
*/
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
再跟进去:
/**
* Enqueue a message into the message queue after all pending messages
* before the absolute time (in milliseconds) <var>uptimeMillis</var>.
* <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
* Time spent in deep sleep will add an additional delay to execution.
* You will receive it in {@link #handleMessage}, in the thread attached
* to this handler.
*
* @param uptimeMillis The absolute time at which the message should be
* delivered, using the
* {@link android.os.SystemClock#uptimeMillis} time-base.
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting. Note that a
* result of true does not mean the message will be processed -- if
* the looper is quit before the delivery time of the message
* occurs then the message will be dropped.
*/
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);
}
嗯,这些方法我们在前面分析整个消息机制时都见过,忘了可以看上一篇博客中的分析。总之,就是向MessageQueue中插入了一条消息。
前面到这个时候就是去分析Looper.loop()方法的,然后分析流程到Handler的dispatchMessage()方法,现在我们再来看一下这个方法的实现,去关注以前分析时被我们主动忽略的地方:
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
看这个if语句:sg.callback不为null时,就执行handleCallback()方法,那我们现在的这个msg中的callback是不是为空呢?再看getPostMessage(前面提过,请往上翻)方法:
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
在这里已经把我们重写的Runnable子类对象赋给了他。那我们现在就需要来看看handleCallback方法的实现:
private static void handleCallback(Message message) {
message.callback.run();
}
一目了然,在这里调用了我们重写的run()方法,就可以执行我们的更新UI的操作了。为什么现在就可以了呢?不要忘了,现在这个当前Handler对象是与主线程关联的,怎么知道的?这个时候我们去翻看一下API中关于Handler类的阐述:
A Handler allows you to send and process Message and Runnable objects associated with a thread’s MessageQueue. Each Handler instance is associated with a single thread and that thread’s message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it – from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.
注意加粗部分,翻译过来就是在哪个线程中创建了Handler对象(实际上这句话也可以用代码证明,只要翻看另一份文档中关于Handler的构造方法就知道了),那么这个Handler对象就与创建它的线程绑定。再去翻看我们关于runOnUiThread方法实现的分析,就明白当前这个Handler对象是主线程创建的,既然是在主线程中,我们当然可以执行更新UI操作啦。这样,我们就实现了更新UI的操作转换了。