Handler源码分析

Handler主要用于线程切换,一个典型的应用场景是:子线程通过Handler更新主线程UI
本文将从源码上来介绍Handler的实现原理

Handler的工作流程

先看一张图:

Handler工作流程

主要流程如下:

  • 构造Message对象
  • 通过Handler将Message发送到MessageQueue
  • Looper从MessageQueue里取出Message对象
  • Looper调用Message对象里保存的Handler对象的dispatchMessage方法将Message的处理移交给Handler

那么Looper和MessageQueue是哪来的呢?看一下Handler的构造方法:

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();//获取Handler所在线程的Looper。
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;//获取Looper里的MessageQueue
        mCallback = callback;
        mAsynchronous = async;
    }

如果mLooper为空则直接抛异常了,所以如果不是在主线程创建Handler之前一定要在子线程里调用Looper.prepare()准备好一个Looper。Looper.prepare()会调用Looper的构造方法创建一个Looper,在Looper的构造方法中又创建了一个MessageQueue。

下面通过源码来看这几个步骤是如何实现的

1.构造Message对象

通过Handler对象构造
通过Message的静态方法构造

或者,直接

Message message = new Message();

各种方式在使用效果上最后的差别不大,任选其一即可。

2.通过Handler将Message发送到MessageQueue

//Handler
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;//注意这一句,将target对象指向当前handler
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);//将Message入消息队列
    }

左右的发送消息的方法最终都调用到了这个方法,顾名思义,这个方法将Message对象添加到MessageQueue队列,在入队之前,将message的target对象赋值为当前handler对象,最后会通过这个target对象来处理这个message。

//MessageQueue
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;
    }

可以看到,MessageQueue其实是一个单链表,所以很多操作都是单链表的操作。如果p==null(当前队列为空)或者when==0(通过sendMessageAtFrontOfQueue方法发送的消息)或者when<p.when的时就将此消息插入到队的头部,否则按时间先后顺序入队,这里的时间是什么时间呢?看下面代码,其实是SystemClock.uptimeMillis() + delayMillis,也就是当前开机时间的毫秒数加上我们设置的延时。

//Handler
public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

3.Looper从MessageQueue里取出Message对象

当创建好Looper后,会调用Looper.loop()方法不断的从MessageQueue里读取Message,如果是主线程,那么Looper.loop()方法在系统创建进程的时候就已经调用过了,如果在子线程则需要自己调用。

//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;

        ...省略

        for (;;) {
            //从队列里取出消息
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

            ...省略

            try {
                //将msg的处理移交给Handler
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            ...省略 
        }
    }

Message msg = queue.next(); // might block 通过一个无限的for循环中通过MessageQueue.next()读消息,如果队列没有消息则阻塞。在next方法中,如果队首的消息执行时间还没到,就设置一个等待时间,如果到了就从链表里取出来,然后返回。

//MessageQueue
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.
      ...
      for(;;){
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }

            nativePollOnce(ptr, nextPollTimeoutMillis);
            synchronized (this) {
      ...
                    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;
                    }
      ...
              }
      }
    }

4.调用Handler的dispatchMessage方法将Message的处理移交给Handler

在Loopermsg.target.dispatchMessage(msg)让Handler去处理,这里的target就是在调用Handler.的enqueueMessage方法时赋值得,忘记了可以去步骤2里再看一下。

至此,处理流程又回到了Handler的dispatchMessage方法里,逻辑很简单,一个细节要注意,如果mCallback不为空,是不会调用handleMessage,这里mCallback是在创建Handler的时候就传进来的,所以使用Handler处理消息,要么在创建Handler的时候传入一个Callback,要么重写handleMessage方法。

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

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

    /**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(Message msg) {
    }
IT文库 » Handler源码分析
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址