美文网首页
Handler、Looper、Message、MessageQu

Handler、Looper、Message、MessageQu

作者: ArcherZang | 来源:发表于2020-03-19 10:37 被阅读0次
    1. Message是什么
      Message implements Parcelable
      其构造方法是没有参数,注释也推荐我们使用obtain()构建
      通过重载static方法obtain和recycleUnchecked知道其有几个重要的参数
      集合平时的使用以及注释,其中大部分参数我们知道他的用途
      说说不常见的 flags标记当前message状态,包括是否支持异步
      when什么时候发送//TO do
      gCheckRecycle判断是否在回收正在使用的messsage时抛出异常IllegalStateException小于LOLLIPOP不能抛
      最重要的4个静态变量:
      sPoolSync是对象锁,虽然是Object,synchronized使用在链式加减、取出和新增的时候使用
      sPoolSize当前回收池大小
      MAX_POOL_SIZE是回收池最大值
      sPool当前链式最顶层和Message对象内部的next组成了全局唯一的回收池(范围是当前进程)
      应该是message在android内部使用很频繁,而java不是立马进行垃圾回收的所以建立一个回收池;
      如果不是使用obtain()就让回收池失去了意义。
        int flags /*package*/
        long when /*package*/
        public int what
        public int arg1
        public int arg2
        Bundle data
        Runnable callback
        Message next
        Handler target
        /**
        * An arbitrary object to send to the recipient.  When using
        * {@link Messenger} to send the message across processes this can only
        * be non-null if it contains a Parcelable of a framework class (not one
        * implemented by the application).   For other data transfer use
        * {@link #setData}.
        *
        * <p>Note that Parcelable objects here are not supported prior to
        * the {@link android.os.Build.VERSION_CODES#FROYO} release.
        */
        public Object obj;
        /**
        * Optional Messenger where replies to this message can be sent.  The
        * semantics of exactly how this is used are up to the sender and
        * receiver.
        */
        public Messenger replyTo
        /**
        * Optional field indicating the uid that sent the message.  This is
        * only valid for messages posted by a {@link Messenger}; otherwise,
        * it will be -1.
        */
        public int sendingUid = -1
    
        public static final Object sPoolSync = new Object();
        private static Message sPool;
        private static int sPoolSize = 0;
        private static final int MAX_POOL_SIZE = 50;
    
        private static boolean gCheckRecycle = true;
    
    1. Handler
      因为不是数据载体,所以不能直接像上面一样分析
      通常我们会new一个Handler,所以我们先分析构造方法
      不带Looper的构造方法最终会走到Handler(Callback callback, boolean async)
      带Looper最终会走到Handler(Looper looper, Callback callback, boolean async)
      先说一下他们的共同点callback和async没有参数默认值null和false;
      区别:
      不带looper:mLooper = Looper.myLooper();mQueue = mLooper.mQueue;
      带looper:mLooper = looper;mQueue = looper.mQueue;
      那么Looper.myLooper()从Looper的sThreadLocal.get()获取;这里有一个前提是不带looper的必须在UI线程创建;
      而sThreadLocal.get()给出了最好的答案,mLooper == null会抛出异常;
      那么是谁在UI线程中创建了myLooper()
        /**
        * 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());
               }
           }
    
           mLooper = Looper.myLooper();
           if (mLooper == null) {
               throw new RuntimeException(
                   "Can't create handler inside thread " + Thread.currentThread()
                           + " that has not called Looper.prepare()");
           }
           mQueue = mLooper.mQueue;
           mCallback = callback;
           mAsynchronous = async;
        }
    
        /**
        * Use the provided {@link Looper} instead of the default one and take a callback
        * interface in which to handle messages.  Also 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 conditions such as display vsync.
        *
        * @param looper The looper, must not be null.
        * @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(Looper looper, Callback callback, boolean async) {
          mLooper = looper;
          mQueue = looper.mQueue;
          mCallback = callback;
          mAsynchronous = async;
        }
    
    1. Looper.prepareMainLooper();
      这个方法在ActivityThread的Main方法中调用(//TODO回头贴链接)
      prepare(false)方法里调用了sThreadLocal.set(new Looper(false))
      new Looper(false)新建了MessageQueue要注意UI线程false,同时mThread = Thread.currentThread();
      然后设置sMainLooper = myLooper(),sMainLooper一般sdk用来检测当前线程是否是主线程即UI线程;
      所以我们总结一下handler的创建方式:
      主线程:Handler handler = new Handler()不带looper的三种方法都可以
      Handler handler = new Handler(Looper.sMainLooper)带looper的三种方法都可以
      其他线程:Looper.prepare();Handler handler = new Handler()不带looper的三种方法都可以,不要忘了前面那句
      Handler handler = new Handler(Looper.prepare())带looper的三种方法都可以

      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));
       }
      
       private Looper(boolean quitAllowed) {
           mQueue = new MessageQueue(quitAllowed);
           mThread = Thread.currentThread();
       }
      
    2. handler.sendMessage()

      handler.post(Runnable r)所有类似的post方法都是调用getPostMessage方法封装成message发送
      handler.sendEmptyMessage(int what)所有类似的sendEmptyMessage方法都是调用Message msg = Message.obtain()生成msg后把所有参数都赋值给新生成的msg后发送
      关于sendMessage这里有4种方法:
      前3个是往下调用关系,sendMessageAtTime和sendMessageAtFrontOfQueue都直接调用enqueueMessage:

      • —> sendMessage(Message msg),调用下一个方法参数delayMillis=0
      • —> sendMessageDelayed(Message msg, long delayMillis)调用下一个方法参数uptimeMillis=SystemClock.uptimeMillis() + delayMillis
      • —> sendMessageAtTime(Message msg, long uptimeMillis)
      • sendMessageAtFrontOfQueue(Message msg)是直接放到队列前面
        ——————————————————————————————这里分割
      • —> enqueueMessage(queue, msg, uptimeMillis),最终都走了这个方法只不过sendMessageAtFrontOfQueue的参数uptimeMillis=0

      还有一个特殊点的message.sendToTarget(),因为他的target是Handler所以还是走sendMessage(Message msg)

       public void sendToTarget() {
           target.sendMessage(this);
       }
      
    3. enqueueMessage()
      // Handler.java
      当前Handler是否支持异步,如果支持修改message的flags属性,
      然后加入队列,这里的queue来自looper

      private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
          msg.target = this;
          if (mAsynchronous) {
              msg.setAsynchronous(true);
          }
          return queue.enqueueMessage(msg, uptimeMillis);
      }
      
    4. enqueueMessage(Message msg, long when)
      // MessageQueue.java
      mQuitting默认false,如果为true回收message,并且返回false;
      正常流程

      • 标记message在使用,将message.when重置为传入的when
      • (1)如果p == null || when == 0 || when < p.when,队列第一个messsage不是空,参数message的when=0且小于第一个messsage的when
      • (2)否则p!=null && when>0&&when < p.when,
        needWake必定为false,因为加入队列的message必定target不为空,
        无线for循环pre、p和p.next迭代获取p如果为空或者加入队列message的when小于p.when,就让msg.next = p以及pre.next = msg
      • 如果needWake=true,nativeWake(mPtr)注释说可以假定mPtr != 0;
        此方法的调用应该是来自native层,当然不排除package内的调用,因为java层正常添加的message都会有target,
      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;
      }
      
    5. Looper.loop()
      这个方法在ActivityThread的Main方法最后调用
      主要看无限for循环

      • 当前线程Looprt队列的next()获取Message msg
      • if (msg == null) return退出
      • mSlowDispatchThresholdMs 最大分发时间,log时间
        mSlowDeliveryThresholdMs 最大发送时间delivery time - post time,log时间
        thresholdOverride默认值0,通过adb设置
        这些不是很重要打log用
      • msg.target.dispatchMessage(msg);
      • msg.recycleUnchecked()
      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();
      
          // 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();
          }
      }
      
    6. Message next()
      final long ptr = mPtr
      如果ptr==0 直接返回空
      int pendingIdleHandlerCount = -1; // -1 only during first iteration
      int nextPollTimeoutMillis = 0;
      以下无限for循环:

      • 如果nextPollTimeoutMillis != 0,调用Binder.flushPendingCommands()

      • nativePollOnce(ptr, nextPollTimeoutMillis)
        阻塞nextPollTimeoutMillis毫秒,>0到达时间继续往下执行,0继续执行,-1永远停止

      • synchronized (this) 同步代码块--开始-------------

        • 设置 now = SystemClock.uptimeMillis();
          设置 Message prevMsg = null;
          设置 Message msg = mMessages;

        • IF 如果msg!=null并且msg.target==null,
          dowhile循环,
          do:会设置prevMsg = msg,msg = msg.next;
          while:msg != null && !msg.isAsynchronous(),就是msg为空或者异步退出当前循环,
          msg是否异步取决与Handler是否有设置默认是false,如果没有handler就是msg自身的值;这个过程

        • 1 . IF 如果msg不为空:
          (1)if 如果now < msg.when:
          计算nextPollTimeoutMillis取msg.when - now和 Integer.MAX_VALUE之间最小值
          (2)else :
          mBlocked = false
          如果prevMsg != null,prevMsg.next = msg.next
          如果prevMsg == null,mMessages = msg.next;并且清空msg.next,然后标记msg.markInUse(),最后返回,因为回收的msg会进入回收池

        • 2 . ELSE :
          nextPollTimeoutMillis = -1

        • 如果mQuitting=true,调用dispose(),dispose()内部执行如果mPtr != 0销毁底层队列且mPtr = 0,完成dispose()方法后返回null;

        • 如果pendingIdleHandlerCount < 0 && (mMessages == null || now < mMessages.when)设置pendingIdleHandlerCount = mIdleHandlers.size();
          这是为了第一次循环时队列中没有msg或者msg没有到执行时间,因为pendingIdleHandlerCount默认-1

        • 如果pendingIdleHandlerCount <= 0那么mBlocked = true并且跳过本次循环;

          因为此时nextPollTimeoutMillis = -1,那么调用nativePollOnce(ptr, nextPollTimeoutMillis)就会阻塞

        • 如果IdleHandler[] mPendingIdleHandlers = null,就new一个数组,数组大小在pendingIdleHandlerCount和mIdleHandlers.size()直接选择最大值

        • 将ArrayList<IdleHandler> mIdleHandlers转成数组加入mPendingIdleHandlers

      • synchronized (this) 同步代码块--结束-------------

      • 内部for循环int i = 0; i < pendingIdleHandlerCount; i++
        迭代数组IdleHandler[] mPendingIdleHandlers
        每次keep默认值为false
        每次keep = idler.queueIdle(),获取当前数组item,然后把item的queueIdle()返回值给keep
        如果keep=flase,同步从数组移出当前item

        源码里重写IdleHandler类时都会返回false,因为如果返回ture,在loop空闲时会一直调用mIdleHandlers里的元素,这样cpu就得不到休息了

      • pendingIdleHandlerCount = 0;
        nextPollTimeoutMillis = 0;如果nativePollOnce(ptr, nextPollTimeoutMillis),不会停止会继续走下去

      无限for循环结束

      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;
          }
      }
      
      /**
      * Callback interface for discovering when a thread is going to block
      * waiting for more messages.
      */
      public static interface IdleHandler {
         /**
         * Called when the message queue has run out of messages and will now
         * wait for more.  Return true to keep your idle handler active, false
         * to have it removed.  This may be called if there are still messages
         * pending in the queue, but they are all scheduled to be dispatched
         * after the current time.
         */
         boolean queueIdle();
      }
      
    7. msg.target.dispatchMessage(msg);
      指向Handler内部的dispatchMessage(Message msg)

      • IF msg.callback不等于空就调用
      • ELSE
        • IF mCallback != null
          如果mCallback.handleMessage(msg)=true,就return
        • 调用handleMessage(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);
          }
      }
      
    8. handleCallback(msg)

      如果message有callback优先处理,且不会经过handler的callback和handleMessage

      private static void handleCallback(Message message) {
          message.callback.run();
      }
      
      Message
      Runnable callback;
      
    9. mCallback.handleMessage(msg)

      如果没有给msg设置callback

      就调用handler的mCallback的handleMessage

      ​ 如果返回true就不调用handleMessage(msg),直接return

      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);
      }
      
    1. handleMessage(msg)

      子类重写用来处理消息

      如果msg.callback=null或者mCallback=null或者mCallback.handleMessage返回false

      就会调用,handler内部是空实现

    2. msg.recycleUnchecked()

      除了flags = FLAG_IN_USE和sendingUid = -1

      其他全部置为空或者0

      回收池增加,同时将Message持有的msg给当前对象的next,并且将当前对象置顶

      /**
      * 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++;
              }
          }
      }
      

    相关文章

      网友评论

          本文标题:Handler、Looper、Message、MessageQu

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