Android Handler 消息机制原理解析

欢迎访问个人我的博客 传送门html

前言

作过 Android 开发的童鞋都知道,不能在非主线程修改 UI 控件,由于 Android 规定只能在主线程中访问 UI ,若是在子线程中访问 UI ,那么程序就会抛出异常java

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy .

而且,Android 也不建议在 UI 线程既主线程中作一些耗时操做,不然会致使程序 ANR 。若是咱们须要作一些耗时的操做而且操做结束后要修改 UI ,那么就须要用到 Android 提供的 Handler 切换到主线程来访问 UI 。所以,系统之因此提供 Handler,主要缘由就是为了解决在子线程中没法访问 UI 的问题。android

概述

要理解 Handler 消息机制原理 还须要了解几个概念:安全

  1. UI 线程数据结构

    主线程 ActivityThreadapp

  2. Message异步

    Handler 发送和处理的消息,由 MessageQueue 管理。async

  3. MessageQueueide

    消息队列,用来存放经过 Handler 发送的消息,按照先进先出执行,内部使用的是单链表的结构。oop

  4. Handler

    负责发送消息和处理消息。

  5. Looper

    负责消息循环,循环取出 MessageQueue 里面的 Message,并交给相应的 Handler 进行处理。

在应用启动时,会开启一个 UI 线程,而且启动消息循环,应用不停地从该消息列表中取出、处理消息达到程序运行的效果。
Looper 负责的就是建立一个 MessageQueue,而后进入一个无限循环体不断从该 MessageQueue 中读取消息,而消息的建立者就是一个或多个 Handler 。
流程图以下:

Android Handler 消息机制原理解析

下面结合源码来具体分析

Looper

Looper 比较重要的两个方法是 prepare( ) 和 loop( )

先看下构造方法

final MessageQueue mQueue;

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

Looper 在建立时会新建一个 MessageQueue

经过 prepare 方法能够为 Handler 建立一个 Lopper,源码以下:

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
 private static Looper sMainLooper;  // guarded by Looper.class

 public static void prepare() {
        prepare(true);
 }

 private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            //一个线程只能有一个looper
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));
 }

 public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

能够看到这里建立的 Looper 对象使用 ThreadLocal 保存,这里简单介绍下 ThreadLocal。

ThreadLocal 是一个线程内部的数据存储类,经过它能够在指定的线程中存储数据,数据存储之后,只有在指定线程中能够获取到存储的数据,对于其余线程来讲则没法获取到数据,这样就保证了一个线程对应了一个 Looper,从源码中也能够看出一个线程也只能有一个 Looper,不然就会抛出异常。

prepareMainLooper() 方法是 系统在 ActivityThread 中调用的。

ActivityThread.java

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

       //...省略代码

        Looper.prepareMainLooper();

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

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

由此能够看出,系统在建立时,会自动建立 Looper 来处理消息,因此咱们通常在主线程中使用 Handler 时,是不须要手动调用 Looper.prepare() 的。这样 Handler 就默认和主线程的 Looper 绑定。
当 Handler 绑定的 Looper 是主线程的 Looper 时,则该 Handler 能够在其 handleMessage 中更新UI,不然更新 UI 则会抛出异常。
在开发中,咱们可能在多个地方使用 Handler,因此又能够得出一个结论:一个 Looper 能够和多个 Handler 绑定,那么 Looper 是怎么区分 Message 由哪一个 Handler 处理呢?
继续看源码 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 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~6 行 获取当前 Looper 若是没有则抛异常,有则获取消息队列 MessageQueue
因此若是咱们在子线程中使用 Handler 则必须手动调用 Looper.prepare() 和 Looper.loop()
系统在代码中提供了示例代码

class LooperThread extends Thread {
            public Handler mHandler;

            public void run() {
                Looper.prepare();

                mHandler = new Handler() {
                    public void handleMessage(Message msg) {
                        // process incoming messages here
                    }
                };

                Looper.loop();
            }
        }

获取到 MessageQueue 后开启消息循环,不断从 MessageQueue 中取消息,无则阻塞,等待消息。有则调用 msg.target.dispatchMessage(msg) 处理消息。

msg.target 就是 Message 所属的 Handler,这个会再后面具体介绍 Handler 中会说明

因此上面的问题就能够回答了,Looper 不须要考虑怎么区分 Message 由哪一个 Handler 处理,只负责开启消息循环接收消息并处理消息便可。处理完消息后会调用 msg.recycleUnchecked() 来回收消息。

那么开启消息循环后,能够中止吗?
答案是确定的,Looper 提供了 quit() 和 quitSafely() 来退出。

public void quit() {
     mQueue.quit(false);
  }

  public void quitSafely() {
     mQueue.quit(true);
  }

能够看到实际上调用的是 MessageQueue 中的退出方法,具体会在 MessageQueue 中介绍。
调用 quit() 会直接退出 Looper,而 quitSafely() 只是设定一个退出标记,而后把消息队列中的已有消息处理完毕后才安全地退出。在 Loooper 退出后,经过 Handler 发送消息会失败。若是在子线程中手动建立了 Looper ,则应在处理完操做后退出 Looper 终止消息循环。

到此 Looper 的源码分析就完了,咱们来总结下 Looper 所作的工做:

  1. 被建立时与线程绑定,保证一个线程只会有一个 Looper 实例 ,而且一个 Looper 实例只有一个 MessageQueue
  2. 建立后,调用 loop( ) 开启消息循环,不断从 MessageQueue 中取 Message ,而后交给 Message 所属的 Handler 去处理,也就是 msg.target 属性。
  3. 处理完消息后,调用 msg.recycleUnchecked 来回收消息

Message 和 MessageQueue

Message 是线程通讯中传递的消息,它有几个关键点

  1. 使用 what 来区分消息
  2. 使用 arg一、arg二、obj、data 来传递数据
  3. 参数 target,它决定了 Message 所关联的 Handler,这个在后面看 Handler 源码时会一目了然。

MessageQueue

MessageQueue 负责管理消息队列,经过一个单链表的数据结构来维护。
源码中有三个主要方法:

  1. enqueueMessage 方法往消息列表中插入一条数据,
  2. next 方法从消息队列中取出一条消息并将其从消息队列中移除
  3. quit 方法退出消息列表,经过参数 safe 决定是否直接退出

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

               //...省略代码
        }
    }

能够发现 next 方法是一个无限循环的方法,若是消息队列中没有消息,那么 next 方法会一直阻塞在这里。当有新消息到来时,next 方法会从中获取消息出来返回给 Looper 去处理,并将其从消息列表中移除。

quit方法

void quit(boolean safe) {
    if (!mQuitAllowed) {
        throw new IllegalStateException("Main thread not allowed to quit.");
    }

    synchronized (this) {
        if (mQuitting) {
            return;
        }
        mQuitting = true;

        if (safe) {
            removeAllFutureMessagesLocked();//移除还没有处理的消息
        } else {
            removeAllMessagesLocked();//移除全部消息
        }

        // We can assume mPtr != 0 because mQuitting was previously false.
        nativeWake(mPtr);
    }
}

private void removeAllMessagesLocked() {
    Message p = mMessages;
    while (p != null) {
        Message n = p.next;
        p.recycleUnchecked();
        p = n;
    }
    mMessages = null;
}

private void removeAllFutureMessagesLocked() {
    final long now = SystemClock.uptimeMillis();
    Message p = mMessages;
    if (p != null) {
        if (p.when > now) {
            removeAllMessagesLocked(); // 移除还没有处理的消息
        } else { // 正在处理的消息不作处理
            Message n;
            for (;;) {
                n = p.next;
                if (n == null) {
                    return;
                }
                if (n.when > now) {
                    break;
                }
                p = n;
            }
            p.next = null;
            do {
                p = n;
                n = p.next;
                p.recycleUnchecked();
            } while (n != null);
        }
    }
}

从 上述代码中能够看出,当 safe 为 true 时,只移除还没有触发的全部消息,对于正在处理的消息不作处理,当 safe 为 false 时,移除全部消息。

Handler

Handler 是咱们使用最多的类,主要用来发送消息和处理消息。

先来看构造方法

public Handler(Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> klass = getClass();
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                    (klass.getModifiers() & Modifier.STATIC) == 0) {
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                    klass.getCanonicalName());
            }
        }
        //获取当前线程的 Looper 实例,若是不存在则抛出异常
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        //关联 Looper 中的 MessageQueue 消息队列
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
}

public Handler(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
}

构造方法主要有三个参数

  1. looper 不传值则调用 Looper.myLooper( ) 获取当前线程的 Looper 实例;传值则使用,通常是在子线程中使用 Handler 时才传参数。
  2. callback Handler 处理消息时的回调
  3. async 是不是异步消息。这里和 Android 中的 Barrier 概念有关,当 View 在绘制和布局时会向 Looper 中添加了 Barrier(监控器),这样后续的消息队列中的同步的消息将不会被执行,以避免会影响到 UI绘制,可是只有异步消息才能被执行。所谓的异步消息也只是体如今这,async 为 true 时,消息还能够继续被执行,不会被推迟运行。

从源码中可看出,由于 UI 线程在启动时会自动建立 Looper 实例,因此通常咱们在 UI 线程中使用 Handler 时不须要传递 Looper 对象。而在子线程中则必须手动调用 Looper.prepare 和 Looper.loop 方法,并传递给 Handler ,不然没法使用,这一点确定有很多童鞋都遇到过。
在拿到 Looper 对象后,Handler 会获取 Looper 中的 MessageQueue 消息队列,这样就和 MessageQueue 关联上了。

关联上 MessageQueue ,接下来那咱们就看下 Handler 是如何发送消息的。

Handler 发送消息方法不少,实际上最后都是调用的 enqueueMessage 方法,看图说话

Android Handler 消息机制原理解析

主要看 enqueueMessage 方法

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

能够看到在发送消息时给 Message 设置了 target = this 也就是当前的 Handler 对象,并调用了 MessageQueue 的 enqueueMessage 方法,这样就把消息存在消息队列,而后由 Looper 处理了。

童鞋们应该记得以前在讲 Looper 时,说到 Looper 开启消息循环后,会不断从 MessageQueue 中取出Message,并调用 msg.target.dispatchMessage(msg) 来处理消息。

接下来,就来看看 Handler 是如何接收消息的也就是 dispatchMessage 方法

public interface Callback {
        public boolean handleMessage(Message msg);
    }

    /**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(Message msg) {

    }

    /**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

能够看出 Handler 接收消息,只是调用一个空方法 handleMessage 是否是有些眼熟呢,看下咱们写过不少次的 Handler 代码

private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case value:

                    break;

                default:
                    break;
            }
        }

    };

没错这就是咱们本身建立 Handler 时重写的方法,由咱们来处理消息,而后根据 msg.what 标识进行消息处理。

总结

应用启动时会启动 UI 线程也就是主线程 ActivityThread,在 ActivityThread 的 main 方法中会调用 Looper.prepareMainLooper( ) 和 Looper.loop ( ) 启动 Looper 。
Looper 启动时会建立一个 MessageQueue 实例,而且只有一个实例,而后不断从 MessageQueue 中获取消息,无则阻塞等待消息,有则调用 msg.target.dispatchMessage(msg) 处理消息。
咱们在使用 Handler 时 须要先建立 Handler 实例,Handler 在建立时会获取当前线程关联的 Looper 实例 ,和 Looper 中的消息队列 MessageQueue。而后在发送消息时会自动给 Message 设置 target 为 Handler 自己,并把消息放入 MessageQueue 中,由 Looper 处理。Handler 在建立时会重写的
handleMessage 方法中处理消息。
若是要在子线程中使用 Handler 就须要新建 Looper 实例,传给 Handler 便可。

再看下流程图
Android Handler 消息机制原理解析

最后

因篇幅较长,童鞋们的 Handler 确定用的炉火纯青了,因此最后就不写例子了。本人写博客不久,写的很差的地方,望各位海涵。