易懂Android消息机制分析

最浅显讲解Android消息机制

前言:以《安卓开发艺术探索》和自己经验为基础,介绍Android消息机制。Android消息机制主要指Handler机制,同时Handler需要底层的MessageQueue和Looper支撑。Looper会对消息队列进行无限循环,一有消息就会处理。同时在Looper中还有一个重要角色,那就是ThreadLocal,注意他并不是线程,他可以在不同线程中互不干扰地存储数据。还要注意,线程是默认没有Looper的,所以需要自己创建,但是在MainActivity中的ActivityThread会默认初始化Looper,所以主线程默认可以使用Handler。


目录

最浅显讲解Android消息机制

一、Android消息机制概述

二、Handler工作原理

三、ThreadLocal工作原理

四、消息队列的工作原理

五、Looper工作原理

六、Handler工作原理

七、主线程消息机制


 

一、Android消息机制概述

Handler、MessageQueue、Looper其实是一个整体,只不过我们经常使用的是Handler而已,那么为什么Android要提供线程切换的功能呢,或者说为什么不能在子线程访问UI呢,这从ViewRootImpl的线程检查可以看出:

    void checkThread() {
        if (mThread != Thread.currentThread()) {
            throw new CalledFromWrongThreadException(
                    "Only the original thread that created a view hierarchy can touch its views.");
        }
    }

从源码可以看出,如果在子线程访问UI会抛出异常,但是安卓要求主线程又不能进行耗时操作,否则会抛出ANR异常,所以安卓提供了Handler机制,让我们可以在线程间进行切换。

有一个疑问?为什么安卓限制不能在子线程访问UI呢,原因是安卓UI空间是线程不安全的,当并发访问时,会出现错误。可是为什么安卓不加上锁进行控制呢?首先,加锁会让UI访问逻辑变得复杂;其次降低了访问效率。所以安卓工程师决定采用消息机制来进行子线程和UI线程的转换。

二、Handler工作原理

Handler创建时会使用当前线程的Looper,如果没有就会报错。

Handler创建完成后,此使Handler、MessageQueue、Looper就可以协同工作了。Handler可以通过post或者send方法将一个Runnable送到Handler内部的Looper处理,当send方法被调用时,MessageQueue的enqueueMessage方法会把消息放入消息队列中,然后Looper循环发现有新消息,最终handleMessage方法就会被调用。因为Looper在创建Handler的线程,所以Hnadler中的逻辑就被切换到所在线程处理了。

三、ThreadLocal工作原理

ThreadLocal是一个线程存储数据类,通过它可以在指定线程存储数据,且只有本线程可以访问该数据,其他线程无法访问。在安卓源码中Looper、ActivityThread以及AMS中都用到了ThreadLocal。在开发过程中,当我们需要一个对象贯穿整个线程时,就可以使用ThreadLocal,比如,当我们需要一个监听器对象对整个线程可见时,我们传统会采用1)静态变量或者作为2)函数参数进行传递,对于第一种情况,如果有N个线程就需要创建N个静态监听器,对于第二种情况,如果函数调用栈很深时,很容易导致Bug的出现。

例子:

public class ThreadLocalDemo {
    public static void main(String[] args) {
        final ThreadLocal<Boolean> threadLocal = new ThreadLocal<>();
        threadLocal.set(true);
        System.out.println("MainThread:"+threadLocal.get());
        new Thread(new Runnable() {
                    @Override
                    public void run() {
                        threadLocal.set(false);
                        System.out.println("Thread2:"+threadLocal.get());
                    }
                }, "Thread2").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Thread3:"+threadLocal.get());
            }
        }).start();
    }
}

从代码可以看出,虽然不同线程访问的是同一个ThreadLocal对象,但是他们通过ThreadLocal获取的值却是不一样的,这就是其神奇之处。其实现原理就是ThreadLocal内部会从各自线程中取出一个数组,然后根据索引得到相应的value值,当然不同线程的数组是不同的。

    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }
    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();
    }

四、消息队列的工作原理

消息队列在安卓中主要是指MessageQueue,主要包含插入和读取两个操作,其方法分别是enqueueMessage和next。

首先来看插入操作:主要是链表的插入操作

  boolean enqueueMessage(Message msg, long when) {
        ...
        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 {
                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;
    }

再来看看next操作,主要是链表的删除操作: 

    Message next() {
            ...
            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 (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);
            }
            ...
        }
    }

五、Looper工作原理

Looper会不停地从消息队列中检查是否有新消息,如果有就会立即处理,如果没有就会阻塞。

首先看看他的构造器:在构造器中创建消息队列对象

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

我们知道Handler使用的前提是要有Looper,否则会报错,那么如何创建Looper呢,通过Looper.prepare()来创建,通过Looper.loop()来开启循环。

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

Looper除了prepare()方法,还提供了prepareMainLooper()方法,这个方法主要是给主线程创建Looper使用的,他就是封装了prepare方法,该Looper还提供了getMainLooper方法,可以在任何地方得到主线程的Looper。Looper也是可以退出的,使用quit和quitSafely。

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();

        // Allow overriding a threshold with a system prop. e.g.
        // adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
        final int thresholdOverride =
                SystemProperties.getInt("log.looper."
                        + Process.myUid() + "."
                        + Thread.currentThread().getName()
                        + ".slow", 0);

        boolean slowDeliveryDetected = false;

        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;
            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;
            try {
                msg.target.dispatchMessage(msg);
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } finally {
                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)) {
                        // Once we write a slow delivery log, suppress until the queue drains.
                        slowDeliveryDetected = true;
                    }
                }
            }
            if (logSlowDispatch) {
                showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg);
            }

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

从源码可以看出:

  1. 唯一跳出循环的条件是next方法返回null,即消息队列中没有消息了;
  2. 当Looper的quit方法被调用,队列被标记为退出状态,他的next方法就会返回null;
  3. 总之Looper必须退出,否则将一直阻塞在那里;
  4. Looper使用msg.target.dispatchMessage(msg)来处理消息,而该方法又在创建Handler的线程中,所以代码逻辑就被切换到指定线程中去了。

六、Handler工作原理

Handler主要包含消息的发送和接收。以sendMessage方法为例:

    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发送消息就是向消息队列插入一条消息,然后消息队列的next方法会把消息返回给Looper处理,最终Handler的handleMessage方法被调用。

七、主线程消息机制

主线程的入口为main方法,在main方法中,Looper.prepareMainLooper来创建主线程的Looper以及MessageQueue,并通过Looper.loop方法来开启循环。

    public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");

        // CloseGuard defaults to true and can be quite spammy.  We
        // disable it here, but selectively enable it later (via
        // StrictMode) on debug builds, but using DropBox, not logs.
        CloseGuard.setEnabled(false);

        Environment.initForCurrentUser();

        // Set the reporter for event logging in libcore
        EventLogger.setReporter(new EventLoggingReporter());

        // Make sure TrustedCertificateStore looks in the right place for CA certificates
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);

        Process.setArgV0("<pre-initialized>");

        Looper.prepareMainLooper();

        // Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
        // It will be in the format "seq=114"
        long startSeq = 0;
        if (args != null) {
            for (int i = args.length - 1; i >= 0; --i) {
                if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
                    startSeq = Long.parseLong(
                            args[i].substring(PROC_START_SEQ_IDENT.length()));
                }
            }
        }
        ActivityThread thread = new ActivityThread();
        thread.attach(false, startSeq);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

主线程的消息循环开始以后,ActivityThread还需要一个Handler来和消息进行交互,这个Handler就是ActivityThread.H。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值