Android消息机制

Android的消息机制主要是指Handler的运行机制,通过Handler可以轻松的将一个任务切换到Handler所在的线程中执行.

概述

将Handler用于UI更新:

有时候需要在子线程中进行耗时的IO操作,当耗时操作完成后可能需要在UI上做一下变化,因为Android开发规范限制,我们不能在子线程中访问UI控件,否则会出发程序异常(ANR 无响应),此时通过Handler就可以将更新UI的操作切换到主线程中执行.

//Android在ViewRootImpl中进行UI操作验证.
 void checkThread() {
        if (mThread != Thread.currentThread()) {
            throw new CalledFromWrongThreadException(
                    "Only the original thread that created a view hierarchy can touch its views.");
        }
    }
不允许在子线程更新UI操作的原因:

Android的UI控件不是线程安全的,如果在多线程中并发访问可能会导致UI控件处于不可预期的状态.
那么为什么系统不对UI控件的访问加上锁机制呢.其实有两点:

  • 加上锁机制会使得UI访问逻辑变得复杂
  • 锁机制会降低UI访问的效率,因为锁机制会阻塞某些线程执行.
Handler的执行流程

Handler创建完毕后,通过Handler的postXX()方法将一个Runnable传递到Handler的内部的Looper中去处理.

 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 postDelayed(Runnable r, Object token, long delayMillis){...}
 public final boolean postAtFrontOfQueue(Runnable r){...}

也可以通过Handler的sendXX()方法发送一个消息,这个消息同样会在Looper中处理.

 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){...}
 public final boolean sendMessageAtFrontOfQueue(Message msg){...}

在这个过程中,其实postXX()方法内部最后也是调用的sendXX()方法来完成的.因此我们就分析一下sendXX()方法的调用过程.

当Handler的sendXX()方法被调用时,会执行enqueueMessage方法将这个消息放入队列中,然后Looper发现有新消息到来时,就会处理这个消息.

  //Handler中的
  private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
//其内部调用的MessageQueue的enqueueMessage方法.

此时,Handler中的业务逻辑就被切换到了创建Handler所在的线程中去执行了(因为Looper运行在创建Handler所在线程).

分析

ThreadLocal
定义

ThreadLocal是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,数据存储后,只有在指定线程中可以获取到存储的数据.

使用场景
  • 当某些数据是以线程为作用域,并且不同线程有不同的数据副本时,就可以使用ThreadLocal.
    比如对于Handler来说,需要获取当前线程的Looper,此时Looper的作用域就是线程,并且不同的线程拥有不同的Looper.
  • 复杂逻辑下的对象传递,比如监听器的传递.
    有些时候一个线程中的任务过于复杂(函数调用栈较深以及代码入口多样性),这种情况下,我们又需要监听器能够贯穿整个线程的执行过程.此时采用ThreadLocal可以让监听器作为线程内的全局对象而存在,在线程内部只要通过get方法就可以获得监听器.
示例

在不同的线程中使用同一个ThreadLocal对象:

public class CustomActivity extends AppCompatActivity {

    private static final String TAG = "Sean";

    private ThreadLocal mThreadLocal = new ThreadLocal<>();


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom);


        mThreadLocal.set(true);
        Log.d(TAG, "Thread[#main] mThreadLocal=" + mThreadLocal.get());


        new Thread("Thread[#1]"){
            @Override
            public void run() {
                mThreadLocal.set(false);
                Log.d(TAG, "Thread[#1] mThreadLocal=" + mThreadLocal.get());
            }
        }.start();

        new Thread("Thread[#2]"){
            @Override
            public void run() {
                Log.d(TAG, "Thread[#2] mThreadLocal=" + mThreadLocal.get());
            }
        }.start();

    }
}

...打印结果:
2018-11-12 15:04:41.942 18529-18529/? D/Sean: Thread[#main] mThreadLocal=true
2018-11-12 15:04:41.943 18529-18565/? D/Sean: Thread[#1] mThreadLocal=false
2018-11-12 15:04:41.943 18529-18566/? D/Sean: Thread[#2] mThreadLocal=null

可以很清楚的看见,虽然在不同的线程访问同一个ThreadLocal对象,但是获取到的值是不同的.

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

首先拿到当前线程实例t,接着通过t获得ThreadLocalMap,我们看到是通过getMap方法获取到的ThreadLocalMap,继续看getMap方法的实现.

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

getMap方法中直接返回了Thread类中的threaLocals.

    ThreadLocal.ThreadLocalMap threadLocals = null;

清楚了各个方法的实现后,我们来捋一捋:
首先ThreadLocal的set方法中,拿到当前线程对象中的ThreadLocalMap对象的实例,其实就是Thread类中的theadLocals.然后将需要保存的值保存到threadLocals中.
说的明显一点就是,每个线程中的ThreadLocal的副本都保存在当前线程Thread对象中,存储结构为ThreadLocalMap,键值的类型分别是当前ThreadLocal实例和传入的内容值.
接下来给获取函数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();
    }

同理,拿到当前线程的对象实例中保存的ThreadLocalMap,然后读取当前ThreadLocal实例所对应的值.

    private T setInitialValue() {
        T value = initialValue();
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
        return value;
    }

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

通过createMap来创建ThreadLocalMap对象实例,set函数中的ThreadLocalMap实例也是通过createMap生成的.
到此ThreadLocal的存取机制工作流程已经介绍清楚了,并且后续会有文章来详细介绍ThreadLocalMap的存储结构.

MessageQueue工作机制

顾名思义,MessageQueue翻译成中文就是消息队列,它提供的主要两个操作是:插入和读取,对应的方法分别为enqueueMessage和next.
虽然MessageQueue叫消息队列,但是它的内部实现是通过单链表结构来维护消息列表的.

enqueueMessage

作用:往消息队列中插入一条消息.

      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方法会返回这条消息并从单链表中移除.

Looper的工作原理

Looper在Android的消息机制中扮演者消息循环的角色,它会不停的从MessageQueue中查看是否有新消息,如果有新消息就立刻处理,否则一直阻塞在那里.
我们先看一下Looper的构造方法,在构造方法中它会创建一个MessageQueue消息队列,然后将当前线程的对象保存起来.

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

Handler的工作需要Looper,没有Looper线程就会报错,那么如果为一个线程创建Looper呢?

    /** Initialize the current thread as a looper.
      * This gives you a chance to create handlers that then reference
      * this looper, before actually starting the loop. Be sure to call
      * {@link #loop()} after calling this method, and end it by calling
      * {@link #quit()}.
      */
    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));
    }

接着调用Looper.loop()方法来开启消息循环.开始循环调用MessageQueue的next()方法查询新消息.

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

loop()方法是一个死循环,唯一跳出循环的方式是MessageQueue的next()方法返回了null.

Looper提供了quit和quitSafely来退出一个Looper.
两者的区别是:quit会直接退出Looper,而quitSafely只是设定一个退出标记,然后把消息队列中的已有消息处理完毕后才安全的退出.
Looper退出后,通过Handler发送消息会失败,并且此时调用send()方法会返回false.
当我们在子线程中手动创建了Looper,那么当所有任务执行完毕后应该调用quit方法来终止消息循环,否则这个子线程会一直处于等待的状态.
当调用Looper的quit或quitSafely方法后会执行MessageQueue的quit方法,此时MessageQueue的next方法就会返回null.也就是说,Looper必须退出,否则loop()方法就会无限循环下去.
如果MessageQueue的next()方法返回了消息,Looper就会处理这条消息.

Handler的工作原理

Handler的主要工作包含发送和接收消息的过程.
Handler发送时向消息队列中插入一条消息,MessageQueue的next()方法会将这条消息返给Looper,Looper收到消息后开始处理,最终交给Handler再进行处理.此时Handler的dispathMessage方法会被调用.

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

首先检查Message的callback是否为null,不为null则通过handleCallBack来处理消息.
Message的callback是一个runnable对象.实际上就是Handler的post方法所传递的Runnable参数.

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

当Message的callback为null时则检查mCallback是否为null,不为null则调用handleMessage方法来处理消息.

文章只是自己学习过程中的总结,写的不好请指正,谢谢.

你可能感兴趣的:(Android消息机制)