Android

Android的消息机制Handler、MessageQueue

2022-03-07  本文已影响0人  漆先生

参考:《Android开发艺术探索》,https://www.jianshu.com/p/8656bebc27cb

一、概述

Android 的消息机制就要是指Handler的运行机制,以及的MesageQueue和Lopper的工作过程。

Handler的主要作用是将一个任务切换到某个指定的线程中去执行。可以在当前线程的来创建Handler,会从threlocal里边取值,直接使用当前线程的Lopper,也可以在一个有Looper的线程中创建Handler。Handler通过post的方法将Runnable投递到Handler内部的Looper中去处理,也可以通过send发送一个消息,这个消息同样会在Looper中处理。

send方法被调用时,会调用MessageQueue的enqueueMesage方法将这个消息翻入消息队列,Looper发现消息到来时,就会处理这个消息。最终消息中的Runnable或者Handler的handleMessage就会被调用,Looper是运行在创建Handler所在的线程中,Handler中的业务逻辑就被切换到创建Handler所在的线程中去执行了。

image.png

二、Message

Message代表一个行为(what)或者一串动作(Runnable),每一个消息在加入消息队列时,都有明确的目标Handler。

三、ThreadLocal

存储本线程的Lopper。提供线程内的局部变量(TLS),这种变量在线程的生命周期内起作用,每一个线程有他自己所属的值(线程隔离)。所操作的对象都是当前线程的localValues对象的table数组,因此可以在多个线程中互不干扰的存储和修改数据。

四、MessageQueue的工作原理

存储消息的队列,虽然叫做队列,但是内部实现并不是用的队列,而是通过单链表的数据结构来维护消息队列。对外提供插入和读取操作,enqueueMessage是往消息队列中插入一条消息,next的作用是从消息队列中取出一条消息并将其从消息队列中移除。

    Message next() {
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }
        int pendingIdleHandlerCount = -1;
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }
            nativePollOnce(ptr, nextPollTimeoutMillis);
            synchronized (this) {
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                if (msg != null && msg.target == null) {
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
                if (msg != null) {
                    if (now < msg.when) {
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        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 {
                    nextPollTimeoutMillis = -1;
                }
                if (mQuitting) {
                    dispose();
                    return null;
                }
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    mBlocked = true;
                    continue;
                }
                if (mPendingIdleHandlers == null) {
                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
                }
                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
            }
            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);
                    }
                }
            }
            pendingIdleHandlerCount = 0;
            nextPollTimeoutMillis = 0;
        }
    }

next是一个无限循环的方法,如果是队列中没有消息,next方法就会阻塞。当有新消息到来,就会返回这条消息到Lopper的loop方法中,并将消息从单列表中移除。

五、Looper的工作原理

消息循环器,不停地从MessageQueue中看是否有消息,有消息就会立马处理,否则一直阻塞在那里。在构造函数里边创建一个MessageQueue,并且保存保存当前线程的对象。

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

Looper.prepare()为当前线程创建Looper。接着通过Looper.loop()来开启消息循环。
HandlerThread是已经带有Looper的线程。在run方法里边也会也是通过此方法创建并开启循环。

    public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }

还提供了Looper.prepareMainLooper给主线程的也就是ActivityThread创建Lopper使用,其本质也是通过prepare方法实现。并且主线程的Looper是不应许退出的。

    public static void prepareMainLooper() {
        prepare(false);//创建的时候不应许退出
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

Lopper.getMainLopper可以在任何地方获取到主线程的Lopper。
Looper可以退出,提供了quie和quitSafely方法:

Looper退出后发送消息会失败,send放回false。
如果是在子线程中创建了Looper,要在事情处理完之后调用quite方法来终止循环,否则子线程一直处于等待状态。退出后这个线程就终止了。

    public static void loop() {
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        if (me.mInLoop) {
            Slog.w(TAG, "Loop again would have the queued messages be executed"
                    + " before this one completed.");
        }

        me.mInLoop = true;
        final MessageQueue queue = me.mQueue;
        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();
        final int thresholdOverride =
                SystemProperties.getInt("log.looper."
                        + Process.myUid() + "."
                        + Thread.currentThread().getName()
                        + ".slow", 0);

        boolean slowDeliveryDetected = false;

        for (;;) {//没消息的时候会阻塞,因为在queue的next中阻塞了
            Message msg = queue.next(); 
            if (msg == null) {
                return;
            }
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }
            final Observer observer = sObserver;

            final long traceTag = me.mTraceTag;
            long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
            long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
            if (thresholdOverride > 0) {
                slowDispatchThresholdMs = thresholdOverride;
                slowDeliveryThresholdMs = thresholdOverride;
            }
            final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
            final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);

            final boolean needStartTime = logSlowDelivery || logSlowDispatch;
            final boolean needEndTime = logSlowDispatch;

            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }

            final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
            final long dispatchEnd;
            Object token = null;
            if (observer != null) {
                token = observer.messageDispatchStarting();
            }
            long origWorkSource = ThreadLocalWorkSource.setUid(msg.workSourceUid);
            try {
                msg.target.dispatchMessage(msg);
                if (observer != null) {
                    observer.messageDispatched(token, msg);
                }
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } catch (Exception exception) {
                if (observer != null) {
                    observer.dispatchingThrewException(token, msg, exception);
                }
                throw exception;
            } finally {
                ThreadLocalWorkSource.restore(origWorkSource);
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (logSlowDelivery) {
                if (slowDeliveryDetected) {
                    if ((dispatchStart - msg.when) <= 10) {
                        Slog.w(TAG, "Drained");
                        slowDeliveryDetected = false;
                    }
                } else {
                    if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
                            msg)) {
                        slowDeliveryDetected = true;
                    }
                }
            }
            if (logSlowDispatch) {
                showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg);
            }

            if (logging != null) {
                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
            }
            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方法是一个死循环,唯一的退出方法是MessageQueue的next方法返回null。Looper的quit方法被调用时,Looper会调用MessageQueue的quit或者是quiteSafely方法通知其退出,消息队列被标记为退出状态时,next方法就会返回null。这样就可以退出,不再无线循环下去了。
loop方法调用了MessaeQueue的next方法,在没有消息时,next方法会阻塞,也导致了loop方法也一直阻塞。
next方法返回了新消息,就会Lopper就会处理:msg.target.dispatchMessage(msg)。msg.target就是发送这条消息的Handler对象。但是dispatchMessage是在创建Handler时使用的Looper中执行,所以最终会在MessageQueue,Looper对应的线程中执行,这样就成功的切换了线程。

六、Handler的工作原理

Handler主要工作数消息的发送和接收过程。

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

先检查msg.callback是否为空。msg.callback是Ruanble,会优先处理。
再次判断mCallback 是否为null,不为空就调用其handleMessage方法,CallBack是一个接口,我们实现handleMessage方法就能处理我们收到的消息了。
最后调用Handler的handleMessage方法来处理消息。

七、postSyncBarrier同步屏障

postSyncBarrier 创建了一个Message对象并加入到了消息链表中,该Message没有target。
设置了同步屏障之后,Handler只会处理异步消息。异步消息的优先级要高于同步消息。
创建Handler时,sync参数传true,就能发送异步消息了。
同步屏障为Handler消息机制增加了一种简单的优先级机制。
Android应用框架中为了更快的响应UI刷新事件在ViewRootImpl.scheduleTraversals中使用了同步屏障。

八、Native实现

Looper 通过 epoll 监听 eventfd,epoll_wait()阻塞。(eventfd 是linux内核一个计数器,主要用于进程间或者线程间,高效的事件通知)
enqueueMessage() 插入消息后,会调用 nativeWake() -> Looper.wake() -> write(),epoll_wait() 便会返回
MessageQueue 取出⼀条消息,比较 when>now,则跳过,同时给 timeoutMillis 赋值,这个值会在 native 的epoll_wait 中使用,阻塞 timeoutMillis 时间后会再次返回。

九、IdleHandler

监听消息队列空闲,在消息队列空闲的时候被调用。可用于启动优化。

十、总结

post() or send()->enqueueMesage()->loop()->queue.next()->msg.target.dispatchMessage()->msg.callBack()在Looper的线程中执行,enqueueMesage和next是同步的
每个Thread只对应一个Looper和一个MessageQueue(一对一)。
每个MessageQueue中有N个待处理消息(一对N)。
每个Message有且仅有一个对应的Handler。(一对一)。
Handler中持有Looper和MessageQueue的引用,可直接对其进行操作。

上一篇 下一篇

猜你喜欢

热点阅读