美文网首页
android消息处理机制

android消息处理机制

作者: 骑着毛驴追宝马 | 来源:发表于2017-09-22 22:06 被阅读0次

    做过android开发的同学,相信对android的消息处理都不陌生。在我们开发应用中也是无时不刻不用到它,相信大家对handler的消息处理都能够熟练使用了,那么本文将从源码角度带领读者完成Handler,MessageQueue,Looper,ThreadLocal之间的联系以及以及从消息发送到完成接收,系统为我们做了些什么。
    handler相信大家都不陌生了,要完成线程间的消息通信一定会用到它,而使用handler无非是用到他的sendMessage或post方法,以及handleMessage回调。其实,在整个消息流中也确实是只有这些处理了。主要依赖的还是MessageQueue,Looper与handler之间的联系。
    在消息发送与消息处理完成,MessageQueue对于我们一直是不可见的,但我们却必须用到它。MessageQueue作为消息队列,顾名思义是用来存储消息的。而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;
    }
    

    通过enqueueMessage方法,将message插入到合适的位置,从这里我们可以看到,MessageQueue并非使用队列作为消息存储的,其实使用了单向链表的结构。
    接下来我们看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方法中,一开始就进入了一个死循环 for (;;),在循环中主要完成对message的查找并返回的操作,当MessageQueue为空时,那么就会一直处于block状态,直到MessageQueue不为空或mQuitting为true.

    分析完MessageQueue我们接下来看Looper,其实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 traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            try {
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
    
            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中仍然是进行了死循环操作 for (;;),在循环中不断从获取MessageQueue中获取消息:
    Message msg = queue.next();
    唯一跳出循环的条件是msg == null。其实当我们调用Looper.quit()时,就是改变MessageQueue的mQuitting为true,使其返回null退出的。
    当获取到新消息时,会调用到
    msg.target.dispatchMessage(msg);
    而msg.target又是一个handler对象,咦,是不是有些熟悉呢?其实一点也没错,这里的handler就是我们一开始在代码里面定义的handler,这一点可以在handler中找到:

    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
    

    不管你是通过send还是post方式,最终都会调用到这里的,不信自己可以去跟踪下代码。
    接下来我们继续跟踪下msg.target.dispatchMessage(msg);方法

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

    到这里我们又回到了handler方法中,又回到了最初的起点:这里会进行条件判断,如果msg.callback不为null,处理handleCallback(msg),而msg.callback是我们通过handler的post方法传进来的Runnable对象,这一点源码中可以看到:

      public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }
    

    继续跟踪getPostMessage(r)方法:

        private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }
    

    可以看到,通过getPostMessage方法,将Runnable对象赋给了Message的callback回调:
    而handleCallback最终对调用到Runnalbe的run方法:

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

    而第二个判断mCallback != null是作为构造参数传给handler,是我们自己定义实现的callback回调;最后一种实现是handleMessage(msg);是一个空实现,是由我们自己继承handleMessage(msg)来实现的。

    到这里我们从消息发送到消息接收并处理整个流程都跑通了,是不是该结束了呢?
    不,因为还有一个核心的东西我们还没有提到,而它正是我们可以完成跨线程通信的核心机制,就是我们开始说到的ThreadLocal,ThreadLocal并不是本地线程,甚至连一个新线程也不算,为什么要叫ThreadLocal?他跟Thread有什么关系?这里我们要从Looper的生命周期开始看起:
    在我们创建handler时,如果我们没有在构造中传入Looper,那么handler会在构造方法中初始化Looper.

        mLooper = Looper.myLooper();
    

    在Looper.myLooper()中:

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

    这里调用到了sThreadLocal.get()方法,而sThreadLocal正是ThreadLocal对象,而在sThreadLocal.get()方法中:

        public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null)
                return (T)e.value;
        }
        return setInitialValue();
    }
    

    这里用到了ThreadLocalMap类,主要用作数据存储的,而在getMap(t)方法中,

        ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }
    

    返回了Thread的threadLocals对象,也是ThreadLocalMap的对象,其实ThreadLocalMap是用作数据存储的,而ThreadLocalMap既是ThreadLocal的内部类,又是Thread的成员变量,不过通过ThreadLocal的set和get方法我们可以得知其实ThreadLocal操作的就是当前线程的ThreadLocalMap对象,通过调用Looper.parpare()为当前线程的ThreadLocalMap对象设置looper对象:

    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.set(new Looper(quitAllowed))方法中:

        public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }
    

    当第一次创建Map时,

      void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }
    

    将Looper对象最终传给了当前线程的ThreadLocalMap对象并缓存,这就是为什么Looper和线程为什么可以绑定了,因为每一个Thread对应了一个Looper对象,当我们通过调用当前线程的Looper.parpare时,其实就已经将 Looper与当前线程绑定在了一起,而Looper持有了MessageQueue的引用,所以接下来的操作都绑定在了Looper所关联的线程中了。所以handler处理消息回调时所在的线程并不一定是在handler的创建线程。

    不信我们可以试试在子线程中创建handler,但在handler构造中传入主线程的Looper,并在回调中打印当前线程名。

    你发现规律了吗?

    相关文章

      网友评论

          本文标题: android消息处理机制

          本文链接:https://www.haomeiwen.com/subject/eujdlxtx.html