Handler的工作原理

作者: 可乐游侠 | 来源:发表于2018-08-24 16:36 被阅读9次

    概述

    Handler机制主要由Handler、MessageQueue、Looper三个类实现。Handler把Message放进MessageQueue里,Looper循环读取MessageQueue中的消息,然后交由消息的target处理,也就是交由Handler处理。由于在Thread A中调用sendMessage()方法,Looper在Thread B中运行处理消息,因此能实现线程的切换。

    MessageQueue

    MessageQueue的作用是存储消息,虽然名称带有Queue,但实际数据结构是一个单链表,这是由于MessageQueue并不完全是先进先出的原则,需要插入和删除操作,因此适用单链表结构。

    MessageQueue主要有插入和读取并删除两个操作。插入数据对应的方法是enqueueMessage(),读取对应的方法是next()。

    enqueueMessage方法源码如下:

    boolean enqueueMessage(Message msg, long when) {
            ...
            synchronized (this) {
                ...
    
                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基本上是根据when属性做链表的插入操作。

    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方法中读取消息大概逻辑为,如果有Message,并且已经到了Message的设定的处理时间,则返回该Message。否则更新nextPollTimeoutMillis变量记录等待时间,并判断是否有空闲消息,如果有空闲消息则进行处理,然后重新读取消息。如果没有空闲消息,就在nativePollOnce(ptr, nextPollTimeoutMillis)阻塞住,等待下一个消息。

    Looper

    Looper主要职责是不停的循环读取MessageQueue中的消息,然后交由Handler进行处理。对应的方法是loop()。

    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;
    
            ...
    
            for (;;) {
                Message msg = queue.next(); // might block
                if (msg == null) {
                    // No message indicates that the message queue is quitting.
                    return;
                }
                ...
                    msg.target.dispatchMessage(msg);
                ...
    
                msg.recycleUnchecked();
            }
        }
    

    Looper无限循环读取消息,即使不再使用,也会阻塞着等待新消息,当前线程就无法结束,因此需要退出Looper的循环。

    根据源码可以看到MessageQueue的next()方法返回null的时候会return。而在MessageQueue中的next()方法中可以看到mQuitting为true的时候返回null。搜索MessageQueue的源码发现通过quit(boolean safe)方法退出。

    if (mQuitting) {
        dispose();
        return null;
    }
    

    Handler

    Handler主要职责是发送消息和处理消息。

    发送消息:

        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类发送消息的方法有很多,都是调用sendMessageDelayed()方法,最后调用enqueueMessage(),可以发现发送消息其实只是把消息放进MessageQueue。

    这里设置了msg.target = this,在Looper取出消息的时候,就是交由target处理。以此来保证发出的消息由同一个Handler进行处理。

    处理消息:

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

    消息处理逻辑如下:

    1. 如果msg的callback不为null,则调用msg.callback.run()。这主要处理Handler的post(Runnable r)方法发送过来的Runnable。处理方法如下:

          private static void handleCallback(Message message) {
              message.callback.run();
          }
      
    2. 如果mCallback不为null,就交给mCallback的handleCallback方法进行处理。

    3. 如果mCallback为null或者mCallback的handleCallback方法返回false,则直接交给Handler的handleMessage()方法处理。

    相关问题

    • 在子线程new Handler的时候会出现bug如下:

      java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
      at android.os.Handler.<init>(Handler.java:203)
      

      从源码中找问题,Handler最终构造方法如下:

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

      当该线程不存在Looper对象时,会抛出这个异常。因此在初始化Handler之前,需要通过Looper.prepare()初始化Looper对象。并调用loop()方法开始循环读取Message。如下:

            Looper.prepare();
              Handler handler = new Handler();
              Looper.loop();  
      

      但是在主线程并不需要这么麻烦,是因为在主线程的main方法中,已经初始化了Looper对象。

      public static void main(String[] args) {
            ...
      
              Looper.prepareMainLooper();
      
              ActivityThread thread = new ActivityThread();
              thread.attach(false);
      
              if (sMainThreadHandler == null) {
                  sMainThreadHandler = thread.getHandler();
              }
            ...
              Looper.loop();
      
              throw new RuntimeException("Main thread loop unexpectedly exited");
          }
      

      难道子线程使用Handler就活该这么麻烦吗?也不是,Android提供了HandlerThread类,封装了Looper相关操作,十分方便。

    • 在解决上个问题的时候,我们知道在主线程的main方法中调用了Looper.loop(),而loop()是无限循环的,那不是阻塞主线程了吗?

      这里确实阻塞住了,可以看到如果loop()方法执行完,就会抛出运行时异常,然后程序就运行完了。

      通过getHandler()方法找到对应的Handler,即H。

             public void handleMessage(Message msg) {
                  if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
                  switch (msg.what) {
                      case LAUNCH_ACTIVITY: {
                          Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
                          final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
      
                          r.packageInfo = getPackageInfoNoCheck(
                                  r.activityInfo.applicationInfo, r.compatInfo);
                          handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
                          Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                      } break;
                      case RELAUNCH_ACTIVITY: {
                          Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityRestart");
                          ActivityClientRecord r = (ActivityClientRecord)msg.obj;
                          handleRelaunchActivity(r);
                          Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                      } break;
                      case PAUSE_ACTIVITY: {
                          Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
                          SomeArgs args = (SomeArgs) msg.obj;
                          handlePauseActivity((IBinder) args.arg1, false,
                                  (args.argi1 & USER_LEAVING) != 0, args.argi2,
                                  (args.argi1 & DONT_REPORT) != 0, args.argi3);
                          maybeSnapshot();
                          Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                      } break;
                ...
      

      通过H的case可以发现,Android的事件比如Activity的生命周期、广播、内存低等各个事件都在。主线程的运行就是处理各个消息,没有消息的时候会阻塞,但是不会ANR。造成ANR的原因一般当前事件没有及时得到处理。而阻塞状态下,新消息到达,就会唤醒主线程进行处理。

      同时,由于主线程阻塞,会释放CPU资源进入休眠状态,并不会消耗大量CPU资源。

    相关文章

      网友评论

        本文标题:Handler的工作原理

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