Handler源码解析

Handler是Android中引入的一种让开发者参与处理线程中消息循环的机制。我们在使用Handler的时候与Message打交道最多,Message是Hanlder机制向开发人员暴露出来的相关类,可以通过Message类完成大部分操作Handler的功能。

说Handler之前先看看Looper。
MessageQueue 是存放Message的消息队列,只是一个容器,而Looper 则是让MessageQueue循环动起来。

默认下创建一个线程,线程里面是没有消息队列的,如果想用消息队列MessageQueue,就需要通过Looper进行绑定。下面是一个简单的例子:

class LooperThread extends Thread {
    public Handler mHandler;
 
    public void run() {
        Looper.prepare();
 
        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                // process incoming messages here
             }
         };
 
        Looper.loop();
    }
}

可以看见Thread通过Looper.prepare() 和 Looper.loop()两个静态方法运行。

从源码里看 Looper的构造函数是private,则说明Looper不能再外部实例化。就可以猜测到Looper和Thread是一一对应的。

    private Looper(boolean quitAllowed) {
        //实例化MessageQueue。
        mQueue = new MessageQueue(quitAllowed);
        //获取当前线程。
        mThread = Thread.currentThread();
    }

看一下Looper.prepare()方法:

  /** Initialize the current thread as a looper.
      * This gives you a chance to create handlers that then reference
      * this looper, before actually starting the loop. Be sure to call
      * {@link #loop()} after calling this method, and end it by calling
      * {@link #quit()}.
      */
    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() 时候将Looper存起来,存在一个叫ThreadLocal 里面。获取的时候也是通过sThreadLocal.get() 来获取。上面提过Message和Thread是一一对应的,也就是说一个线程只能拥有一个Looper,所以在prepare时候先通过sThreadLocal.get()来获取Looper,如果是线程刚进来那是没有Looper的所以返回的是null,接着把改Looper存起来。如果有存在则抛出"Only one Looper may be created per thread".

// sThreadLocal.get() will return null unless you've called prepare().
    static final ThreadLocal sThreadLocal = new ThreadLocal();

Looper.prepare()调用完之后Looper就准备好了,接着就可以通过Looper.loop() 让MessageQueue循环动起来。loop()的源码:

/**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the 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.");
        }

        //获取当前线程的MessageQueue。
        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 (;;) {
            //获取MessageQuene消息队列的消息.
            Message msg = queue.next(); // might block

            //如果消息队列没有消息,则return,即阻塞在这里,等待获取Message。
            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 是一个Handler,这个意思是让改Message关联的Handler通过dispatchMessage()处理Message。
            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();
        }
    }

Handler 构造函数

Handler 是暴露给外部调用者使用,Handler有多个构造函数.

  • public Handler()

  • public Handler(Callback callback)

  • public Handler(Looper looper)

  • public Handler(Looper looper, Callback callback)

第1,2个构造函数是没有传Looper的,他将获取该线程的Looper和MessageQueue消息队列.

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

第3,4构造函数有传Looper,这两个构造函数会将该Looper保存到名为mLooper的成员字段中

public Handler(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

第2,4构造函数还传入一个Callback回调函数.是一个接口

public interface Callback {
        public boolean handleMessage(Message msg);
    }

Handler.Callback是用来处理Message的一种手段,在构造函数中传递Callback,则可以处理Message,如果返回的是true,则不再往下执行,起到拦截的效果。如果构造函数没有传递Callback,则应在Handler中重写handleMessage方法。

sendMessage 发送消息

在线程中可以通过sendMessage XXX方式往消息队列中添加Message。

  • sendMessage(Message msg):
  • sendMessageDelayed(Message msg, long delayMillis):
  • sendMessageAtTime(Message msg, long uptimeMillis) :
  • sendEmptyMessage(int what)
  • sendEmptyMessageDelayed(int what, long delayMillis)
  • sendEmptyMessageAtTime(int what, long uptimeMillis) :

通过看Handler源码可以知道,最终都是调用sendMessageAtTime方法。而在sendMessageAtTime中通过enqueueMessage方法将Message放入消息队列中。

Handler源码解析_第1张图片
sendMessage.png
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) {
        //将Message的target绑定为当前的Handler 
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

  • msg.target = this : 将Message的target绑定为当前的Handler .

  • queue.enqueueMessage(msg, uptimeMillis): queue 是当前Handler的消息队列MessageQueue.通过queue.enqueueMessage将Message放入消息队列。

post 方式发送消息

  • post(Runnable r)

  • postAtTime(Runnable r, long uptimeMillis)

  • postAtTime(Runnable r, Object token, long uptimeMillis)

  • postDelayed(Runnable r, long delayMillis)

    其中post 和 postDelayed 最后还是调用sendMessageDelayed方法。postAtTime最后调用sendMessageAtTime方法,最终的调用和sendMessage一样。

public final boolean post(Runnable r){
  return  sendMessageDelayed(getPostMessage(r), 0);
}

可以看到内部调用了getPostMessage方法,该方法传入一个Runnable对象,得到一个Message对象,getPostMessage的源码如下:

 private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }

通过上面的代码我们可以看到在getPostMessage方法中,我们创建了一个Message对象,并将传入的Runnable对象赋值给Message的callback成员字段,然后返回该Message,然后在post方法中该携带有Runnable信息的Message传入到sendMessageDelayed方法中。

dispatchMessage

在Looper中可以知道在Looper.loop()中最后通过msg.target.dispatchMessage(msg)来处理Message。

看一下dispatchMessage的源码:

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

post方式

这其中,首先判断msg.callback是否为空,msg.callback是一个Runnable对象,如果不为null,则说明这是通过post的方式发送消息。内部通过 handleCallback(msg)方式执行。

    private static void handleCallback(Message message) {
        message.callback.run();
    }

这样就会执行message.callback.run(),也就是Runnable的run方法

sendMessage方法

如果msg.callback返回有null,则是通过sendMessageXXX方式发送消息。

这里面接着判断mCallback是否有值,即构造函数中是否传Callback,如果有就会调用Callback中的handleMessage,如果没有就会调用Handler中的handleMessage。

总结

综合上述:handler 提供3中方式处理消息,首先先判断是否是post方式,先尝试Post的Runnable的run方法。

接着尝试构造函数的handleMessage方法,最后调用handler的handleMessage方法。

你可能感兴趣的:(Handler源码解析)