Android中消息传递模块差不多看了好几次,虽然每次看的方式都差不多但是还是发觉的到每次看了之后,理解的更清晰一点。
关于这个模块的文章数不胜数,但是最重要的还是自己动手理解一遍更好。
会牵扯到的几个类: Handler.java , Looper.java , MessageQueue.java , Message.java
源代码路径:
xxx/frameworks/base/core/java/android/os 看的过程中你会发现高版本和低版本系统代码有些地方比较大的差距。从中我们可以分析为什么要做这样的修改,这样的修改的优点。
先看看在Looper类的注释中的一段代码。
* <p>This is a typical example of the implementation of a Looper thread,
* using the separation of {@link #prepare} and {@link #loop} to create an
* initial Handler to communicate with the Looper.
*
* <pre>
* 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();
* }
* }</pre>
*/
Looper.java
这里Looper.prepare() ; 和 Looper.loop() ;这两个方法做了什么?
/** 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");
}
//如果是main线程,则不允许退出。
sThreadLocal.set(new Looper(quitAllowed));
}
当我们手动调用Looper.prepare()方法的时候,内部调用prepare(boolean quitAllowd)方法,参数quitAllowd表示是否允许退出。
Android中刷新UI都在main线程中完成的,因此prepare(false)的时候是在启动main线程的时候会用到。我们可以看到Looper中另外一个方法:
/**
* Initialize the current thread as a looper, marking it as an
* application's main looper. The main looper for your application
* is created by the Android environment, so you should never need
* to call this function yourself. See also: {@link #prepare()}
*/
//查询该方法有两个位置用到。一是在SystemServer中,另外一个是在ActivityThread中。
//vi services/java/com/android/server/SystemServer.java +97
//vi core/java/android/app/ActivityThread.java +4985
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
Looper.prepare()方法中,完成了Looper的创建并将起存储至ThreadLocal变量中。
从上面代码中可以看到:
sThreadLocal.set(new Looper(quitAllowed));
因此下面我们跟踪一下Looper的构造方法、
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
构造方法中看到创建了MessageQueue和得到当前线程的Thread对象。这里的MessageQueue是后面消息循环以及消息的传递重要的部分。
因此,从这里我们可以看出,Looper中持有:MessageQueue,currentThread,ThreadLocal。
接下来看下,Looper.loop()方法。注:方法中部分打印Log相关的代码此处已经删除。
Android Source Code 4.4
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static void loop() {
//获取当前looper
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
//Looper中持有消息队列。获取当前Looper的消息队列
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();
//无限循环
for (;;) {
//取出消息
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
//++++++++++++++++++++这一句是重点,获取到消息后会回调到Handler方法中的handleMessage()方法中。
//在低版本的系统代码中,会判断msg.target==null,这里去掉了。
msg.target.dispatchMessage(msg);
//回收当前消息对象所占内存
msg.recycle();
}
}
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static final void loop() {
Looper me = myLooper();
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();
while (true) {
Message msg = queue.next(); // might block
//if (!me.mRun) {
// break;
//}
if (msg != null) {
if (msg.target == null) {
// No target is a magic identifier for the quit message.
return;
}
msg.recycle();
}
}
}
从上面的对比可以看出4.4的代码明显比2.3的代码变化。
1.while(true){...}循环修改为for(,,){...} 貌似这里没啥区别
2.Looper me = myLooper();获取到当前looper,4.4加了非空判断。因为在调用了Looper.prepare()后才会有Looper产生。可以看上面的分析。
3.去掉了message中target判断空的if语句。
分析为何这里去掉。
先看当我们调用Handler的handler.obtainMessage() ;
------->in Handler.java
/**
* 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);
}
此时Handler会去调用Message的obtain方法,该方法将this作为参数传递进去,也就是将当前的Handler对象引用传递进去。
----->in Message.java
/**
* Same as {@link #obtain()}, but sets the values of the <em>target</em>, <em>what</em>,
* <em>arg1</em>, <em>arg2</em>, and <em>obj</em> members.
*
* @param h The <em>target</em> value to set.
* @param what The <em>what</em> value to set.
* @param arg1 The <em>arg1</em> value to set.
* @param arg2 The <em>arg2</em> value to set.
* @param obj The <em>obj</em> value to set.
* @return A Message object from the global pool.
*/
public static Message obtain(Handler h, int what,
int arg1, int arg2, Object obj) {
Message m = obtain();
m.target = h;
m.what = what;
m.arg1 = arg1;
m.arg2 = arg2;
m.obj = obj;
return m;
}
而且再看看当msg被添加到队列的时候调用的方法
boolean enqueueMessage(Message msg,long when)其中首先就是判断将被添加的target是否为null,否则跑出nullPointerException。
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
} ......
因此msg.target不可能为空,也就没有判断的必要。
4.将可能的情况都先放到前面过滤,减少了if语句的嵌套。是代码更加清晰明了。
刚好手上也有5.0的代码,干脆也贴上来看下。
/**
* 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;
// 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();
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
msg.target.dispatchMessage(msg);
msg.recycleUnchecked();
}
}
对比可以发现5.0的和4.4的差不多只是msg的回收方法变了。编程recycleUnchecked()。
因此这里需要对比4.4的Message和5.0的Message。这里简单看下不同点。
-------->5.0 Message.java 添加了当前msg是否正在使用的校验。当然,这里添加了,说明很多地方也会相应的增加判断校验,差别就出来了。
/**
* Return a Message instance to the global pool.
* <p>
* You MUST NOT touch the Message after calling this function because it has
* effectively been freed. It is an error to recycle a message that is currently
* enqueued or that is in the process of being delivered to a Handler.
* </p>
*/
public void recycle() {
if (isInUse()) {
if (gCheckRecycle) {
throw new IllegalStateException("This message cannot be recycled because it "
+ "is still in use.");
}
return;
}
recycleUnchecked();
}
Handler.java
平时我们在代码中是直接创建Handler的派生类或者创建匿名内部类。类似于这样
private static class MyHandler extends Handler{
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
}
}
或者
Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
}
} ;
————————————————————————————————————————————————————————
这里我们最先看看Handler的创建。构造方法中最终会调用到这个:
public Handler(Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
//这里判断派生出来的Handler子类是否为static,不产生致命危机,但是可能会导致内存泄露。
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());
}
}
//取出与该Handler相连接的Looper,该Looper与Thread相连接。
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
//在Handler里面也持有MessageQueue,这个MessageQueue和Looper的MessageQueue相同
//所以在Handler的其他处理方法中。removeMessages,hasMessages,enqueueMessage这些操作都相当于操作Looper中的MessageQueue
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
上面代码中,第一个if语句判断当前Handler是否为static,警示Handler最好为static这样可以防止内存泄露,至于为什么,这里就不讲了。 可以看到, mLooper = Looper.myLooper(); mQueue = mLooper.mQueue;与thread绑定的Looper对象的东西也分享给了Handler,这样MessageQueue,Message,Handler,Looper就连接起来了。Handler中移除msg,msg入队列等都是在Looper的MessageQueue中操作。
Message msg = handler.obtainMessage() ;
msg.what = 1 ;
msg.obj = "Hello World" ;
handler.sendMessage(msg) ;
这样就能在hangleMessage(Message msg)方法中接收到消息了。该消息是如何传递的?
先看sendMessage(msg)做了什么。
---------->code in Handler.java
/**
* Pushes a message onto the end of the message queue after all pending messages
* before the current time. It will be received 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.
*/
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);
}
先看下这个注释,返回true则表示msg成功添加进了queue中,false则表示该msg正在被执行或者looper异常退出了。
* @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)
------>最后
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
//将消息放入队列中去。
return queue.enqueueMessage(msg, uptimeMillis);
}
有个使用,我们将优先级搞得消息添加到队列头部
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);
}
注意它直接调用了enqueueMessage,第三个参数是0。因此我们从其他方法调用可以看到这里的第三个参数应该是和消息的先后有关系。
——————————————————————————————————————
这里先跟一下,sendMessageAtFrontOfQueue方法的流程。
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;
//sendMessageAtFrontOfQueue()--->enqueueMessage(queue, msg, 0); 则此处会走第一个分支。
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;
}
链表。。。。呵呵呵。。。。。看的有点绕。
——————————————————————————————————————
回到Looper.loop()方法中,可以看到这一句,msg.target.dispatchMessage(msg) ,将msg给msg.target去处理,而这个target就是发送消息的Handler自身
/**
* Handle system messages here.
*/
//在Looper.loop()方法中,msg会调用target的dispatchMessage方法。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
这里的几个判断我就不讲了。
MessageQueue.java
上面Looper.loop()方法中queue.next()
Message next() {
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
// We can assume mPtr != 0 because the loop is obviously still running.
// The looper will not call this method after the loop quits.
nativePollOnce(mPtr, 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 (false) Log.v("MessageQueue", "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("MessageQueue", "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;
}
}
这个方法我没理顺。估计理顺的话要牵扯到其他部分的逻辑。
这里就有个疑问,我用Handler发送了好几个msg,而且时间不一样,MessageQueue是如何做的处理呢? 应该和上面的next()方法有很大关系。这里就不研究了,先就到这里。
另外,Message.java实现了Parceable接口。比较java中的serializable接口。
public final class Message implements Parcelable
这里看看实现Parceable接口需要做的工作吧。
public static final Parcelable.Creator<Message> CREATOR
= new Parcelable.Creator<Message>() {
public Message createFromParcel(Parcel source) {
Message msg = Message.obtain();
msg.readFromParcel(source);
return msg;
}
public Message[] newArray(int size) {
return new Message[size];
}
};
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
if (callback != null) {
throw new RuntimeException(
"Can't marshal callbacks across processes.");
}
dest.writeInt(what);
dest.writeInt(arg1);
dest.writeInt(arg2);
if (obj != null) {
try {
Parcelable p = (Parcelable)obj;
dest.writeInt(1);
dest.writeParcelable(p, flags);
} catch (ClassCastException e) {
throw new RuntimeException(
"Can't marshal non-Parcelable objects across processes.");
}
} else {
dest.writeInt(0);
}
dest.writeLong(when);
dest.writeBundle(data);
Messenger.writeMessengerOrNullToParcel(replyTo, dest);
}
private final void readFromParcel(Parcel source) {
what = source.readInt();
arg1 = source.readInt();
arg2 = source.readInt();
if (source.readInt() != 0) {
obj = source.readParcelable(getClass().getClassLoader());
}
when = source.readLong();
data = source.readBundle();
replyTo = Messenger.readMessengerOrNullFromParcel(source);
}
对于这一块,文章中提到的都很基础,仅仅只是跟着流程走了一遍,还有很多没有提到,还需要继续研究。