Android消息机制之二基础简介(2)

Android 5年前 (2018) 125la.com站长
193 0 0
广告也精彩

我们通过上一篇《Android消息机制Handler,Looper,Message,MessageQueue关系之一》知道,Android的消息机制必须将HandlerLooperMessageMessageQueue一起“组织”起来,而且是缺一不可。

比如在子线程中使用Handler必须先Looper.prepare(),然后Looper.loop(),这样才有作用。(主线程也是这样声明的,具体可看第一篇,这里是从子线程中第一个消息机制开始讲解)

直接上代码

//代码片段3,加Looper.prepare()和Looper.loop()
    private class MyThread extends Thread{

        @Override
        public void run() {
            super.run();
            //初始化
            Looper.prepare();  //[1.0 Looper的初始化]

            myHandler =new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    //to do something
                }
            };
            //循环
            Looper.loop(); //[2.0 Looper的循环]
            //这下面的代码一般情况是不会执行的
        }
    }

1.0 Looper.prepare();

下面是prepare(),最终调用的还是prepare(boolean quitAllowed)。

    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));//[1.1 Looper的初始化和保存]
    }
1.1 Looper的初始化和保存

我们上次分析过ThreadLocal它是用来保存各线程中变量的值(此处是Looper对象),而且各线程互不影响。

Looper的构造函数中只是初始化了MessageQueue和Thread对象

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

    final MessageQueue mQueue;
    final Thread mThread;

    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed); //[1.2 MessageQueue的初始化,这样Looper和MessageQueue扯上了关系]
        mThread = Thread.currentThread();
    }
1.2 MessageQueue的初始化

直接调用MessageQueue的构造函数,同时传入一个是否允许退出的标志位quiteAllowed

    MessageQueue(boolean quitAllowed) {
        mQuitAllowed = quitAllowed;  //主线程中的Looper是不允许退出的(quitAllowed=false),其他子线程是允许的(quitAllowed= true)
        mPtr = nativeInit(); //通过native方法初始化消息队列,其中mPtr是供native代码使用(此处摘于gityuan.com)
    }

    //是否允许退出,主线程是不允许退出的
    void quit(boolean safe) {
        if (!mQuitAllowed) {
            throw new IllegalStateException("Main thread not allowed to quit.");
        }

        synchronized (this) {
            if (mQuitting) {
                return;
            }
            mQuitting = true;

            if (safe) {
                removeAllFutureMessagesLocked();
            } else {
                removeAllMessagesLocked();
            }

            // We can assume mPtr != 0 because mQuitting was previously false.
            nativeWake(mPtr); 
        }
    }

2.0 Looper的循环

直接看代码,代码有点多。

   /**
     * 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(); //获取当前的looper对象,如果没有prepare,就抛出异常
        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();

        for (;;) {// 死循环
            Message msg = queue.next(); // might block   //[2.1获取下一条Message,这里有提示,可能阻塞]
            if (msg == null) {//如果为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); //[2.2 Handler消息的分发,msg.target就是Handler]

            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();//[2.3 Message的回收]
        }
    }

2.1 从MessageQueue中获取Message

queue.next()获取的是Message,这里可能阻塞。

    Message next() {
        // Return here if the message loop has already quit and been disposed.
        // This can happen if the application tries to restart a looper after quit
        // which is not supported.
        final long ptr = mPtr;  //[2.1.1当消息循环已经退出,则直接返回]
        if (ptr == 0) {
            return null;
        }

        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        //这里也有一个死循环,
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }
            //阻塞操作,当等待nextPollTimeoutMillis时长,或者消息队列被唤醒,都会返回(摘于gityuan.com)
            nativePollOnce(ptr, nextPollTimeoutMillis);

            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                if (msg != null && msg.target == null) {
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    //当消息Handler为空时,查询MessageQueue中的下一条异步消息msg,则退出循环。(摘于gityuan.com)
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
                if (msg != null) {
                    if (now < msg.when) {
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // Got a message.
                        //获取一条message 同时把阻塞标签mBlocked置为false
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        //设置消息的使用状态,即flags |= FLAG_IN_USE
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1; //表示消息队列中无消息,会一直等待下去
                }

                // Process the quit message now that all pending messages have been handled.
                //正在退出
                if (mQuitting) {
                    dispose();
                    return null;
                }

                // If first time idle, then get the number of idlers to run.
                // Idle handles only run if the queue is empty or if the first message
                // in the queue (possibly a barrier) is due to be handled in the future.
                //pendingIdleHandlerCount,开头是初始化为-1(直接看英文)
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    // No idle handlers to run.  Loop and wait some more.
                   //没有idle Handler
                    mBlocked = true;
                    continue;
                }

                if (mPendingIdleHandlers == null) {
                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
                }
                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
            }

            // Run the idle handlers.
            // We only ever reach this code block during the first iteration.
            // //只有第一次循环时,会运行idle handlers,执行完成后,重置pendingIdleHandlerCount为0.(摘于gityuan.com)
            for (int i = 0; i < pendingIdleHandlerCount; i++) {
                final IdleHandler idler = mPendingIdleHandlers[i];
                mPendingIdleHandlers[i] = null; // release the reference to the handler  //去掉handler的引用

                boolean keep = false;
                try {
                    keep = idler.queueIdle(); //idle时执行的方法
                } catch (Throwable t) {
                    Log.wtf(TAG, "IdleHandler threw exception", t);
                }

                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }
             //重置idle handler个数为0,以保证不会再次重复运行(摘于gityuan.com)
            // Reset the idle handler count to 0 so we do not run them again.
            pendingIdleHandlerCount = 0;

            // While calling an idle handler, a new message could have been delivered
            // so go back and look again for a pending message without waiting.
            //当调用一个空闲handler时,一个新message能够被分发,因此无需等待可以直接查询pending message.(摘于gityuan.com)
            nextPollTimeoutMillis = 0;
        }
    }

nativePollOnce()是阻塞操作,其中nextPollTimeoutMillis代表下一个消息到来前,还需要等待的时长;当nextPollTimeoutMillis = -1时,表示消息队列中无消息,会一直等待下去。

当处于空闲时,往往会执行IdleHandler中的方法。当nativePollOnce()返回后,next()从mMessages中提取一个消息。(此两行摘抄于gityuan.com)

2.1.1 mPtr初始化和改变赋值

//在MessageQueue的构造函数中初始化
    MessageQueue(boolean quitAllowed) {
        mQuitAllowed = quitAllowed;
        mPtr = nativeInit(); //本地方法中初始化
    }  

  //dispose()中赋值为0
  // Disposes of the underlying message queue.
    // Must only be called on the looper thread or the finalizer.
    private void dispose() {
        if (mPtr != 0) {
            nativeDestroy(mPtr);//nativeDestroy
            mPtr = 0;
        }
    }
2.2 Handler消息的分发dispatchMessage

在Looper.loop()中有

 msg.target.dispatchMessage(msg);

此处调用的是msg.target.dispatchMessage(),然而msg.target是Handler,我们先看看Message

//Message.java中声明了Handler的变量
 /*package*/ Handler target;

Message的初始化,Message.java中有一个无参数构造函数,同时Android推荐使用obtain()方法来获取Message对象,因为Message创建后会通过recycleUnchecked把假如一个message池中,重复利用。

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

    /** Constructor (but the preferred way to get a Message is to call {@link #obtain() Message.obtain()}).
    */
    public Message() {
    }
2.3 Message的回收

Message创建实例后,并不会直接释放而是放入消息池中,以便重复利用

    /**
     * Return a Message instance to the global pool.
     * <p>
     * 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.
     * </p>
     */
    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++;
            }
        }
    }

上面我们知道msg.target.dispatchMessage(),其实就是Handler.dispatchMessage()进行消息分发。我们直接看Handler源码中的dispatchMessage

    /**
     * Callback interface you can use when instantiating a Handler to avoid
     * having to implement your own subclass of Handler.
     *
     * @param msg A {@link android.os.Message Message} object
     * @return True if no further handling is desired
     */
    public interface Callback {
        public boolean handleMessage(Message msg);
    }
 
   /**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(Message msg) {
    }
    
    /**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            //如果msg中有callback,直接调用message.callback.run(),具体看下面
            handleCallback(msg); 
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) { //走自己实现的handleMessage,也就是我们自己代码中写的
                    return;
                }
            }
            handleMessage(msg); //走我们自己实现的handleMessage,也就是Handler自身的回调方法handleMessage()
        }
    }

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

dispatchMessage(Message msg),只是分发message,然后回调Handler的handleMessage()让用户自己处理。

这样就把Handler,Looper,MessageQueue,Message联系在一起了。

小姐(结)来了

上面写得有点乱,也就是简单的走了一下,实在不好意思。不过还是建议有兴趣的朋友自己走走过程,加深影响。

不过,我们从上面看,可以粗略的看到。

  1. Handler、Message、Looper、MessageQueue有紧密的关系,请看下图(图片来源于gityuan.com)
  2. Handler的创建必须在prepare和loop之间,而且不允许多次调用prepare()

Android消息机制之二基础简介(2)

 

广告也精彩
版权声明:125la.com站长 发表于 2018年5月17日 下午12:57。
转载请注明:Android消息机制之二基础简介(2) | 125啦读书导航

相关文章

广告也精彩

暂无评论

暂无评论...