android Looper Message 代码分析

今天遇到一件事情,很不开心,于是决定分析一下Looper的实现。

Looper 代码其实不多,只是用到了一些外部不能使用的类,然而代码难度也不是很大。下面且听我细细分析。

重点关注一下我们会使用的方法,比如Looper.prepare(); Looper.loop();

好的,先看一个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));
    }

可以看到实际上是调用了一个私有方法,那就看这个私有方法吧。这个私有方法做了什么?

首先是判断sThreadLocal里面是不是已经有Looper对象了,没有就创建并存储到该对象中;有就抛异常,简单粗暴。

关于ThreadLocal,可以看一下 Java并发编程:深入剖析ThreadLocal 这里的分析。

我大致说一下,就是说一个线程中通过 sThreadLocal来保存的Looper最多只有一个。辣么,这个就说明,Looper在任何线程中最多只有一个对象。

再细看一下,这里通过调用Looper的私有构造去创建了一个Looper对象,而且这个私有构造,也仅仅是在这里被调用过。所以,再次确保,Looper在任何线程中最多只有一个对象。

然后是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.");
        }
        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
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            final long end;
            try {
                msg.target.dispatchMessage(msg);
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (slowDispatchThresholdMs > 0) {
                final long time = end - start;
                if (time > slowDispatchThresholdMs) {
                    Slog.w(TAG, "Dispatch took " + time + "ms on "
                            + Thread.currentThread().getName() + ", h=" +
                            msg.target + " cb=" + msg.callback + " msg=" + msg.what);
                }
            }

            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();
if (me == null) {
    throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}

这里可以看到,会先看看当前有没有 Looper对象,如果没有就抛异常。这里也就可以看到,如果在自己的代码中,如果没有先执行Looper.prepare();就调用Looper.loop();的话就会抛异常。

然后的逻辑就是遍历当前LooperMessageQueue,取出里面的每个Message对象,都去调用msg.target.dispatchMessage(msg);以及msg.recycleUnchecked();所有的Message对象都取出来了,就跳出循环了。这中间还打印了各种log,不过这些不是关键了。

至于其中的Binder.clearCallingIdentity()可以看看 android IPC通信中的UID和PID识别 ,不过与整体逻辑的分析没有什么影响。

总结:

  1. Looper要想实例化,必须调用prepare()或者prepareMainLooper()
  2. 调用Looper.loop()之前必须先实例化Looper对象。
  3. 每个线程之会有最多一个Looper对象。
  4. Looperloop()方法会取出MessageQueue中的全部Message对象,然后把消息分发出去。

本来准备说一下MessageQueue的,但是里面太多native方法了,就不想去看了。那就说一下Message。其实Message还是比较简单的,是一个实现了Parcelable接口的对象。

Message 提供了一个空构造,这个很好,非常容易理解和使用。public Message() {},但是这上面注释明确说了,更建议使用obtaion()方法。

/**
     * Return a new Message instance from the global pool. Allows us to
     * avoid allocating new objects in many cases.
     */
    public static Message obtain() {
        synchronized (sPoolSync) {
            if (sPool != null) {
                Message m = sPool;
                sPool = m.next;
                m.next = null;
                m.flags = 0; // clear in-use flag
                sPoolSize--;
                return m;
            }
        }
        return new Message();
    }

可以看出 obtain()和构造方法没有什么本质的区别,主要是弄了一个静态变量sPool作为缓存。

然后看一下,Message有一个next字段,这个很有意思,很像那种单链表结构。有一个指针域,指向下一个。

然后Message有多个obtain()重载方法,但是实现都差不多。

    /**
     * Same as {@link #obtain()}, but copies the values of an existing
     * message (including its target) into the new one.
     * @param orig Original message to copy.
     * @return A Message object from the global pool.
     */
    public static Message obtain(Message orig) {
        Message m = obtain();
        m.what = orig.what;
        m.arg1 = orig.arg1;
        m.arg2 = orig.arg2;
        m.obj = orig.obj;
        m.replyTo = orig.replyTo;
        m.sendingUid = orig.sendingUid;
        if (orig.data != null) {
            m.data = new Bundle(orig.data);
        }
        m.target = orig.target;
        m.callback = orig.callback;

        return m;
    }
    /**
     * Same as {@link #obtain()}, but sets the value for the target member on the Message returned.
     * @param h  Handler to assign to the returned Message object's target member.
     * @return A Message object from the global pool.
     */
    public static Message obtain(Handler h) {
        Message m = obtain();
        m.target = h;

        return m;
    }
    /**
     * Same as {@link #obtain(Handler)}, but assigns a callback Runnable on
     * the Message that is returned.
     * @param h  Handler to assign to the returned Message object's target member.
     * @param callback Runnable that will execute when the message is handled.
     * @return A Message object from the global pool.
     */
    public static Message obtain(Handler h, Runnable callback) {
        Message m = obtain();
        m.target = h;
        m.callback = callback;

        return m;
    }

    /**
     * Same as {@link #obtain()}, but sets the values for both target and
     * what members on the Message.
     * @param h  Value to assign to the target member.
     * @param what  Value to assign to the what member.
     * @return A Message object from the global pool.
     */
    public static Message obtain(Handler h, int what) {
        Message m = obtain();
        m.target = h;
        m.what = what;

        return m;
    }

大体都是一样的,只是有参数的obtain(args);就会把参数赋值给成员变量。

然后看一下其中的一个recycle()方法,看看里面到底做了什么?

/**
     * Return a Message instance to the global pool.
     * 

* You MUST NOT touch the Message after calling this function because it has * effectively been freed. It is an error to recycle a message that is currently * enqueued or that is in the process of being delivered to a Handler. *

*/
public void recycle() { if (isInUse()) { if (gCheckRecycle) { throw new IllegalStateException("This message cannot be recycled because it " + "is still in use."); } return; } recycleUnchecked(); } /** * Recycles a Message that may be in-use. * Used internally by the MessageQueue and Looper when disposing of queued Messages. */ void recycleUnchecked() { // Mark the message as in use while it remains in the recycled object pool. // Clear out all other details. flags = FLAG_IN_USE; what = 0; arg1 = 0; arg2 = 0; obj = null; replyTo = null; sendingUid = -1; when = 0; target = null; callback = null; data = null; synchronized (sPoolSync) { if (sPoolSize < MAX_POOL_SIZE) { next = sPool; sPool = this; sPoolSize++; } } }

可以看到这里把所有的成员变量全部置空了,然后把next设置为sPool,然后把sPool设置为this了。

那么,sPool是什么呢?

obtain()里面可以看到:

 public static Message obtain() {
        synchronized (sPoolSync) {
            if (sPool != null) {
                Message m = sPool;
                sPool = m.next;
                m.next = null;
                m.flags = 0; // clear in-use flag
                sPoolSize--;
                return m;
            }
        }
        return new Message();
    }

但是第一个调用obtain()肯定不会走if的逻辑,那么此时,sPool=null,而且 sPool是私有的,所有sPool的赋值只能发生在recycleUnchecked()这里了,这里赋值肯定不会为空,肯定是一个实实在在的 Message对象了。那么下次obtain()的时候,就会走if逻辑了。这时候,就是返回上次保存在sPool中的对象了,这个对象其实也就是当前对象this

这里也可以看出obtain()和一般单例模式的对象获取是不同的,并不是第一个new,第二次用之前的;而是非要等调用过recycle()之后,才能真的实现复用。

然后看一下sendToTarget()

    /**
     * Sends this Message to the Handler specified by {@link #getTarget}.
     * Throws a null pointer exception if this field has not been set.
     */
    public void sendToTarget() {
        target.sendMessage(this);
    }

这个方法也是很有用的,平常使用中就会用到这个的。但是实现很简单,就是调用HandlersendMessage(msg)方法。这里也可以看出,如果之前不是通过obtain(Handler h,xxx)来创建Message对象的,或者之前没有主动调用过setTarget(handler),那么这个方法就会出现空指针异常。

大体上就说这些吧,关于与MessageQueue结合的部分,后续应该会看。

你可能感兴趣的:(android)