Message分析:
定义一个message包含一个描述和任意发送到Handler的数据对象,这个对象包含两个额外的int型数据和一个Object型数据,此Object类型的数据在大多数情况下是不能被重新配置的。
虽然Message的构造方法是public修饰的,但是构造一个Message最好的办法是调用Message.obtain()或者Handler.obtainMessage(),因为这两种方式是从Message的回收池中取一个Message。
Message实现了Parcelable接口,可以实现进程间通信。
public int what:使用者定义Message code是为了接收者可以鉴别是哪种消息,每一个Handler都有自己独立的Message code命名区间,所以你不必担心会影响到其他的handler。
public int arg1,arg2:是最低耗的办法来替代setData()方法,如果你只需要存储int型数据的话。
public Object obj:可以发送任意一个对象给接收者,当使用Messenger在进程间传递Message时这个对象必须不为空,且实现了Parcelable接口,传输其他形式的参数时使用
setData()即可。
public Messenger replyTo;这是回复Message的Messenger,它的具体使用要根据接收者和发送者而定
public int sendingUid = -1:可选字段,指示发送Message的uid,只有当使用Messenger发送时才有效,在其他情况下它的值一直是-1;
private static final Object sPoolSync:Message的同步锁。
private static Message sPool;Message消息池,最大容量为50
Message中还包含了一些其他字段:int falgs;Bundle data;Handler target;Runnable callback等。
Message中主要的方法:
obtain方法:从消息池中返回一个message实例,这种方式获取message对象有效避免了创建过多的Message对象。(其他带参的obtain方法都是调用无参的obtain方法得到message,然后在把参数添加到得到的message中。)
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();
}
recycle方法:消息回收,与obtain相反,它是往消息池中增加一个消息实例,并清空此实例的内容。
public void recycle() {
if (isInUse()) {
if (gCheckRecycle) {
throw new IllegalStateException("This message cannot be recycled because it "
+ "is still in use.");
}
return;
}
recycleUnchecked();
}
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) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
这两个是Message中起主要作用发方法,还有其他系列的get和set方法,以及copyFrom(Message o)都比较容易理解,就不赘述了。
MessageQueue分析:
MessageQueue虽然名叫消息队列,其实是用一个单链表来存储消息列表。在MessageQueue中,主要有两个操作:插入消息,对应的是enqueueMessage()方法;取出消息,对应的是next()方法。现在就来看这个方法。
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(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;
}
这个方法发思路比较简单,就是往Message的单链表中插入一条消息。
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 {
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;
}
}
可以看出,next()方法是一个无限循环的方法,如果消息队列中没有消息,那么next()方法将一直阻塞。当有新消息到来的时候,next()方法会返回这条消息并将其从单链表中删除。
Looper分析:
Looper的作用是为一个线程运行一个消息循环,一个线程默认是没有Looper的,可以执行prepare()方法来为线程启动一个Looper,然后执行loop()方法来让Looper开始处理消息。
Looper这个类是用来设置和管理MessageQueue的轮询事件,它影响着基于MessageQueue或者handler的消息队列的状态,而不是作用于它自己。例如,idle handlers和sync barriers是在MessageQueue里面定义的,但是,线程的准备Looper,执行Looper和退出Looper是在Looper里面定义的。
构造方法:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
实例化一个MessageQueue,并且得到当前线程,在后面会用到。
prepare()方法:初始化当前线程为一个looper线程,调用prepare()方法之后你可以创建一个handler来引用这个Looper。看下具体的实现:
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中添加一个Looper。要看懂这里,要了解一下ThreadLocal的原理:ThreadLocal是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,对于其他线程来说则无法获取到数据,在创建ThreadLocal的时候会获取当前线程,并绑定。了解了这些,就应该看懂prepare()方法的作用了,就是给当前线程添加一个Looper。
prepareMainLooper()方法:初始化一个线程为Looper线程,并且把它当做整个应用程序的主Looper,应用程序的主Looper是有安卓系统环境来创建的,所以作为开发者,是永远不会调用这个方法的。
getMainLooper()方法:得到应用程序的主Looper,这个方法只能在应用程序的主线程里面调用。
loop()方法:启动这个线程的消息队列,在调用quit()方法的时候这个消息队列的轮询才停止。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;
// Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
// This must be in a local variable, in case a UI event sets the logger
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
msg.target.dispatchMessage(msg);
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
// Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed from 0x"
+ Long.toHexString(ident) + " to 0x"
+ Long.toHexString(newIdent) + " while dispatching to "
+ msg.target.getClass().getName() + " "
+ msg.callback + " what=" + msg.what);
}
msg.recycleUnchecked();
}
}
这个方法里面有一个无限循环,循环里面调用了MessageQueue的next()方法,这个next()方法,next()也是一个无限循环,不停的轮询消息队列,一旦有消息,就立即返回给
handler来处理,然后移除这个消息。只有当MessageQueue的next()方法返回null的时候才会跳出循环,轮询才会结束。
到此,Android消息机制里面涉及的几大类已经分析完了,现在总结一下整个流程:首先Looper.prepare()来为线程绑定一个Looper(注:绑定Looper的同时会生成一个MessageQueue,用于轮询消息),然后再在这个线程里面创建一个Handler,这个Handler会绑定到这个Looper,然后Looper.loop()来启动轮询。当handler.sendMessage(msg)的时候,这个msg会被插入到MessageQueue的里面去,然后通过MessageQueue的next()方法取出消息,给Handler处理,然后移除消息。大致过程就是这样的,画图应该清晰一些,但是懒病犯了,就不画图了。