Android 消息机制Handler

一、前言

android中,为了保证线程安全的更新UI,且不影响UI更新的性能,没有采取加锁方式更新UI,而是使用单线程更新。所以在android中,只有子线程才能更新UI。为了达到切换线程执行更新UI功能,需要使用Handler机制来完成。另一方面,android可以被理解为是基于事件驱动的,即根据事件的刺激,而做出相应的反应。在Activity的生命周期切换时,便需要Handler机制的参与。

Handler消息机制,是生产者消费者模式的一类。由Handler发送Message,特定的情况下再去消费该Message的非阻塞的模式。至于为什么是非阻塞方式,android只能由主线程更新UI,为了不让用户感觉卡顿现象,只能由将耗时功能放在子线程中,执行完成时再切换至主线程。如果Handler切换的时候,阻塞了线程,便会影响到了用户的体验。

二、线程切换

简而言之,Handler的线程切换,并不是特别的神秘。他只是由一个线程向另一个线程插入一条Runnable,再由该线程去执行。

public class Handler extends Thread {
    
    public Handler() {
        super("Handler");
    }

    private volatile boolean isStop = false;
    private List messages = new ArrayList<>();

    // 插入一条消息
    public synchronized void insertMessage(Runnable message) {
        messages.add(message);
    }

    @Override
    public void run() {
        while (!isStop) {
            Runnable message = null;
            // 1、消息队列中拿到消息
            synchronized (messages) {
                if (messages.size() > 0) {
                    message = messages.remove(0);
                }
            }
            if (message != null) {
                // 2、执行消息
                message.run();
            }

        }
    }

    public void stopThread() {
        isStop = true;
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println(Thread.currentThread());
        Runnable message = new Runnable() {
            
            @Override
            public void run() {
                System.out.println(Thread.currentThread());
            }
        };
        Handler handler = new Handler();
        handler.start();
        handler.insertMessage(message);
        
    }

}

上面代码,虽然简单,却将线程切换的核心知识点写出来了。即通过共享变量的方式,让另一个线程感知执行对象的存在。再配上一定的规则,Handler是按照时间顺序推迟执行。

虽然实现了线程的切换,但是这样简单的Handler会存在很多问题。

问题:

  • 消息使用Runnable是否满足需要?
  • 消息队列用什么数据结构存在比较合理?
  • 采用线程死循环的方式,极度的浪费CPU资源,是否有其他合理的方式?
  • 每新建个Handler对象,都会产生一个线程,能不能利用消息队列的遍历模块?

带着以上的问题,再来Android中的Handler机制会更加的清除点,

三、Handler消息机制

Handler消息机制

如上图可知,Handler的消息机制可分为,消息存储模块、消息的消费模块。以及消息的封装,毕竟java是面向对象的方式,需要将请求参数封装成Message对象。

1) Handler类

 * A Handler allows you to send and process {@link Message} and Runnable
 * objects associated with a thread's {@link MessageQueue}.  Each Handler
 * instance is associated with a single thread and that thread's message
 * queue.  When you create a new Handler, it is bound to the thread /
 * message queue of the thread that is creating it -- from that point on,
 * it will deliver messages and runnables to that message queue and execute
 * them as they come out of the message queue.
 * 

简而言之:
Handler是一个关联一个消息队列,发送或处理Runnable对象,每个Handler都关联一个单个的线程和消息队列,当你创建一个新的Handler的时候它就将绑定到一个线程或线程上的消息队列,这个Handler就将为这个消息队列提供消息或Runnable对象,处理消息队列释放出来的消息或Runnable对象。

对于用户来说,你只需要了解Handler这个类就行了,并不要了解MessageQueue等类,这极大地简化了用户的使用难度。思考下,我们在将模块或者组件设计的之时,能不能让用户了解的很少,就能使用了?

从文档上,可以得到以下的结论。

  • Handler是发送或者处理Runnable的类的。
  • 每个Handler在创建的时候他就绑定到了某一个Thread中。

下面提取两个Handler构造方法:

    public Handler(Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class 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());
            }
        }

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

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

从构造方法中可见,在初始化的时候就会绑定一个Looper,如果Handler没有关联一个Looper就会抛出异常。Callback对象,是执行该Message时候的回调方法。这样就可以通知在另一个线程中执行该Message了。

Handler关联Looper有两种方式
  • 1、初始化的时候就传入一个可用的looper
  • 2、采用looper.prepare()方法,这样当前线程就可以绑定一个Looper对象。然后再构造方法中会调用Looper.myLooper(),这样handler中就保存一份Looper。其中的sThreadLocal可以简单的理解为以Thread为key,以Looper为value的Map集合。
    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));
    }


2) Looper类

  * Class used to run a message loop for a thread.  Threads by default do
  * not have a message loop associated with them; to create one, call
  * {@link #prepare} in the thread that is to run the loop, and then
  * {@link #loop} to have it process messages until the loop is stopped.

Looper是用于为线程运行消息循环的类,默认情况下,线程不会和Looper进行关联,需要使用looper.prepare()方法后,才是关联。之后再调用looper.loop()方法,这样就可以处理消息了,直到loop被停止。

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

Looper的构造方法中可以看出,和Looper相关联的是MessageQueue和当前的Thread对象。

由于Handler中持有Looper对象,自然可以拿到MessageQueue对象。MessageQueue中是存储Message的集合,下面会具体说。因为所有的请求都会封装成Message对象,所以MessageQueue只需要存储Message一种类型即可。

从源码可见,Looper最主要的方法是looper.loop(),这样就可以开始让Looper类工作了。

    /**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the loop.
     */
    public static void loop() {
        // 拿到当前线程的looper
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        // 通过Looper拿到Queue队列
        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();
        // 死循环中读取数据,直到拿到一个有效的Message为止
        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 {
                // 这句话很重要,它是Message执行的触发动作
                // 通过message中的Handler,来执行dispatchMessage()
                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();
        }
    }

上述代码可见,从消息队列中读取到了Message之后,通过Handler中的msg.target.dispatchMessage(msg);来处理Message。

消息的处理策略:
  • 1、第一步如果传入的参数是Runnable(对应代码中的msg.callback),直接调用Runnable中的run方法,然后结束
  • 2、如果无Runnable,那么得看Handler中是否传入了Callback接口对象。如果有mCallback,调用handleMessage(msg)方法,这会返回一个Boolean值。如果true就结束。
  • 3、如果mCallback为null或者handleMessage(msg)返回为false,那就会走到handleMessage(Message msg)方法,子Handler中只需要重写handleMessage方法即可。
    /**
     * 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);
        }
    }

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

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

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

Looper类的作用:

  • 存储MessageQueue和当前线程
  • 轮询消息队列,找到可以执行的消息,再执行即可

3) MessageQueue类


 * Low-level class holding the list of messages to be dispatched by a
 * {@link Looper}.  Messages are not added directly to a MessageQueue,
 * but rather through {@link Handler} objects associated with the Looper.
 *
 * 

You can retrieve the MessageQueue for the current thread with * {@link Looper#myQueue() Looper.myQueue()}.

MessageQueue类是存储多个Message的集合,被Looper类分发处理。我们只能通过Handler类来增加消息,而不能直接的操作MessageQueue,通过looper.myQueue()可以获得当前的线程的MessageQueue。

MessageQueue类只需要关于两点
1、存储机制
2、被轮询Message机制

①、插入消息
    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);
    }

无论是调用sendMessageXXX方法,最终都会用到sendMessageAtTime(Message msg, long uptimeMillis)该方法。插入一个消息需要三个要素,即消息队列Queue、Message和等待执行的时间uptimeMillis。

在enqueueMessage方法中,有行比较重要的代码:msg.target = this;在msg中持有当前Handler对象的引用。 这样Message就和Handler一一对应了,当找到可以执行的Message之后,就能通过handler.dispatchMessage(Message msg)来调度Message了。

前面都是在做准备工作,真正的插入是在MessageQueue中enqueueMessage(msg, uptimeMillis);实现的。Message类本质就是一个以时间为顺序的链表。他通过执行的时间判断,将新的Message插入到哪个地方。

插入的位置可以通过两方面来看,一是队首,二是非队首位置。

通过用链表的方式存储有什么好处

这是由业务决定的,因为所有的消息只会发送一次,没有重发功能,所有的Message都会按照时间的顺序执行。按照链表存储,如果不把第一个链首执行完成,就不可能去执行下一个。这样我们只需要查看链首的消息即可。如果按照Map或者其他的数据结构,就需要遍历整个集合,会非常耗费CPU资源。

boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }

        synchronized (this) {

            msg.markInUse();
            msg.when = when;
            Message p = mMessages;
            boolean needWake;
           // 如果没有消息队首
           // 或者自己的时间等于0
           // 或者执行的时间比队首的时间还要早
            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;
            }
        }
        return true;
    }
②、轮询MessageQueue

轮询功能的触发事件是调用looper.loop()。在loop方法中有个Message msg = queue.next(); // might block 这是真正的从消息队列中遍历。为此,先看看queue.next().

简单的看,next方法就是个死循环,不断的在遍历MessageQueue。

    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;
        }
        //  IdlerHandler的数量
        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
                Message msg = mMessages;
                // 判断首消息是否是个栅栏消息,
                // barrier消息是一个没有handler引用,阻塞同步的消息,对异步的消息开放
                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) {
                     // 判断该Mesage是否到了被执行的时间。
                    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;
                        // 得到一个执行的Message,并且重新构建MessageQueue
                        if (prevMsg != null) {
                            // 中间的Message,让前面的节点指向后面的节点
                            prevMsg.next = msg.next;
                        } else {
                            // 首节点,则直接让下一个Message成为首节点
                            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) {
                     // 关闭消息队列,返回null,通知Looper停止循环
                    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.
            // 处理IdleHandler
            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,可以再次的执行for循环
            nextPollTimeoutMillis = 0;
        }
    }

对于next()方法,取出一个可执行的Message,再重新的构建MessageQueue结构,这样就完成了该类的主要任务。

4) Message类

Message常量

Message类,即Android消息机制处理的对象。它里面封装了所有程序运行的变量。下面就一一介绍主要的变量参数:

  • what :消息的标志,即消息的ID
  • arg1、arg2:消息携带的参数
  • obj : 用于跨进程时,传递的Object对象
  • replyTo :用于跨进程的Messager
  • next : 用于构建链表
  • target : Handler,用于处理该消息的Handler
  • when :执行该消息的绝对时间
  • callback : Runnable,将Handler传递的Runnable,封装成此Message
  • sPool :消息池链表的头部

基本的常量,就在上图所示。对于Message对象,可以通过构造方法实现,但推荐通过Message.obtain()或者Handler.obtainMessage(),这样是从一个可回收的对象池中获取Message对象。

对于Message有些值得研究的,如:

  • Message的存储结构,是链表存储方式
  • Message的消息池原理

(一)、消息池机制

对于消息池,它的完成的就是废物利用,节省内存开销。

①、obtain()

Message中obtain()有很多重载方法,先看下最基本的无参方法。

   public static Message obtain() {
        synchronized (sPoolSync) {
            // 消息池还有值
            if (sPool != null) {
                // 去除链表首部,并成为要使用的Message
                Message m = sPool;
                sPool = m.next;
                m.next = null;
                m.flags = 0; // clear in-use flag
                // 消息池大小减一
                sPoolSize--;
                return m;
            }
        }
        return new Message();
    }

从源码中,我们大体可以了解到,该方法就是从消息池中拿出一个Message使用。这个方法是个消费者,整体是个生成者和消费者模型,那么生成者在哪了?

②、recycleUnchecked()

既然是废物利用,那么就在Message使用完成的时候,才能回收重新使用。而消息的回收则在recycleUnchecked()方法中。

void recycleUnchecked() {
        // Mark the message as in use while it remains in the recycled object pool.
        // Clear out all other details.
        // 还原Message
        flags = FLAG_IN_USE;
        what = 0;
        arg1 = 0;
        arg2 = 0;
        obj = null;
        replyTo = null;
        sendingUid = -1;
        when = 0;
        target = null;
        callback = null;
        data = null;

        synchronized (sPoolSync) {
            if (sPoolSize < MAX_POOL_SIZE) {
                // 将该回收的Message放在消息池的队首
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
    }

从源码中,该方法就做了两件事情。

  • 1、还原该Message的参数
  • 2、将该Message插入到消息池链表队首

由于可能会多线程的操作sPool,需要对sPool读或者写加锁,即增加了sPoolSync对象锁。

5) HandlerThread 类

通常Handler会跟Handler联系在一起比较。简单的说HandlerThread是一个继承了Thread,含有Looper成员变量的线程。

下面就来看下HandlerThread源码,就可以知道该类的功能了。

public class HandlerThread extends Thread {
    int mPriority;
    int mTid = -1;
    Looper mLooper;
    private @Nullable Handler mHandler;

    public HandlerThread(String name) {
        super(name);
        mPriority = Process.THREAD_PRIORITY_DEFAULT;
    }
    
    public HandlerThread(String name, int priority) {
        super(name);
        mPriority = priority;
    }
    
    /**
     * Call back method that can be explicitly overridden if needed to execute some
     * setup before Looper loops.
     */
    protected void onLooperPrepared() {
    }

    @Override
    public void run() {
        mTid = Process.myTid();
        // 1、线程执行的时候,调用 Looper.prepare();让looper和此线程绑定
        Looper.prepare();
        synchronized (this) {
            // 在获取looper的方法中是阻塞的,构建好looper对象后notifyAll通知过去,解除阻塞
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
       // 2、完成Looper准备的回调
        onLooperPrepared();
       // 开启loop方法轮序消息队列
        Looper.loop();
        mTid = -1;
    }
    
    /**
     * This method returns the Looper associated with this thread. If this thread not been started
     * or for any reason isAlive() returns false, this method will return null. If this thread
     * has been started, this method will block until the looper has been initialized.  
     * @return The looper.
     */
    public Looper getLooper() {
        if (!isAlive()) {
            return null;
        }
        
        // If the thread has been started, wait until the looper has been created.
        synchronized (this) {
            while (isAlive() && mLooper == null) {
                try {
                    wait();
                } catch (InterruptedException e) {
                }
            }
        }
        return mLooper;
    }

    /**
     * @return a shared {@link Handler} associated with this thread
     * @hide
     */
    @NonNull
    public Handler getThreadHandler() {
        if (mHandler == null) {
            mHandler = new Handler(getLooper());
        }
        return mHandler;
    }

    /**
     立即停止Looper
     */
    public boolean quit() {
        Looper looper = getLooper();
        if (looper != null) {
            looper.quit();
            return true;
        }
        return false;
    }

    /**
      安全的停止Looper
     */
    public boolean quitSafely() {
        Looper looper = getLooper();
        if (looper != null) {
            looper.quitSafely();
            return true;
        }
        return false;
    }

    /**
     * Returns the identifier of this thread. See Process.myTid().
     */
    public int getThreadId() {
        return mTid;
    }
}

总的来说,代码比较简单,值得注意的是getLooper()中,如果looper还没初始化好,就wait()阻塞起来。当run方法初始化完成后,在调用notifyAll()解除阻塞。

HandlerThread使用步骤:
  • 创建对象 HandlerThread handlerThread=new HandlerThread("HandlerThread")
  • 开启线程 handlerThread.start()
  • 获取Looper, Looper looper=handlerThread.getLooper();
  • 构建该线程Handler,Handler handler=new Handler(looper);
  • 执行自己的操作
  • quit()或quitSafely(),结束Looper

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