Handler,Looper,HandlerThread浅析,handlerthreadlooper
Handler想必在大家写Android代码过程中已经运用得炉火纯青,特别是在做阻塞操作线程到UI线程的更新上.Handler用得恰当,能防止很多多线程异常.
而Looper大家也肯定有接触过,只不过写应用的代码一般不会直接用到Looper.但实际Handler处理Message的关键之处全都在于Looper.
以下是我看了<深入理解Android>的有关章节后,写的总结.
Handler
先来看看Handler的构造函数.
public Handler() {
        this(null, false);
    }
public Handler(Looper looper) {
        this(looper, null, false);
    }
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的2个成员变量mQueue,mLooper
mLooper可以从构造函数传入.如果构造函数不传的话,则直接取当前线程的Looper:mLooper = Looper.myLooper();
mQueue就是mLooper.mQueue.
把Message插入消息队列
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);
    }
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
上面两个正是把Message插入消息队列的方法.
从中能看出,Message是被插入到mQueue里面,实际是mLooper.mQueue.
每个Message.target = this,也就是target被设置成了当前的Handler实例.
到此,我们有必要看看Looper是做一些什么的了.
Looper
这是Looper一个标准的使用例子.
class LooperThread extends Thread {    
    public Handler mHandler;    
    public void run() {
        Looper.prepare();        
        ......
        Looper.loop();   
    }
}
我们再看看Looper.prepare()和Looper.loop()的实现.
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));
    }
public static Looper myLooper() {
        return sThreadLocal.get();
    }
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();
        }
    }
prepare()方法给sThreadLocal设置了一个Looper实例.
sThreadLocal是Thread Local Variables,线程本地变量.
每次调用myLooper()方法就能返回prepare()设置的Looper实例.
Looper()方法里面有一个很显眼的无限For循环,它就是用来不断的处理messageQueue中的Message的.
最终会调用message.target.dispatchMessage(msg)方法.前面

