Android消息机制简介

相关类介绍

先来看下相关类在源码中的注释。

  • Handler

    Handler类注释:Handler可以向与线程关联的MessageQueue中发送MessageRunnable对象,并可以处对这些Message及Runnable对象进行处理.每一个Handler都和一个线程以及该线程的MessageQueue关联。当创建一个Handler时,该Handler就会和创建该Handler的线程MessageQueue绑定–之后Handler将传递Message和runnable objects给该MessageQueue,并在它们从消息队列出队时处理它们。

    Handler有两个作用:安排Message和runnables在将来某个点执行(延时执行);将一个action入队到自己所有的另一个线程进行执行(线程切换)。

    分发消息可以通过以下几个方法完成:

    1. post(Runnable),//Runnable
    2. postAtTime(Runnable, long),
    3. postDelayed(Runnable, long),
    4. sendEmptyMessage(int), //Message
    5. sendMessage(Message),
    6. sendMessageAtTime(Message, long),
    7. sendMessageDelayed(Message, long)

    post系列的方法用于enqueue runnables,setMessage系列的方法用来传递Message,Message可以通过Bundle传递数据,接收到Message后通过handleMessage方法进行处理。

    在传递Message和Runnable时,可以选择在MessageQueue准备好后马上执行或者延时一定时间或者在某个时间点进行执行,后两者可以用来实现timeouts,ticks以及其他基于时间的行为。

    应用的进程被创建后,主线程会维护一个消息队列用于管理顶层的应用对象(activities,broadcast receivers等)以及应用它们创建的所有窗口。可以创建自己的线程,通过Handler反过来和主线程进行沟通(post或者send),发送的Message和runnable对象在主线程的handler中进行调度,并在合适的时机进行处理。

  • Message

    Message包含向Handler发送的描述信息和任意的数据对象,主要包含两个整数字段和一个额外的对象字段(不需要强制类型转换)。

    在构造Message对象时,最好的方法是通过Message的obtain()方法或者Handler的obtainMessage()方法,两者的区别在于后者会自动设置Message的target为调用的Handler。

  • MessageQueue

    用于保存待Looper分发的message列表的底层类。Message不是直接添加到MessageQueue中的,而是通过与Looper关联的Handler进行添加。

    可以通过Looper#myQueue()方法获取当前线程的消息列表。

  • Looper

    用于进行线程的消息循环。线程默认没有关联的Looper,要创建Looper可以通过调用Looper.prepare()和Looper.loop()。不过主线程例外,系统会为主线程创建Looper,该过程在ActivityThread的main方法中进行。常见的和message loop交互的方式是通过Handler类。

    典型的Looper实现如下,通过Looper.prepare()和Looper.loop()初始化一个和Looper通信的Handler。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    class LooperThread extends Thread {
    public Handler mHandler;
    public void run() {
    Looper.prepare();
    mHandler = new Handler() {
    public void handleMessage(Message msg) {
    // process incoming messages here
    }
    };
    Looper.loop();
    }
    }

Message获取

  1. Message获取方式

    前面说了Message的获取主要有两种方式:通过Handler的obtainMessage()系列方法或者通过Message的obtain()系列方法。先来看看Handler的obtainMessage()系列方法:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    /**
    * Returns a new {@link android.os.Message Message} from the global message pool. More efficient than
    * creating and allocating new instances. The retrieved message has its handler set to this instance (Message.target == this).
    * If you don't want that facility, just call Message.obtain() instead.
    */
    public final Message obtainMessage()
    {
    return Message.obtain(this);
    }
    1
    2
    3
    4
    public final Message obtainMessage(int what)
    {
    return Message.obtain(this, what);
    }
    1
    2
    3
    4
    public final Message obtainMessage(int what, Object obj)
    {
    return Message.obtain(this, what, obj);
    }
    1
    2
    3
    4
    public final Message obtainMessage(int what, int arg1, int arg2)
    {
    return Message.obtain(this, what, arg1, arg2);
    }
    1
    2
    3
    4
    public final Message obtainMessage(int what, int arg1, int arg2, Object obj)
    {
    return Message.obtain(this, what, arg1, arg2, obj);
    }

    从注释上可知,其实Handler获取Message最终还是通过Message的相关方法,只不过除了从Message对象池获取Message外,还将本身设为了Message的target。下面来看下Message的相关方法。

    obtain

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    /**
    * Return a new Message instance from the global pool. Allows us to
    * avoid allocating new objects in many cases.
    */
    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();
    }

    上面这个方法是其他几个方法的基础,另外几个方法(上图中第2~6个重载方法)都是在该方法的基础上对得到的Message属性(即Message携带的数据)进行了赋值。比如下面的方法,除了获取Message对象外,还将该对象的target设为了参数handler。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    /**
    * Same as {@link #obtain()}, but sets the value for the <em>target</em> member on the Message returned.
    * @param h Handler to assign to the returned Message object's <em>target</em> member.
    * @return A Message object from the global pool.
    */
    public static Message obtain(Handler h) {
    Message m = obtain();
    m.target = h;

    return m;
    }

    而obtain(Message orig)生成新的Message并将orig的值复制到新的Message:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    /**
    * Same as {@link #obtain()}, but copies the values of an existing
    * message (including its target) into the new one.
    * @param orig Original message to copy.
    * @return A Message object from the global pool.
    */
    public static Message obtain(Message orig) {
    Message m = obtain();
    m.what = orig.what;
    m.arg1 = orig.arg1;
    m.arg2 = orig.arg2;
    m.obj = orig.obj;
    m.replyTo = orig.replyTo;
    m.sendingUid = orig.sendingUid;
    if (orig.data != null) {
    m.data = new Bundle(orig.data);
    }
    m.target = orig.target;
    m.callback = orig.callback;

    return m;
    }

    另外有一个较特殊的一个重载方法:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    /**
    * Same as {@link #obtain(Handler)}, but assigns a callback Runnable on
    * the Message that is returned.
    * @param h Handler to assign to the returned Message object's <em>target</em> member.
    * @param callback Runnable that will execute when the message is handled.
    * @return A Message object from the global pool.
    */
    public static Message obtain(Handler h, Runnable callback) {
    Message m = obtain();
    m.target = h;
    m.callback = callback;

    return m;
    }

    该方法除了Handler外还接收了一个Runnable参数,该对象在消息进行处理时会优先进行执行,详细的后面的消息处理部分会介绍。

  2. Message对象池的维护

    在上面看到Message对象池的时候一直有个疑问,Message对象池是怎么维护的?再来看一下Message#obtain()方法:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    /**
    * Return a new Message instance from the global pool. Allows us to
    * avoid allocating new objects in many cases.
    */
    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();
    }

    从上面的代码中可以看出来,Message采用了链表的结构,每次取对象时将链表头部的元素取出并将指针向前移动一位,同时清除返回对象的in-use标志。在sPool为空的情况下,也就是对象池中没有可用的对象是才会重新构造Message对象。Message的构造方法如下:

    1
    2
    3
    4
    /** Constructor (but the preferred way to get a Message is to call {@link #obtain() Message.obtain()}).
    */
    public Message() {
    }

    问题来了,开始的时候对象池为空,而且构造方法里什么也没做,那么构造的对象是怎么加入到对象池(链表)中的?查找一下引用sPool的地方:

    sPool

对sPool进行修改的地方有两处,其中一处在obtain()方法中,这个排除,还有一处是在recycleUnchecked()方法中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* Recycles a Message that may be in-use.
* Used internally by the MessageQueue and Looper when disposing of queued Messages.
*/
void recycleUnchecked() {
// Mark the message as in use while it remains in the recycled object pool.
// Clear out all other details.
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) {//MAX_POOL_SIZE = 50
next = sPool;
sPool = this;
sPoolSize++;
}
}
}

可以看到,如果对象池没满,则调用该方法的Message对象会被放到链表的头部。

再来看一下上面的FLAG_IN_USE是干嘛的:

1
2
3
4
5
6
7
8
9
/** If set message is in use.
* This flag is set when the message is enqueued and remains set while it
* is delivered and afterwards when it is recycled. The flag is only cleared
* when a new message is created or obtained since that is the only time that
* applications are allowed to modify the contents of the message.
*
* It is an error to attempt to enqueue or recycle a message that is already in use.
*/
/*package*/ static final int FLAG_IN_USE = 1 << 0;

从注释来看,在Message被enqueue后该标志就会一直存在,直到新的Messge被创建或者Message重新被obtain,因为只有在此时(消息发出去之前)才允许修改Message内容。

总结一下这一部分。Message用在在不同线程之间发送消息,是Handler和Looper沟通的媒介,消息内容可以是简单的int类型,也可以时Object类型,也可以是复杂的Bundle类型。Message获取有两种方式:通过Handler或者通过Message。通过Handler获取Message会将自身设为Message的target,发送消息时采用Message的sendToTarget()方法即可;通过Message获取的对象根据参数的不同可以采用sendTotarget()或者Handler的sendMessage()方法进行发送。

消息发送过程

上面提到过,消息的发送也有两种方式,通过Message#sendTotarget()或者通过Handler的sendMessage()系列方法。Message#sendTotarget()代码如下:

1
2
3
4
5
6
7
/**
* Sends this Message to the Handler specified by {@link #getTarget}.
* Throws a null pointer exception if this field has not been set.
*/
public void sendToTarget() {
target.sendMessage(this);
}

其实就是调用Handler的sendMessage(Message msg)方法。

Handler发送消息的方法有以下几种重载方式:

几个sendEmptyMessage……的方法其实在方法内部通过obtain方法获取了Message对象,然后设置该对象的what值,最后调用对应的sendMessage……方法。而sendMessage()、sendMessageDelayed()最终都是调用的sendMessageAtTime()方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* 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);
}

从注释可知,放入消息队列中的Message是按照传递的uptimeMillis进行排列的,sendMessageAtTime()传递的是发送消息时的时间加上延时的时间(不包括休眠时间),而另一个方法sendMessageAtFrontOfQueue()与之类似,不过传递的绝对时间为0,这回导致该消息被放置到消息队列的最前面。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* Enqueue a message at the front of the message queue, to be processed on
* the next iteration of the message loop. You will receive it in
* {@link #handleMessage}, in the thread attached to this handler.
* <b>This method is only for use in very special circumstances -- it
* can easily starve the message queue, cause ordering problems, or have
* other unexpected side-effects.</b>
*
* @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.
*/
public final boolean sendMessageAtFrontOfQueue(Message msg) {
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, 0);
}

代码里提到该方法只有在特殊情况下才能使用,否则容易产生负面影响,具体用法尚不明确(用来插队的?)。

消息入队

消息发送后最终都会通过Handler#enqueueMessage()方法将消息进行入队,该方法实现如下:

1
2
3
4
5
6
7
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}

可以看到,通过哪种方式获取Message对象,最终都会设置该Message的target。消息的异步与否先不去管,继续往下追代码,之后就进入到了MessageQueue的enqueueMessage()方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {//obtain message的时候已经清除了in-use的标志
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();//添加in-use标志
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();//什么时候p.target会为null?
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {//前面有异步消息的话不需要wake
needWake = false;
}
}
msg.next = p; // invariant: p == prev.next
prev.next = msg;//插入队列
}

// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {//native代码先不去了解
nativeWake(mPtr);
}
}
return true;
}

从上面可以看到,如果队列为空传递过来的时间为0或者小于队列中第一个消息的时间,则将该消息放到队列最前面,否则按照时间顺序放到合适的位置。

消息循环处理

上面已经大致介绍过,用来进行消息循环的类是Looper,线程默认是没有关联Looper的,典型的创建Looper上面已经提过了:

1
2
3
4
5
6
7
8
9
10
11
12
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}

下面就来了解下,这样创建的Looper是怎么和线程绑定起来的,Handler又是怎么和Looper关联起来的以及Looper是怎么取到并处理MessageQueue中的消息的。首先来看下Looper#prepare()方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 /** Initialize the current thread as a looper.
* This gives you a chance to create handlers that then reference
* this looper, before actually starting the loop. Be sure to call
* {@link #loop()} after calling this method, and end it by calling
* {@link #quit()}.
*/
public static void prepare() {
prepare(true);
}

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));
}

该方法首先会判断sThreadLocal.get() 是否为null,如不是则抛出异常,从异常内容可以看到每个线程只能创建一个Looper,而且可以推测,Looper的关键在sThreadLocal这个变量。来看下该变量的定义:

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

ThreadLocal是线程局部变量的意思,用来存储和线程相关的变量,是一种实现多线程并发的方式。ThreadLocal中有一个静态内部类ThreadLocalMap,里面存储以ThreadLocal为键,以泛型为值的线程局部变量。Thread内部有一ThreadLocalMap的成员变量,而这个map是在ThreadLocal中维护的,借此Thread和ThreadLocal就发生了关联。

再来看看ThreadLocal#get()方法的内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* Returns the value in the current thread's copy of this
* thread-local variable. If the variable has no value for the
* current thread, it is first initialized to the value returned
* by an invocation of the {@link #initialValue} method.
*
* @return the current thread's value of this thread-local
*/
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}

创建Looper之前map为空,所以执行到setInitialValue():

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* Variant of set() to establish initialValue. Used instead
* of set() in case user has overridden the set() method.
*
* @return the initial value
*/
private T setInitialValue() {
T value = initialValue();
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
}

其中initialValue()得到的结果为null,在该方法会通过createMap(t, null)创建map,并将该ThreadLocal和null关联:

1
2
3
4
5
6
7
8
9
10
/**
* Create the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @param firstValue value for the initial entry of the map
*/
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}

从上面可以看出prepare()方法中的get()返回值应为null,之后执行set()方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* Sets the current thread's copy of this thread-local variable
* to the specified value. Most subclasses will have no need to
* override this method, relying solely on the {@link #initialValue}
* method to set the values of thread-locals.
*
* @param value the value to be stored in the current thread's copy of
* this thread-local.
*/
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}

这里的map已经不为null了,所以执行map.set(this, value);在该方法中会将ThreadLoacal关联的值更新为new Looper(quitAllowed),这里只关心Looper相关内容,ThreadLocal详细内容之后再做了解(可以参考这篇文章http://www.iteye.com/topic/103804)。来看下Looper的构造过程:

1
2
3
4
private Looper(boolean quitAllowed/*true*/) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}

在Looper的构造方法中初始化了消息队列,而且可以看到Looper中也包含所在线程的引用。到这里Looper的创建就算完成了。

接下来就是Handler的创建了。现在有个疑问,Looper是在Looper.prepare()中创建的,并不是类的成员变量,H那么Handler是怎么和Looper关联起来的?来看下Handler的构造过程:

1
2
3
4
5
6
7
8
9
10
/**
* Default constructor associates this handler with the {@link Looper} for the
* current thread.
*
* If this thread does not have a looper, this handler won't be able to receive messages
* so an exception is thrown.
*/
public Handler() {
this(null, false);
}

从注释可以了解到,没有Looper的线程创建Handler会抛出异常。继续往下追:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Use the {@link Looper} for the current thread with the specified callback interface
* and set whether the handler should be asynchronous.
*
* Handlers are synchronous by default unless this constructor is used to make
* one that is strictly asynchronous.
*
* Asynchronous messages represent interrupts or events that do not require global ordering
* with respect to synchronous messages. Asynchronous messages are not subject to
* the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
*
* @param callback The callback interface in which to handle messages, or null.
* @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
* each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
*
* @hide
*/
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 that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}

Handler泄露的代码暂不关心。 mLooper = Looper.myLooper();获取了当前线程的Looper:

1
2
3
4
5
6
7
/**
* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
*/
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}

mQueue = mLooper.mQueue;说明Handler中的mQueue和Looper中的mQueue对应的是同一个MessageQueue对象。到这里Looper、Handler、MessageQueue都已准备完成,前面也对消息入队的过程做了介绍,下面就可以开始进行消息的loop了,该过程通过Looper.loop()进行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 /**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
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) {//表明线程正在退出
// No message indicates that the message queue is quitting.
return;
}
//省略代码
try {
msg.target.dispatchMessage(msg);
//省略代码
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
//省略代码
msg.recycleUnchecked();
}
}

该方法里建立了一个死循环来不断的获取消息,代码里的关键有三个地方:

  • Message msg = queue.next();用来取消息
  • msg.target.dispatchMessage(msg);用来分发消息
  • msg.recycleUnchecked();用来回收消息

先来看看queue.next()的实现 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
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();
}

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;
}

// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}

// If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
}

if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}

// Run the idle handlers.
// We only ever reach this code block during the first iteration.
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler

boolean keep = false;
try {
//idler类型根据addIdleHandler添加的数据类型而定
//可以在没有消息的时候处理些其他的事情,比如GC等(ActivityThread.GcIdler)
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}

if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}

// Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0;

// 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;
}
}

先看下Binder.flushPendingCommands()的注释:

1
2
3
4
5
6
7
8
9
10
11
/**
* Flush any Binder commands pending in the current thread to the kernel
* driver. This can be
* useful to call before performing an operation that may block for a long
* time, to ensure that any pending object references have been released
* in order to prevent the process from holding on to objects longer than
* it needs to.
* @apiSince 1
*/

public static final native void flushPendingCommands();

也就是说把当前线程等待的Binder命令都送到Binder driver,以免被阻塞太长时间,具体的实现就先不关心了,这里只看和消息处理相关的内容。

现在的Android版本存在Java和Native两个消息队列。在next()方法中,首先通过nativePollOnce(ptr, nextPollTimeoutMillis);处理native层的messagequeue,其中ptr代表的就是native的Messagequeue,如果没什么要处理的就从java Messagequeue中取消息,如果没有消息或者最前面的消息还没到处理时间,就会给nextPollTimeoutMillis设置一个非零值,然后下一次循环native层就可以多处理会儿,直到取到一个java的Messagenext()才会返回。Native层的处理推荐参考《深入理解Android 卷2》第2章中的内容。

在取Java Message时会创建一个死循环,根据now和msg和when字段判断是否取出首个消息,如果第一次循环时第一个消息的时间还没到,则处理IdleHandler,比如进行GC等操作。Binder.flushPendingCommands();尚不清楚是干嘛的,以后再做了解。next()直到取到消息才会返回,除非线程正在退出,此时返回null。

回到Looper的死循环中,消息取出后开始进行消息得分发:msg.target.dispatchMessage(msg); 。很明显,该方法位于Handler中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* 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);
}
}

调用顺序为msg.callback.handleCallback -> handler.mCallback.handleMessage -> handlet.handleMessage,其实效果都是一样的,这里只看Handler#handleMessage()方法:

1
2
3
4
5
/**
* Subclasses must implement this to receive messages.
*/
public void handleMessage(Message msg) {
}

该方法的实现为空,需要在子类或者匿名内中进行重写。比如:

1
2
3
4
5
6
7
8
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
//省略代码
}
}
};

到目前为止,消息已经得到了处理,整个流程差不多也结束了,之后就是些收尾的工作了。前面在介绍消息池的时候提到过,在消息得到处理后会进行回收,也就是Looper.loop()中的msg.recycleUnchecked();,该方法在前面介绍消息池的时候已经提过了,就不再提了。

总结

Looper线程中创建和线程相关的Handler及MessageQueue,Handler在其他线程中发送消息,入队到Looper线程的MessageQueue中,同时Looper不断的从MessageQueue中去取消息,再交还给对应的Handler进行处理。

上面是消息处理的大致流程,之后会了解下Android应用启动的流程,顺便了解下MainThread的消息种类和处理流程。

Powered by Hexo and Hexo-theme-hiker

Copyright © 2018 - 2022 得一 All Rights Reserved.

访客数 : | 访问量 :