Looper 源码解析

Looper 源码解析

MessageQueue 是存放Message的消息队列,只是一个容器,而Looper 则是让MessageQueue循环动起来。

默认下创建一个线程,线程里面是没有消息队列的,如果想用消息队列MessageQueue,就需要通过Looper进行绑定。下面是一个简单的例子:

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

可以看见Thread通过Looper.prepare() 和 Looper.loop()两个静态方法运行。

从源码里看 Looper的构造函数是private,则说明Looper不能再外部实例化。就可以猜测到Looper和Thread是一一对应的。

    private Looper(boolean quitAllowed) {
        //实例化MessageQueue。
        mQueue = new MessageQueue(quitAllowed);
        //获取当前线程。
        mThread = Thread.currentThread();
    }

看一下Looper.prepare()方法:

  /** Initialize the current thread as a looper.
      * This gives you a chance to create handlers that then reference
      * this looper, before actually starting the loop. Be sure to call
      * {@link #loop()} after calling this method, and end it by calling
      * {@link #quit()}.
      */
    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));
    }

在Looper.prepare() 时候将Looper存起来,存在一个叫ThreadLocal<Looper> 里面。获取的时候也是通过sThreadLocal.get() 来获取。上面提过Message和Thread是一一对应的,也就是说一个线程只能拥有一个Looper,所以在prepare时候先通过sThreadLocal.get()来获取Looper,如果是线程刚进来那是没有Looper的所以返回的是null,接着把改Looper存起来。如果有存在则抛出"Only one Looper may be created per thread".

// sThreadLocal.get() will return null unless you've called prepare().
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

Looper.prepare()调用完之后Looper就准备好了,接着就可以通过Looper.loop() 让MessageQueue循环动起来。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.");
        }

        //获取当前线程的MessageQueue。
        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 (;;) {
            //获取MessageQuene消息队列的消息.
            Message msg = queue.next(); // might block

            //如果消息队列没有消息,则return,即阻塞在这里,等待获取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);
            }

            // msg.target 是一个Handler,这个意思是让改Message关联的Handler通过dispatchMessage()处理Message。
            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();
        }
    }
  • final Looper me = myLooper() : 获取当前的Looper myLopper() 返回的是sThreadLocal.get()。
  • final MessageQueue queue = me.mQueue: 获取当前线程的MessageQueue。
  • for(,,): 这个是死循环,不停地进行循环。
  • Message msg = queue.next(): 获取MessageQuene消息队列的消息. 如果消息队列没有消息,则阻塞在这里,直到MessageQueue有Message。
  • msg.target.dispatchMessage(msg); msg.target 其实是一个Handler。这个意思是让改Message关联的Handler通过dispatchMessage()处理Message。
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容