[Android] 从源码分析 Handler 消息机制

前言

上篇文章叙述了 Handler 的用法和避免因为不当使用 Handler 引起内存泄露的方法。这篇文章将从源码分析 Handler 消息机制的实现。

Looper

我们知道要想使用 Handler 就必须在当前线程里初始化 Looper,我们初始化 Looper 的做法是调用 Looper.prepare() 方法。然后调用 Looper.loop() 方法。首先,我先来看 Looper.prepare() 的源码:

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

由上面源码可以看出,在 Looper 的 prepare() 方法里调用了 sThreadLocal.set(new Looper(quitAllowed))。sThreadLocal 的类型是 ThreadLocal 。 ThreadLocal 是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,数据存储以后,只能在指定的线程中可以获取到存储的数据,对于其他线程来说则无法获取到数据。这里通过 ThreadLocal 的 set 方法将一个 Looper 对象存储到当前线程中。

    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
        Printer logging = me.mLogging;
        if (logging != null) {
          logging.println(">>>>> Dispatching to " + msg.target + " " +
            msg.callback + ": " + msg.what);
        }

        msg.target.dispatchMessage(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();
      }
    }

由上述代码可以看出,Looper.loop() 方法的主体是一个死循环。只有当 MessageQueue 的 next() 方法返回 null 的时候才会跳出循环。但是 MessageQueue 的 next() 方法是一阻塞的方法,当 MessageQueue 中没有消息的时候 next() 方法会阻塞。当调用了 MessageQueue 的 quit 或者 quitSafely 方法时 MessageQueue 的 next 方法就会返回 null。

如果 MessageQueue 的 next 方法返回了新消息,将执行 msg.target.dispatchMessage(msg),这里的 msg.target是发送这条消息的 Handler 对象,这样 Handler 发送的消息最终交给他的 dispatchMessage 方法处理。而 Handler 的 dispatchMessage 方法是在创建 Handler 时所使用的 Looper 中执行的,所以将代码切换到了 Looper 所在的线程中执行了。

Handler 和 MessageQueue

先来看 Handler 的初始化

    public Handler() {
      this(null, false);
    }
    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 that has not called Looper.prepare()");
      }
      mQueue = mLooper.mQueue;
      mCallback = callback;
      mAsynchronous = async;
    }

由上面代码可以看出,在 Handler 初始化的时候会先通过Looper.myLooper 方法取出当前线程的 Looper,如果当前线程还没有初始化 Looper,将抛出异常。

Handler 的主要工作就是发送和处理消息。Handler 发送消息是通过 post 和 send 的一系列的方法来实现的。但他们最终都要调用 Handler 的 sendMessageAtTime 方法。

     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 的 sendMessageAtTime 方法会调用 enqueueMessage,而 enqueueMessage 调用了 MessageQueue 的 enqueueMessage 方法。

下面看 MessageQueue 的 enqueueMessage 方法:

     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("MessageQueue", 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;
     }

由上述代码可以看出,Handler 发送消息是向消息队列中插入一条消息, MessageQueue 的 next 方法会返回这条消息给 Looper 交给 Handler 处理。这时 Handler 的 dispatchMessage 方法会被调用,Handler 进入处理消息的阶段。
Handler 的 dispatchMessage 方法的实现如下所示:

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

在 Handler 处理消息的过程如下:

首先判断 Message 的 callBack 是否为空,不为空则调用 handleCallback 方法。callBack 实际是 Runnable 对象,而 handleCallback 方法则调用了 Runnable 的 run 方法。如果 Message 的 callBack 为空则判断 mCallBack 是否为空。不为空这调用它的 handleMessage 方法。mCallBack 是个接口,通过 CallBack 可以使用 Handler(Callback callback) 来创建 Handler 的对象,
而不用派生 Handler 的子类。最后调用 Handler 的 handlerMessage 方法处理消息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值