详解Handler

作者: Chase_stars | 来源:发表于2019-07-07 12:05 被阅读17次

    生活有度,人生添寿 — 书摘

    写在前面

    对于Android开发者来说,Handler一定不陌生,在日常开发中会经常用到它,我们都知道Android主线程不能处理耗时任务,否则会容易发生ANR,但是在子线程执行完耗时任务,要想更新UI怎么办呢?不要慌,Android提供了一个消息机制Handler来解决这个问题。

    Handler的作用是跨线程通信,当子线程中进行耗时操作后需要更新UI时,通过Handler将有关UI的操作切换到主线程中执行。

    分别介绍下四要素:

    • Message(消息):需要被传递的消息,其中包含了消息Id,消息处理对象以及消息处理的数据等,由MessageQueue统一列队,最终由Handler处理。
    • MessageQueue(消息队列):用来存放Handler发送过来的消息,内部通过单链表的数据结构来维护消息队列,等待Looper的抽取。
    • Handler(处理者):负责Message的发送及处理,通过Handler的sendMessage向MessageQueue发送消息,通过handleMessage处理相应的消息事件。
    • Looper(消息泵):通过Looper.prepare()创建实例,通过Looper.loop()不断的从MessageQueue中抽取消息,按分发机制将消息分发给目标处理者。

    用法

    下面用一个简单的Demo来演示一下Handler该如何使用,这里开启了一个子线程sleep一秒来模拟任务,在子线程中调用sendEmptyMessage发送一条消息,当Handler的handleMessage收到该条消息时,弹出一个Toast。

    public class MainActivity extends AppCompatActivity implements View.OnClickListener {
        private Button mStartTask;
    
        private Handler mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 1) {
                    Toast.makeText(MainActivity.this, "更新UI", Toast.LENGTH_SHORT).show();
                }
            }
        };
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            initView();
        }
    
        private void initView() {
            mStartTask = findViewById(R.id.btn_start_task);
            mStartTask.setOnClickListener(this);
        }
    
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_start_task:
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(1000);
                                mHandler.sendEmptyMessage(1);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                    break;
            }
        }
    }
    

    学会了使用,那么问题来了,让我们带着问题去分析源码:
    1.明明是在子线程发送的,是如何切换至主线程的呢?
    2.sendEmptyMessage发送的消息,handleMessage是如何接收到的呢?

    源码

    一.首先来看Handler是如何创建的,初始化的时候都做了什么?

    1.从Handler的构造函数开始
        /**
         * Default constructor associates this handler with the {@link Looper} for the
         * current thread.
         *
         * If this thread does not have a looper, this handler won't be able to receive messages
         * so an exception is thrown.
         */
        public Handler() {
            this(null, false);
        }
    
        /**
         * Constructor associates this handler with the {@link Looper} for the
         * current thread and takes a callback interface in which you can handle
         * messages.
         *
         * If this thread does not have a looper, this handler won't be able to receive messages
         * so an exception is thrown.
         *
         * @param callback The callback interface in which to handle messages, or null.
         */
        public Handler(Callback callback) {
            this(callback, false);
        }
    
        /**
         * Use the provided {@link Looper} instead of the default one and take a callback
         * interface in which to handle messages.
         *
         * @param looper The looper, must not be null.
         * @param callback The callback interface in which to handle messages, or null.
         */
        public Handler(Looper looper, Callback callback) {
            this(looper, callback, false);
        }
    
        /**
         * Use the {@link Looper} for the current thread
         * and set whether the handler should be asynchronous.
         *
         * Handlers are synchronous by default unless this constructor is used to make
         * one that is strictly asynchronous.
         *
         * Asynchronous messages represent interrupts or events that do not require global ordering
         * with respect to synchronous messages.  Asynchronous messages are not subject to
         * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
         *
         * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
         * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
         *
         * @hide
         */
        public Handler(boolean async) {
            this(null, async);
        }
    
        /**
         * Use the {@link Looper} for the current thread with the specified callback interface
         * and set whether the handler should be asynchronous.
         *
         * Handlers are synchronous by default unless this constructor is used to make
         * one that is strictly asynchronous.
         *
         * Asynchronous messages represent interrupts or events that do not require global ordering
         * with respect to synchronous messages.  Asynchronous messages are not subject to
         * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
         *
         * @param callback The callback interface in which to handle messages, or null.
         * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
         * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
         *
         * @hide
         */
        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,但有一点需要注意,只有先Looper.prepare(),才会创建新的Looper,
            // 也就是说Looper.prepare()一定在这之前执行过了,否则会直接抛出异常
            // Looper.prepare()是在哪里调用的呢?
            mLooper = Looper.myLooper();
            if (mLooper == null) {
                throw new RuntimeException(
                    "Can't create handler inside thread that has not called Looper.prepare()");
            }
            // 创建Looper实例时,Looper会创建一个MeesageQueue,
            // 直接把Looper的MessageQueue拿出来使用
            mQueue = mLooper.mQueue;
            // 为Callback赋值
            mCallback = callback;
            mAsynchronous = async;
        }
    

    从上面代码可以看出,无论是调用无参数的构造函数还是带参数的构造函数,最终都会调用带两个参数的构造函数,带两个参数的构造函数内部做了一些初始化的事情,为其一些变量赋值。

    2.何处调用Looper.prepare()
    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();
    
            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");
        }
    

    以上代码是ActivityThread类中的main函数,在这个函数中Android系统已经帮我们调用了Looper.prepare(),就是Looper.prepareMainLooper()。

    3. Looper.prepareMainLooper()做了什么
        private Looper(boolean quitAllowed) {
            mQueue = new MessageQueue(quitAllowed);
            mThread = Thread.currentThread();
        }
    
        /**
         * Initialize the current thread as a looper, marking it as an
         * application's main looper. The main looper for your application
         * is created by the Android environment, so you should never need
         * to call this function yourself.  See also: {@link #prepare()}
         */
        public static void prepareMainLooper() {
            prepare(false);
            synchronized (Looper.class) {
                if (sMainLooper != null) {
                    throw new IllegalStateException("The main Looper has already been prepared.");
                }
                sMainLooper = myLooper();
            }
        }
    
        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));
        }
    
        /**
         * Return the Looper object associated with the current thread.  Returns
         * null if the calling thread is not associated with a Looper.
         */
        public static @Nullable Looper myLooper() {
            return sThreadLocal.get();
        }
    

    从以上代码看到prepareMainLooper内部其实先调用了prepare,prepare内部会创建一个新的Looper对象,并放入ThreadLocal;然后又调用了myLooper,myLooper内部会从ThreadLocal得到Looper对象,并赋值给sMainLooper。

    那么Looper的构造函数做了什么呢?创建了一个新的MessageQueue实例,并得到当前所在线程。

    既然用到了ThreadLocal,就介绍一下它是用来干什么的,ThreadLocal 为解决多线程程序的并发问题提供了一种新的思路。使用这个工具类可以很简洁地编写出优美的多线程程序。当使用ThreadLocal 维护变量时,ThreadLocal 为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。实则ThreadLocal.set设置的值是与当前线程进行绑定了的。

    所以就能得出结论,Looper.prepare()函数就是将Looper与当前线程进行绑定,ThreadLocal就是负责绑定。

    二.Handler如何发送和接收消息

    1.Handler开始sendMessage
        /**
         * Pushes a message onto the end of the message queue after all pending messages
         * before the current time. It will be received in {@link #handleMessage},
         * in the thread attached to this handler.
         *  
         * @return Returns true if the message was successfully placed in to the 
         *         message queue.  Returns false on failure, usually because the
         *         looper processing the message queue is exiting.
         */
        public final boolean sendMessage(Message msg)
        {
            return sendMessageDelayed(msg, 0);
        }
    
        /**
         * Enqueue a message into the message queue after all pending messages
         * before (current time + delayMillis). You will receive it in
         * {@link #handleMessage}, in the thread attached to this handler.
         *  
         * @return Returns true if the message was successfully placed in to the 
         *         message queue.  Returns false on failure, usually because the
         *         looper processing the message queue is exiting.  Note that a
         *         result of true does not mean the message will be processed -- if
         *         the looper is quit before the delivery time of the message
         *         occurs then the message will be dropped.
         */
        public final boolean sendMessageDelayed(Message msg, long delayMillis)
        {
            if (delayMillis < 0) {
                delayMillis = 0;
            }
            return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
        }
    
        /**
         * Enqueue a message into the message queue after all pending messages
         * before the absolute time (in milliseconds) <var>uptimeMillis</var>.
         * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
         * Time spent in deep sleep will add an additional delay to execution.
         * You will receive it in {@link #handleMessage}, in the thread attached
         * to this handler.
         * 
         * @param uptimeMillis The absolute time at which the message should be
         *         delivered, using the
         *         {@link android.os.SystemClock#uptimeMillis} time-base.
         *         
         * @return Returns true if the message was successfully placed in to the 
         *         message queue.  Returns false on failure, usually because the
         *         looper processing the message queue is exiting.  Note that a
         *         result of true does not mean the message will be processed -- if
         *         the looper is quit before the delivery time of the message
         *         occurs then the message will be dropped.
         */
        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);
        }
    

    从以上代码看出,最终调到了enqueueMessage,内部将当前的Handler赋值给了Message中的target变量,这样就将每个调用sendMessage的Handler与Message进行绑定;返回值为queue.enqueueMessage(),也就是说最终调到了MessageQueue的enqueueMessage,将这个消息加入到MessageQueue中。

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

    上面的代码就是把消息放入消息队列,如果添加消息成功会返回true,失败则返回false,等待Looper来读取。

    如果是delay的消息并不会先等待一段时间在放入消息队列,而是直接进入并阻塞当前线程,然后将其delay的时间与队头进行比较,按照触发时间进行排序,如果触发时间更近则放入队头,保证队头的时间最小,队尾的时间最大,此时,如果对头的Message正是被delay的,则将当前线程堵塞一段时间,等待足够的时间再唤醒执行该Message,否则唤醒后直接执行。

    3.Looper.loop()读取消息

    众所周知,Handler内部维护了Looper的,通过Looper.loop()开启消息循环,不断的从MessageQueue中读取消息,最后调用handleMessage来处理消息。

    不知细心的同学有没有发现Looper.loop()是何时调用的,其实是在ActivityThread类的main函数中调用的,在这个函数中Android系统也已经帮我们调用好了Looper.loop()。

    那么就来看看Looper.loop()都做了什么吧。

        /**
         * 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.");
            }
            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 (;;) {
                // 从MessageQueue中读取消息
                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 {
                    // 这行代码非常重要,这里的dispatchMessage则又回到了调用sendMessage的Handler中。
                    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();
            }
        }
    

    在这个函数中,首先拿到与主线程绑定的Looper,然后开始死循环,并在死循环中不断调用MessageQueue的next函数读取消息,当得到消息后会通过Message的target调用dispatchMessage派发消息。Message的target是Handler的sendMessage最后调用enqueueMessage中将当前Handler赋值给target的,所以也就是调用的Handler的dispatchMessage。

    4.Handler处理消息

    现在再将视线回到Handler,通过Looper.loop()读取出来的消息投递给了Handler的dispatchMessage。

        /**
         * Callback interface you can use when instantiating a Handler to avoid
         * having to implement your own subclass of Handler.
         */
        public interface Callback {
            /**
             * @param msg A {@link android.os.Message Message} object
             * @return True if no further handling is desired
             */
            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) {
            // msg.callback就是Runnable对象
            if (msg.callback != null) {
                handleCallback(msg);
            } else {
                if (mCallback != null) {
                    if (mCallback.handleMessage(msg)) {
                        return;
                    }
                }
                handleMessage(msg);
            }
        }
       
        private static void handleCallback(Message message) {
            // 其实就是让Runnable执行
            message.callback.run();
        }
    

    首先来看dispatchMessage,msg.callback就是Runnable对象,如果不为null,就会调用handleCallback让Runnable跑起来;mCallback是Callback接口,如果不为null就会调用Callback的handleMessage,否则就会执行Handler自己的handleMessage。

    5.回到主线程

    到这里Handler的工作机制就算分析完了,在子线程中Handler发送消息的时候就已经和Message进行了绑定,在通过Looper.loop()开启消息轮询的时候,当调用MessageQueue的next得到Message的时候,就会调用与Message绑定的Handler对象执行dispatchMessage,最终调用handleMessage,由于Looper对象是在主线程创建的,Handler也是在主线程中创建的,所以自然就从子线程切换到了主线程。

    6.分析Message

    Message作为消息,也必要了解一下,它其实可以理解为一个Bean。

    在实际项目中会用到大量的Message,为了避免重复创建Message,Message内部提供了一个obtain()方法,它会从消息池中返回一个新的Message实例。

        private static final Object sPoolSync = new Object();
        private static Message sPool;
        private static int sPoolSize = 0;
    
        /**
         * Return a new Message instance from the global pool. Allows us to
         * avoid allocating new objects in many cases.
         */
        public static Message obtain() {
            synchronized (sPoolSync) {
                if (sPool != null) {
                    Message m = sPool;
                    sPool = m.next;
                    m.next = null;
                    m.flags = 0; // clear in-use flag
                    sPoolSize--;
                    return m;
                }
            }
            return new Message();
        }
    
     /**
         * Recycles a Message that may be in-use.
         * Used internally by the MessageQueue and Looper when disposing of queued Messages.
         */
        void recycleUnchecked() {
            // Mark the message as in use while it remains in the recycled object pool.
            // Clear out all other details.
            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) {
                    next = sPool;
                    sPool = this;
                    sPoolSize++;
                }
            }
        }
    
    

    从以上代码可以看到,sPool就是一个静态的变量,若为空则创建一个新的Message实例,否则会直接返回sPool,在回收Message时,会将Message重置并赋值给sPool,这样就有效的避免了重复创建Message,从而达到复用的目的。

    总结

    具体流程.png
    • Handler.sendMessage()时会通过MessageQueue.enqueueMessage()向MessageQueue中添加一条消息,MessageQueue会按照delay时间进行排序,保证队头时间最小,队尾时间最大,如果队头的时间是delay的,则将当前线程堵塞一段时间,等待足够的时间唤醒当前线程继续执行。
    • 通过Looper.loop()开启消息循环后,不断轮询调用MessageQueue.next(),当读取的消息不为空时,就会调用目标Handler.dispatchMessage()去传递消息。
    • 目标Handler收到消息后调用Handler.handleMessage()处理消息。

    相关文章

      网友评论

        本文标题:详解Handler

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