
老司机们都知道,Android的线程间通信就靠Handler、Looper、Message、MessageQueue这四个麻瓜兄弟了,那么,他们是怎么运作的呢?下面做一个基于主要源代码的大学生水平的分析。 原文链接
Looper在 Looper 中,维持一个Thread对象以及MessageQueue,通过Looper的构造函数我们可以知道:
    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);//传入的参数代表这个Queue是否能够被退出
        mThread = Thread.currentThread();
    }
Looper在构造函数里干了两件事情:
- 将线程对象指向了创建Looper的线程
- 创建了一个新的MessageQueue
分析完构造函数之后,接下来我们主要分析两个方法:
- looper.loop()
- looper.prepare()
 public static void loop() {
        final Looper me = myLooper();//获得当前线程绑定的Looper
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MessageQueue queue = me.mQueue;//获得与Looper绑定的MessageQueue
        // 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();
        
        //进入死循环,不断地去取对象,分发对象到Handler中消费
        for (;;) {
            Message msg = queue.next(); // 不断的取下一个Message对象,在这里可能会造成堵塞。
            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);
            }
            
            //在这里,开始分发Message了
            //至于这个target是神马?什么时候被赋值的? 
            //我们一会分析Handler的时候就会讲到
            msg.target.dispatchMessage(msg);
            if (logging != null) {
                logging.println("            
            
                关注
                打赏
            
            
        
 
                 
    