Handler的深入理解

179 阅读5分钟

Handler知其然而不知其所以然,主要遇见的问题,looper如何确定向哪个Handler发送消息?如何保证线程中只有一个looper和MessageQueue?延时消息如何发送之后如何唤醒?除了Callback???
第一个问题:首先要查看Looper类的loop方法,因为这个方法的作用就是向Handler发送消息。源码如下

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 {
            //调用消息target的dispatchMessage方法处理消息
            //通过查看得知Message的target是一个Handler对象,查看Message的target赋值的位置
                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();
        }
    }

接着应该看msg的target在哪赋值的?首先看Message这个类里面的赋值方法:有两个方法setTarget(Handler target)这个方法直接去赋值,但只在WifiMonitor和WifiP2pMonitor中使用,void recycleUnchecked()这个只是将target赋值为null。所以一般的Hanler并不会直接调用,因此考虑要查看其他类的对target的赋值,Handler有发送Message的作用,查看Handler发送Message的方法。会发现无论使用任何方法会调用boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis)这个方法

  private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
      //这一步将msg.target赋值为this,也就是说在handler向MessageQueue发送消息的时候
      //msg.targt就是自己本身,因此looper就会使用msg.target.dispatchMessage(msg)处理就会调到对应的Handler
      msg.target = this;
      if (mAsynchronous) {
          msg.setAsynchronous(true);
      }
      return queue.enqueueMessage(msg, uptimeMillis);
  }

我们可以在看一下Handler的dispatchMessage(Message msg)方法

 public void dispatchMessage(Message msg) {
      if (msg.callback != null) {
          handleCallback(msg);
      } else {
      //有回掉接口,则先调用接口,这个接口可自定义返回值,如果为true则不调用handleMessage(),这个是一个空方法,继承后可重写
          if (mCallback != null) {
              if (mCallback.handleMessage(msg)) {
                  return;
              }
          }
          handleMessage(msg);
      }
  }

第二个问题首先Looper的创建必须要调用private Looper(boolean quitAllowed),这个方法为私有方法,因此查看调用这个方法的只有 private static void prepare(boolean quitAllowed)这个方法,这个方法也是私有的,因此只能继续查看调用
prepare(boolean quitAllowed)的方法,调用这个方法的有两个,一个是

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

这也是我们常用的在子线程中使用Handler的一定要调用方法,另一个是

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

这个方法在两个类中被调用,一个是ActivityThread的main方法,这也解释了在Activity中不需要对Looper做特殊的操作,另一个是SystemServer的run方法。看一下prepare(boolean quitAllowed)的源码:

 private static void prepare(boolean quitAllowed) {
         //通过ThreadLocal获取当前Looper是否存在,如果存在则抛出运行时异常
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        //不存在则设置ThreadLocal,新建Looper
        sThreadLocal.set(new Looper(quitAllowed));
    }

private Looper(boolean quitAllowed)的源码是

private Looper(boolean quitAllowed) {
         //建立MessageQueue,因此一个线程中只有一个Looper和MessageQueue
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

第三个问题这个问题需要看一下MessageQueue的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 (;;) {
        //不为0就是说不是第一次赋值,有没到时间的message,去做一个刷新任务命令,是一个nativie方法
            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) {
                //还没到唤起的时间nextPollTimeoutMillis重新设置,将msg设定的时间减去当前的时间
                    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还可以使用使用如下方法:

  • public Handler()
  • public Handler(Callback callback)
  • public Handler(Looper looper)
  • public Handler(Looper looper, Callback callback)
  • public Handler(boolean async)
  • public Handler(Callback callback, boolean async)
  • public Handler(Looper looper, Callback callback, boolean async)
    这几个方法除了public Handler(Looper looper, Callback callback, boolean async)方法之外,其余最终会调用 public Handler(Callback callback, boolean async)。代码如下:
 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,MessageQueue,Callback
        mLooper = Looper.myLooper();
        //looper为空,则会抛出去运行异常
        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;
    }