一、概述
Android的消息机制主要是指handler的运行机制,它需要与Looper和MessageQueue配合。Handler是message的发送者和处理者,多用于更新UI。MessageQueue是负责存放message的单向链表。Looper负责开启一个MessageQueue,并循环遍历其中的消息。
二、实例分析
Handler handler = new Handler( );
在主线程中此代码没有问题,但是如果运行在子线程,就会报错:Can’t create handler inside thread that has not called Looper.prepare(),我们看下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;
}
这里我们找到原因了,因为Looper为空,需要创建自己线程的Looper:
Looper.prepare();
Handler handler = new Handler();
Looper.loop();
prepare的源码如下:
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));
}
prepare为这个线程new 了一个Looper,之后还需要让Looper去遍历消息队列, 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.recycle();
}
}
for循环取queue.next()中数据,如果没有数据,就阻塞,直到next()为空。这样有人会问,为什么在主线程中不需要创建Looper。这是因为在主线程中默认已创建了一个Looper用于处理主线程的消息循环。每个线程都有自己的Looper,我们来看一下Looper的创建:
static final ThreadLocat<Looper> sThreadLocal = new ThreadLocal<Looper>();
ThreadLocal是一个线程内部的数据存储类,所有线程访问一个对象,但是每个线程都有自己的一份数据,这就是它的奇妙之处。我们看一下ThreadLocal的get方法:
public void set(T value){
Thread currentThread = Thread.currentThread();
Values values = Values(currentThread);
if(values == null){
values = initializeValues(currentThread);
}
values.put(this, values);
}
可以看到ThreadLocal通过内部的成员,设置自己的值,每个线程都会存一份副本,这样可以很好的解决线程并发的问题,而且比synchronized有更好的并发量。ThreadLoacl请查看博客:
http://blog.csdn.net/lufeng20/article/details/24314381
三、总结
Looper提供了quit和quitSafely两种方法来退出,quit会直接退出,quitSafely会把消息队列中数据执行完毕才会退出。自己退出Looper是个好习惯,防止线程一直处于等待状态。
如果在子线程用handler,可以使用HandlerThread,已经创建好了Looper和消息队列,不用自己手写。而且避免了多次创建Thread线程导致的性能问题,关于HandlerThread请查看博客:
http://blog.csdn.net/feiduclear_up/article/details/46840523