Looper、Handler、Message 源码分析

2016/8/20 posted in  Android

Looper

文档这么介绍这个类的

  • Class used to run a message loop for a thread. Threads by default do
    • not have a message loop associated with them; to create one, call
    • {@link #prepare} in the thread that is to run the loop, and then
    • {@link #loop} to have it process messages until the loop is stopped.

通常在线程中是这样使用

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();
      }

首先调用了 Looper.prepare() 接着调用了Looper.loop();,具体来看看这两个函数

继续看看 Lopper 中的主要成员变量

 // sThreadLocal.get() will return null unless you've called prepare().
 //在prepare 的时候 set 的值
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
    private static Looper sMainLooper;  // guarded by Looper.class
//消息队列
    final MessageQueue mQueue;
    final Thread mThread;

而ThreadLocal类为每一个线程都维护了自己独有的变量拷贝。每个线程都拥有了自己独立的一个变量,竞争条件被彻底消除了,那就没有任何必要对这些线程进行同步,它们也能最大限度的由CPU调度,并发执行。并且由于每个线程在访问该变量时,读取和修改的,都是自己独有的那一份变量拷贝,变量被彻底封闭在每个访问的线程中,并发错误出现的可能也完全消除了。对比前一种方案,这是一种以空间来换取线程安全性的策略。
具体 可参看这里

prepare()

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));
}

prepare 比较简单,只是初始化了 sThreadLocal的值。一个 Looper 只能有一个 ThreadLoacl 对象,当sThreadLocal.get() != null抛出异常

ThreadLocal对象保证每个线程中的 Looper 实例互不相同
** 一句话概括 prepare(),对于每个 thread 准备一个 Looper 变量,并保证每个Looper在每个线程中独一无二**

loop()

public static void loop() {
    //这里得到的 Looper,就是prepare 中 set 的,一个线程对应一个 Looper
        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();

    //循环从 MessageQueue 取出消息执行,MessageQueue在 Looper 的构造函数中被创建
        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);
            }

        //MessageQueue中 取出的 msg,交给target.dispatchMessage 处理
            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();
        }
    }

mylooper()

    public static Looper myLooper() {
        return sThreadLocal.get();
    }

直接返回ThreadLocal中存储的 Looper 变量。
然后取出 looper 中的 Queue,并且循环取出队列中的 message,交给msg.target.dispatchMessage(msg);处理

target 是 handler 后面会讲到

public void dispatchMessage(Message msg) {  
        if (msg.callback != null) {  
        //post 的回调
            handleCallback(msg);  
        } else {  
            if (mCallback != null) {  
                if (mCallback.handleMessage(msg)) {  
                    return;  
                }  
            }  
            handleMessage(msg);  
        }  
    } 

handleMessage(msg)是一个空方法,我们在创建 handler 实例时,复写这个方法。然后根据msg.what进行消息处理

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());
            }
        }

    //通过Looper.myLooper()获取了当前线程保存的Looper实例,        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        // 获取了这个Looper实例中保存的MessageQueue(消息队列),这样就保证了handler的实例与我们Looper实例中MessageQueue关联上了。
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

同样,通过Looper.myLooper()获取当前线程中的 Looper 对象,并且得到其中的 Queue

所有 sendMessagesendMessageDelayedsendEmptyMessageDelayed等,最终都调用

     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) {
        //Looper的loop方法会取出每个msg然后交给msg,target.dispatchMessage(msg)去处理消息
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
    

最终会将msg 加入到 queue 的队列中

MessageQueue

boolean enqueueMessage(Message msg, long when) {
        if (msg.isInUse()) {
            throw new AndroidRuntimeException(msg + " This message is already in use.");
        }
        if (msg.target == null) {
            throw new AndroidRuntimeException("Message must have a target.");
        }

        synchronized (this) {
            if (mQuitting) {
                RuntimeException e = new RuntimeException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w("MessageQueue", e.getMessage(), e);
                return false;
            }

            msg.when = when;
            Message p = mMessages;
            boolean needWake;
            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;
    }

Handler post

eg

mHandler.post(new Runnable()  
        {  
            @Override  
            public void run()  
            {  
                //do something 在 handler 线程
            }  
        }); 
public final boolean post(Runnable r)  
   {  
      return  sendMessageDelayed(getPostMessage(r), 0);  
   }  
   
   
    private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }

在getPostMessage中,得到了一个Message对象,然后将我们创建的Runable对象作为callback属性,赋值给了此message.

产生一个Message对象,可以new ,也可以使用Message.obtain()方法;两者都可以,但是更建议使用obtain方法,因为Message内部维护了一个Message池用于Message的复用,避免使用new 重新分配内存。

最终还是会调用enqueueMessage

在 dispathMessage 的过程中

public void dispatchMessage(Message msg) {  
       if (msg.callback != null) {  
           handleCallback(msg);  
       } else {  
           if (mCallback != null) {  
               if (mCallback.handleMessage(msg)) {  
                   return;  
               }  
           }  
           handleMessage(msg);  
       }  
   }  

getPostMessage中,将post 中的Runnable赋值给了Message.callback
所以,会执行handleCallback(msg)

private static void handleCallback(Message message) {
        message.callback.run();
    }

即执行 Post 中的Runnable

其实这个Runnable并没有创建什么线程,而是发送了一条消息

总结

到此,这个流程已经解释完毕,让我们首先总结一下

  1. 首先Looper.prepare()在本线程中保存一个Looper实例,然后该实例中保存一个MessageQueue对象;因为Looper.prepare()在一个线程中只能调用一次,所以MessageQueue在一个线程中只会存在一个。
  2. Looper.loop()会让当前线程进入一个无限循环,不端从MessageQueue的实例中读取消息,然后回调msg.target.dispatchMessage(msg)方法。
  3. Handler的构造方法,会首先得到当前线程中保存的Looper实例,进而与Looper实例中的MessageQueue想关联。
  4. Handler的sendMessage方法,会给msg的target赋值为handler自身,然后加入MessageQueue中。
  5. 在构造Handler实例时,我们会重写handleMessage方法,也就是msg.target.dispatchMessage(msg)最终调用的方法。
  6. Activity的启动代码中,已经在当前UI线程调用了Looper.prepare()和Looper.loop()方法。

参考

http://blog.csdn.net/lmj623565791/article/details/38377229