Android消息机制全面解析

Android消息机制可以说是众人皆知了,作为一个Android开发者没用过是不可能的。其原理相对是一个比较简单的内容。本篇文章我们来进行一个简单的梳理。在消息机制中我们主要有下面几块内容需要掌握。

  • Handler:一个发送和处理消息的类,其依赖于Looper构建,如果他所在的线程中没有Looper就会出现异常。而消息的处理也是在looper所在的线程。
  • Looper,一个无限循环器,循环去拿MessageQueue中的message。
  • MessageQueue,消息队列。单链表形式存储Message。
  • ThreadLoacal:此内容可查看另一篇文章:ThreadLocal全面解析。
    1、首先我们来看消息队列MessageQueue,它提供了插入消息,和拿出消息的两个方法。分别是enqueueMessage,next
    boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }
        if (msg.isInUse()) {
            throw new IllegalStateException(msg + " This message is already in use.");
        }

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

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

根据这个方法我们可以看到,我们的MessageQueue是以单链表形式存储我们的消息的,并且,当我们的消息都是立即发送的时候,会把消息存储在链表第一个位置,当我们发送延时消息的时候,会根据延时的时间大小将我们的消息存放在链表中。时间小的在链表前面。

    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;
        if (ptr == 0) {
            return null;
        }

        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }

            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.
                    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.
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        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.
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    // No idle handlers to run.  Loop and wait some more.
                    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.
            for (int i = 0; i < pendingIdleHandlerCount; i++) {
                final IdleHandler idler = mPendingIdleHandlers[i];
                mPendingIdleHandlers[i] = null; // release the reference to the handler

                boolean keep = false;
                try {
                    keep = idler.queueIdle();
                } catch (Throwable t) {
                    Log.wtf(TAG, "IdleHandler threw exception", t);
                }

                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }

            // 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.
            nextPollTimeoutMillis = 0;
        }
    }

通过next方法源码我们可以看出,是一个无线循环的方法,一直去消息队列中取消息,如果没有消息将会阻塞在这里,有消息了就会跳出循环,返回消息并把消息从消息队列中删除。

  • Looper消息循环,我们知道如果我们在一个子线程中创建Handler,如果在这个线程中没有调用 Looper.prepare();的话会发生"Can't create handler inside thread that has not called Looper.prepare()"的异常,因为Handler是依赖Looper存在的,但是为什么我们在主线程中创建Handler没有调用 Looper.prepare();就可以呢?那是因为我们的系统在AcitivityThread的Main方法中默认调用了Looper.prepareMainLooper();其原理也是调用了prepare方法。
    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实例放在了我们的ThreadLocal中。

    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

而我们创建Looper的同时还创建了我们的MessageQueue.所以我们子线程的消息队列和主线程的消息队列不是同一个。Looper也不是同一个。
我们知道当我们执行了Looper.prepare();方法创建了Looper之后,它并没有真正的开始工作,还没有循环起来去拿队列中的消息进行处理。我们还需要调用Looper.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();
        }
    }

从loop方法中我们可以看出loop方法是一个无线循环的方法,在循环里面会调用消息队列的next方法获取消息,并调用msg.target.dispatchMessage(msg);处理消息,而跳出循环的条件是msg==null,但是通过我们之前对消息队列next方法的分析,我们知道,next方法也是一个无线循环的方法,并且在消息队列中没有消息的时候一直循环去拿消息,直到拿到消息。所以loop方法会阻塞在那里,等待消息队列返回消息。那么什么时候next才能返回null呢。其实当我们loop调用quit()或者quitSafely()。就会调用我们的消息队列的quit()方法,这时,消息队列返回消息就会是null。
我们来看一下这两个方法

class Looper
    public void quit() {
        mQueue.quit(false);
    }

    public void quitSafely() {
        mQueue.quit(true);
    }

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

从上面的代码中我们可以看出当我们Looper进行quit或者quitSafely的时候实际上是调用MessageQueue的removeAllMessagesLocked()和removeAllFutureMessagesLocked();

class MessageQueue
    private void removeAllMessagesLocked() {
        Message p = mMessages;
        while (p != null) {
            Message n = p.next;
            p.recycleUnchecked();
            p = n;
        }
        mMessages = null;
    }

    private void removeAllFutureMessagesLocked() {
        final long now = SystemClock.uptimeMillis();
        Message p = mMessages;
        if (p != null) {
            if (p.when > now) {
                removeAllMessagesLocked();
            } else {
                Message n;
                for (;;) {
                    n = p.next;
                    if (n == null) {
                        return;
                    }
                    if (n.when > now) {
                        break;
                    }
                    p = n;
                }
                p.next = null;
                do {
                    p = n;
                    n = p.next;
                    p.recycleUnchecked();
                } while (n != null);
            }
        }
    }
 class Message
    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++;
            }
        }
    }

通过上面的两个方法的源码我们可以看出,Looper的quit方法会直接将我们消息队列中的消息调用recycleUnchecked()方法将所有消息的内容消除,导致我们的消息无法进行处理。并且,不允许再往消息队列中插入新的消息,直到我们消息队列中没有消息之后,MessageQueue的next就会返回null,然后我们的Looper就会停止循环,而我们的removeAllFutureMessagesLocked是把所有的消息和当前时间进行比较,来比较是否是延迟消息如果是延迟消息,将之后的延迟消息的消息内容制空。

  • Handler,发送和处理消息的方法。其中有很多可以发送消息的方法。
    public final boolean post(Runnable r);
    public final boolean postAtTime(Runnable r, long uptimeMillis);
    public final boolean postAtTime(Runnable r, Object token, long uptimeMillis);
    public final boolean postDelayed(Runnable r, long delayMillis);
    public final boolean sendMessage(Message msg);
    public final boolean sendEmptyMessage(int what);
    public final boolean sendEmptyMessageDelayed(int what, long delayMillis) ;
    public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis);
    public final boolean sendMessageDelayed(Message msg, long delayMillis);
    public boolean sendMessageAtTime(Message msg, long uptimeMillis);
    发送消息的方法有很多,但是通过源码我们可以看出他们是有关系的,比如post方法都会默认调用sendMessageDelayed方法,而sendMessageDelayed方法又会默认去调用sendEmptyMessageAtTime方法。sendMessageDelayed和sendEmptyMessageAtTime方法的区别并不大,sendMessageDelayed的延时事件参数是一个相对时间,相对于现在1000毫秒,而sendEmptyMessageAtTime的参数是一个绝对时间,是以系统开机时间开始(去除休眠时间)的一个绝对时间。
    public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

而Post系列方法和send系列方法的区别为 post系列方法参数为Runnable他会创建一个Massage并把runnable复制给msg.callback,并且将我们的发送消息的Handler复制给我们的Message的target 参数。通过发送消息的源码我们可以看出最终会调用消息队列的enqueueMessage方法将消息放到消息队列当中,通过上面我们对Looper的分析我们知道,当Looper取到消息的时候会调用msg.target.dispatchMessage(msg);来处理消息,其实就是调用我们发送消息的Handler的dispatchMessage方法来处理消息。

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

通过上面的方法我们可以看出,当消息有CallBack时候,就会执行消息的CallBack,如果没有将会查看mCallback,mCallback其实就是我们创建Handler的时候Handler构造方法中的Runnable,如果mCallback返回true的话我们Handler的handleMessage方法就不会执行,如果mCallback返回为false的话我们的handleMessage就会执行了。

你可能感兴趣的:(Android消息机制全面解析)