美文网首页
Android的消息处理机制(深入源码)

Android的消息处理机制(深入源码)

作者: 奥卡姆剃须刀 | 来源:发表于2019-03-08 23:30 被阅读0次
    image.png

    一 Android的消息机制概述

    简介:Android的消息机制主要是指Handle的运行机制,Handle的运行需要底层的MessageQueue和Looper的支撑;所以说Android的消息机制主要就是指Handle的运行机制以及Handle所附带的MessageQueue 和 Looper的工作过程,这三者实际上是一个整体。

    由于Android规定访问UI只能在主线程中进行,如果子线程中访问UI,就会抛出异常 ,子线程不能访问UI,iOS也是一样的

    延伸出一个问题:

    • 为什么系统不允许在子线程中访问UI呢?
      因为UI线程是不安全的,如果多线程中并发访问可能会导致UI控件处于不可预期的状态
    • 为什么系统不对UI控件的访问加上锁机制呢?
      首先加上锁机制会让UI访问的逻辑变得复杂,其次锁机制会降低访问UI的效率,因为锁机制会阻塞某些线程的执行。鉴于这两个缺点,最简单切高效的方法就是采用单线程模型来处理UI操作,那也就是通过Handle切换一下UI访问的执行线程即可

    Handle的工作原理如下图

    image.png

    Handler创建完毕后,这个时候其内部的Looper以及messageQueue就可以和Handler一起协同工作了,通过Handler的post方法讲一个Runnable投递到Handler内部的Looper处理,也可以通过Handler的send方法发送一个消息,这个消息同样会在Looper中去处理,其实Post方法最终也是通过send方法来完成的,当Handler的send方法被调用时,他会调用MessageQueue的enqueueMessage方法将这个消息放入消息队列中,然后Looper发现有新消息到来时,就会处理这个消息,最终消息中的Runnable或者Handler的handleMessage方法就会被调用。注意Looper是运行在Handler所在的线程中的,这样一来Handler中的业务逻辑就会被切换到创建Handler所在的线程中去执行了如上图。

    二 Android的消息机制分析

    2.1 ThreadLocal的工作原理

    简介: ThreadLocal是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,数据存储以后,只有在指定线程中可以获取存储的数据,对于其他线程来说则无法获取到数据。

    作用: 一般来说,当某些数据是已线程为作用域并且不同线程具有不同的数据副本的时候,就可以考虑采用ThreadLocal

    例子演示

    // 定义一个ThreadLocal对象,这里选择Boolean类型的
        private ThreadLocal<Boolean> mBooleanThreadLocal = new ThreadLocal<Boolean>();
        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_thread);
            // 主线程设为 true
            mBooleanThreadLocal.set(true);
            Log.d(TAG, "[Thread#Main] mBooleanThreadLocal = " + mBooleanThreadLocal.get());
            // 子线程设为 false
            new Thread("Thread#1") {
                @Override
                public void run() {
                    mBooleanThreadLocal.set(false);
                    Log.d(TAG, "[Thread#1] mBooleanThreadLocal = " + mBooleanThreadLocal.get());
                }
            }.start();
            // 子线程不设置
            new Thread("Thread#2") {
                @Override
                public void run() {
                    Log.d(TAG, "[Thread#2] mBooleanThreadLocal = " + mBooleanThreadLocal.get());
                }
            }.start();
    
    

    结果为

     D/ThreadActivity: [Thread#Main] mBooleanThreadLocal = true
     D/ThreadActivity: [Thread#1] mBooleanThreadLocal = false
     D/ThreadActivity: [Thread#2] mBooleanThreadLocal = null
    

    可以看出不同线程中访问的是同一个ThreadLocal对象,但是他们通过ThreadLocal获取到的值确实不一样的,是因为不同线程访问同一个ThreadLocal的get方法,ThreadLocal内部会从各自的线程中取出一个数组,然后从数组中根据当前ThreadLocal的索引去查找主对应的Value的值

    ThreadLocal 内部实现原理:
    set方法

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

    首先会通过getmap方法获取当前线程的ThreadLocalMap数据,如果ThreadLocalMap值为null,那就就对其初始化,并存入value值。ThreadLocalMap内部有一个数组 Entry[] table,ThreadLocal就存在这个数组里边,那我们来看一下这个ThreadLocalMap是如何使用set方法将ThreadLocal存入到table数组中的
    ThreadLocalMap的set方法

    private void set(ThreadLocal<?> key, Object value) {
                Entry[] tab = table;
                int len = tab.length;
                int i = key.threadLocalHashCode & (len-1);
                for (Entry e = tab[i];
                     e != null;
                     e = tab[i = nextIndex(i, len)]) {
                    ThreadLocal<?> k = e.get();
                    if (k == key) {
                        e.value = value;
                        return;
                    }
                    if (k == null) {
                        replaceStaleEntry(key, value, i);
                        return;
                    }
                }
                tab[i] = new Entry(key, value);
                int sz = ++size;
                if (!cleanSomeSlots(i, sz) && sz >= threshold)
                    rehash();
            }
    

    我们可以看出threadLocal的值在tabble数组中的存储位置总是为threadLocal的 Referent字段所标识的对象的下一个位置

    ThreadLocalMap的get方法:
    get方法可以看出逻辑也比较清晰:

    public T get() {
            Thread t = Thread.currentThread();
            ThreadLocalMap map = getMap(t);
            if (map != null) {
                ThreadLocalMap.Entry e = map.getEntry(this);
                if (e != null) {
                    @SuppressWarnings("unchecked")
                    T result = (T)e.value;
                    return result;
                }
            }
            return setInitialValue();
        }
    
    2.2 消息队列的工作原理

    简介: 消息队列在Android中指的是MessageQueue,包含两个操作:插入(enqueueMessage)和读取(next);尽管MessageQueue叫做消息队列,但是他的内部实现原理用的却是单链表,其源码如下

     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的实现来看,他的主要操作其实就是单链表的插入操作
    Next方法的源码

    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方法就是一个无线循环的方法,如果消息队列中没有消息,那么Next方法一直阻塞在这里,当有新消息到来时,next方法会返回这条消息并将其从单链表中移除

    2.3 Looper的工作原理

    简介: Looper在Android的消息机制中扮演者消息循环的角色,就是会不停的从MessageQueue中查看是否有新消息如果有新消息,就会立刻处理;否则则阻塞在那里

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

    可以通过Looper.prepare() 为当前线程创建一个Looper,接着通过Looper.loop来开启消息循环

            new Thread("Thread#1") {
                @Override
                public void run() {
                    Looper.prepare();
                    Handler handler = new Handler();
                    Looper.loop();
                }
            }.start();
    

    需要注意:

    • looper还提供了prepareMainLooper方法,给主线程创建Looper使用的,本质也是prepare方法实现
    • Looper提供了一个getMainLooper方法,可以在任何地方获取到主线程的Looper
    • Looper可以退出quite和quitSafely方法,quite会直接退出Looper,而quitSafely会把消息队列中的已有消息处理完毕后才安全退出,
    • 子线程创建的Looper,在消息处理完毕后要手动调用quit方法来终止消息循环

    Looper的loop方法:
    只有调用了loop方法后,消息循环系统才会真正的起作用,loop方法是一个死循环,唯一跳出循环的方式是MessageQueue的next方法返回null,loop方法会调用MessageQueue的next方法来获取新消息,而next方法是一个阻塞操作,当没有消息是,next方法会一直阻塞在那里,这也就导致loop方法一直阻塞在那里,MessageQueue的next方法返回新消息,Looper就会处理这条消息

    如下源码

    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();
            }
        }
    
    2.4 Handle的工作原理

    简介:Handle的工作主要包含消息的发送和接受过程。消息的发送可以通过Post的一系列方法以及Send的一系列方法来实现,Post方法最终也是通过send方法来实现的;
    来看一下源码

    public final boolean sendMessage(Message msg)
        {
            return sendMessageDelayed(msg, 0);
        }
    
    public final boolean sendMessageDelayed(Message msg, long delayMillis)
        {
            if (delayMillis < 0) {
                delayMillis = 0;
            }
            return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
        }
    
    public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
            MessageQueue queue = mQueue;
            if (queue == null) {
                RuntimeException e = new RuntimeException(
                        this + " sendMessageAtTime() called with no mQueue");
                Log.w("Looper", e.getMessage(), e);
                return false;
            }
            return enqueueMessage(queue, msg, uptimeMillis);
        }
    
     private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
            msg.target = this;
            if (mAsynchronous) {
                msg.setAsynchronous(true);
            }
            return queue.enqueueMessage(msg, uptimeMillis);
        }
    

    由源码可以看出,Handler发送消息的过程仅仅是向消息队列中插入了一条消息,MessageQueue的next方法就会返回这条消息给Looper,Looper收到消息后就开始处理了,最终消息由Looper交由Handler处理,即Handler的dispatMessage方法会被调用,这时候Handler就进入了处理消息的阶段。
    dispatMessage的实现源码如下:

     public void dispatchMessage(Message msg) {
    // 检查是否为空
            if (msg.callback != null) {
    // callback是一个Runnable对象,实际上就是Handler的post方法所传递的Runnable参数。
                handleCallback(msg);
            } else {
    // 检查mCallback 是否为空,
                if (mCallback != null) {
                    if (mCallback.handleMessage(msg)) {
                        return;
                    }
                }
    // 最后来处理消息
                handleMessage(msg);
            }
        }
    

    Handler还有一个特殊的构造方法,那就是通过一个特定的Looper来构造Handler,他的实现如下所示:

     public Handler(Looper looper) {
            this(looper, null, false);
        }
    

    Handler的默然构造方法 public Handler(), 这个构造方法会调用下面的构造方法。
    也解释了在没有Looper的子线程中创建Handler会引发程序异常的原因了

     public Handler(Callback callback, boolean async) {
    
            mLooper = Looper.myLooper();
            if (mLooper == null) {
                throw new RuntimeException(
                    "Can't create handler inside thread that has not called Looper.prepare()");
            }
            mQueue = mLooper.mQueue;
            mCallback = callback;
            mAsynchronous = async;
        }
    

    三 主线程的消息循环

    简介 Android的主线程就是ActivityThread,主线程的入口方法为main,在main方法中系统会通过Looper.prepareMainLooper() 来创建主线程的Looper以及MessageQueue,并通过Looper.loop() 来开启主线程的消息循环

     public static void main(String[] args) {
            ...............
            Looper.prepareMainLooper();
     
            ActivityThread thread = new ActivityThread();
            thread.attach(false);
     
            if (sMainThreadHandler == null) {
                sMainThreadHandler = thread.getHandler();
            }
            Looper.loop();
    ................
    

    主线程的消息循环开始以后,ActivityThread还需要一个Handler来和消息队列进行交互,这个Handler就是ActivityThread.H 他内部定义了一组消息类型,主要包含四大组件的启动和停止等过程;

    ActivityThread通过ApplicationThread和AMS进行进程间通信,AMS已进程间通信的方式完成ActivityThread的请求后会回调ApplicationThread中的Binder方法,然后ApplicationThread会向H发送消息,H收到消息后会将ApplicationThread中的逻辑切换到ActivityThread去执行,即切换到主线程中去执行,这个过程就是主线程的消息循环模型

    参考资料:
    《Android开发艺术探索》

    相关文章

      网友评论

          本文标题:Android的消息处理机制(深入源码)

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