Android消息机制
从开发的角度来说,Handler是Android消息机制的上层接口,这使得在开发过程中只需要和Handler交互,我们通过它可以将一个任务很轻松的切换到Handler所在的线程中去执行。
Android的消息机制主要是指Handler的运行机制,Handler的运行需要底层的MessageQueue和Looper支持。
MessageQueue是消息队列,它内部存储了一组消息,以队列的形式提供对消息的插入和删除,它是采用单链表的数据结构来存储消息列表的。
Looper是消息循环,它会以无限循环的形式去查是否有新消息,如果有就处理消息,没有就继续等待。
Lopper中还有一个值得注意的东西,那就是ThreadLocal
public final class Looper {
private static final String TAG = "Looper";
// sThreadLocal.get() will return null unless you've called prepare().
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
private static Looper sMainLooper; // guarded by Looper.class
final MessageQueue mQueue;
final Thread mThread;
private Printer mLogging;
... ...
}
public class ThreadLocal<T>
我们可以看到TreadLocal并不是线程,但是它的名字里面有Thread,那么肯定和线程是有关系的,它的作用是可以在每个线程中存储数据,ThreadLocal可以在不同的线程中互不干扰的存储并提供数据,还可以获取每个线程的Looper。
我们知道创建Handler的时候,需要使用当前线程的Looper来构造消息循环系统,那么Handler又是怎么获取到当前线程的Looper的呢,就是通过ThreadLocal
public static Looper myLooper() {
return sThreadLocal.get();
}
线程默认是没有Looper的,如果需要使用Handler就必须为线程创建Looper。我们说的主线程其实就是ActivityThread,ActivityThread被创建的时候就会初始化Looper,所以在主线程中默认可以使用Handler。
Handler的主要作用是将一个任务切换到某个指定的线程中去执行。
首先,我们先分析一下在我们的主线程中Handler,Looper,MessageQueue是怎么协同工作的?
我们知道ActivityThead是程序的入口,在那里会进行Looper 的初始化:
public static void main(String[] args) {
//代码省略
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
执行ActivityThread.main方法后,应用程序就启动起来了,并且会一直从消息队列中取消息,然后处理消息,那么系统是如何将消息投递到消息队列中的呢,又是如何从消息队列中获取消息并处理消息呢?就是用Handler。
Handler最常用的post方法,将一个消息post到它所在的线程,并在handlerMessage方法中处理它。
那么Handler是如何关联消息队列以及线程的呢?
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;
}
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
通过查源码可知,Handler的创建,最后调用的构造函数就是上面两种。对于在UI线程中,我们使用第一种就可以。
我们可以看到,如果没有传进一个Looper,也就是调用了第一种构造方法,那么会使用Looper.myLooper()来获取Looper对象:
public static Looper myLooper() {
return sThreadLocal.get();
}
通过上面分析,我们知道程序启动的时候会调用prepareMainLooper:
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));
}
public static Looper myLooper() {
return sThreadLocal.get();
}
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
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();
}
/**
* 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;
}
从上面的代码中我们可以看到,在调用prepareMainLooper时,会先调用prepare方法,在prepare方法中创建了Looper并将该对象设置给了sThreadLocal,这样队列就与线程关联上了,这样一来,不同的线程就不能访问其他的消息队列。
再回到Handler中来,消息队列通过Looper与线程关联上,而Handler又与Looper,因此,Handler最终就和线程,线程的消息队列关联上了。
那么创建Looper之后,又是怎么执行消息循环的呢?Handler post消息给消息队列,消息又是如何处理的呢?
我们可以看到在mian方法中,Looper初始化后,调用了Looper.loop()方法:
/**
* 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();
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
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
final long end;
try {
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (slowDispatchThresholdMs > 0) {
final long time = end - start;
if (time > slowDispatchThresholdMs) {
Slog.w(TAG, "Dispatch took " + time + "ms on "
+ Thread.currentThread().getName() + ", h=" +
msg.target + " cb=" + msg.callback + " msg=" + msg.what);
}
}
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();
}
}
通过上面代码,我们可以到在loop方法中得到当前线程的Looper和MessageQueue,然后开启了一个死循环,通过从消息队列中逐个取出消息,通过msg.target.dispatchMessage(msg);
来处理消息。
public final class Message implements Parcelable {
/*package*/ Bundle data;
/*package*/ Handler target;
/*package*/ Runnable callback;
// sometimes we store linked lists of these things
/*package*/ Message next;
}
我们可以看到,target就是Handler,所以是调用了Handler的dispatchMessage(msg),于是这样消息队列将消息投递给了Handler
public interface Callback {
public boolean handleMessage(Message msg);
}
public void handleMessage(Message msg) {
}
//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);
}
}
我们看到在dispatchMessage方法中,如果Runnable类型的callback为空,就执行handlerMessage来处理消息,否则就执行handlerCallback来处理,该方法会调用callback的run方法。其实这就是对应的两种Handler的分发类型:如若post(Runnable callback)则callback就不为空,如果使用sendMessage方法时,一般不会设置callback,所以callback就会空了。
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();//获取一个Message对象
m.callback = r;
return m;
}
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
这两种消息投递方法,最终都会调用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);
}
我们分析可知,在post(Runnable)时,会将Runnable包装成Message对象,并且将Runnable对象设置给Message对象的callback字段。然后最终会调用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);
}
最终调用了MessageQueue的enqueueMesasge方法,在这个方法中,最终将Message对象插入到MessageQueue中,也就是单链表的最后。
最后总结一下Hanlder消息机制的过程: