Handler机制的流程分析

Handler是Android系统中用于两个线程或者进程通信的一种机制,其实底层也是通过Binder机制来实现的。Handler涉及的类有Message, MessageQueue, Looper, Handler, Messenger.我们先来说一下Message.

Message是一个用于将需要传递的信息打包成能通过Handler机制传递的的包裹类。就像以前写信一样,需要一个信封和邮票,将信件打包成一个能传递的可邮递信件。我们先来看一下它的主要的成员变量。

    /**
     * User-defined message code so that the recipient can identify 
     * what this message is about. Each {@link Handler} has its own name-space
     * for message codes, so you do not need to worry about yours conflicting
     * with other handlers.
     */
    public int what;

    /**
     * arg1 and arg2 are lower-cost alternatives to using
     * {@link #setData(Bundle) setData()} if you only need to store a
     * few integer values.
     */
    public int arg1; 

    /**
     * arg1 and arg2 are lower-cost alternatives to using
     * {@link #setData(Bundle) setData()} if you only need to store a
     * few integer values.
     */
    public int arg2;

    /**
     * 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}.
     * 
     * 

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; /*package*/ Bundle data; /*package*/ Handler target; /*package*/ Runnable callback; // sometimes we store linked lists of these things /*package*/ Message next; private static Message sPool;

首先呢我们来说一下,Message用来携带信息的字段。arg1和arg2是用来传递整型数据的,当你只需要传递一个或两个整型数据的时候可以通过这两个成员变量来传递。当你需要传递一个对象时,可以使用obj这个成员变量来实现。当然你也可以打包成Bundle对象data来传递。

replyTo是一个Messenger对象,Messenger是对Message和Binder机制的一种封装,让Message可以通过IMessenger(在我的直观认为IMessenger是一个用于传递Message对象的AIDL接口)。关于AIDL的使用可以到慕课网去学习AIDL小白成长记事

target是用来标志该Message的收件人是谁,callback是用来处理Message的,如果callback,则直接运行callback的run方法(方法里面是对传递过来的数据的处理)。sPool是用于减少Message的创建,而是复用原来已经创建的Message对象,从而减少内存的消耗,提高性能。

接下来我们来看一下Message中比较重要的方法。

    /**
     * Return a new Message instance from the global pool. Allows us to
     * avoid allocating new objects in many cases.
     */
    public static Message obtain() {
        synchronized (sPoolSync) {
            if (sPool != null) {
                Message m = sPool;
                sPool = m.next;
                m.next = null;
                m.flags = 0; // clear in-use flag
                sPoolSize--;
                return m;
            }
        }
        return new Message();
    }

    /** 
     * Obtains a Bundle of arbitrary data associated with this
     * event, lazily creating it if necessary. Set this value by calling
     * {@link #setData(Bundle)}.  Note that when transferring data across
     * processes via {@link Messenger}, you will need to set your ClassLoader
     * on the Bundle via {@link Bundle#setClassLoader(ClassLoader)
     * Bundle.setClassLoader()} so that it can instantiate your objects when
     * you retrieve them.
     * @see #peekData()
     * @see #setData(Bundle)
     */
    public Bundle getData() {
        if (data == null) {
            data = new Bundle();
        }
        
        return data;
    }

    /** 
     * Like getData(), but does not lazily create the Bundle.  A null
     * is returned if the Bundle does not already exist.  See
     * {@link #getData} for further information on this.
     * @see #getData()
     * @see #setData(Bundle)
     */
    public Bundle peekData() {
        return data;
    }

    /**
     * Sets a Bundle of arbitrary data values. Use arg1 and arg2 members
     * as a lower cost way to send a few simple integer values, if you can.
     * @see #getData() 
     * @see #peekData()
     */
    public void setData(Bundle data) {
        this.data = data;
    }

    public void setTarget(Handler target) {
        this.target = target;
    }

    /**
     * Sends this Message to the Handler specified by {@link #getTarget}.
     * Throws a null pointer exception if this field has not been set.
     */
    public void sendToTarget() {
        target.sendMessage(this);
    }

obtain()方法是用于创建Message对象的,结合成员sPool可以避免过多地创建Message对象。obtain()方法有很多的重载,其它的都是通过在内部调用这个无参obtained()方法,然后根据相应参数设置相应成员变量的值。

getData()和peekData()是获取Message中的Bundle的对象的引用,getData()返回的Bundle对象一定是不为空的(如果为空它会帮你创建一个新的Bundle对象并返回),而peekData()会直接返回Message中的Bundle对象的引用,不管是否为空。setData()则是设置Message中Bundle的引用。

sendToTarget()是将该Message对象交给Handler去发送。其实Message对象是通过Handler来传递最后再回到Handler去处理,有的同学可能会有疑问:为什么数据要绕一圈再回到Handler手中?在Java中每个线程或进程都有自己独立的工作内存空间,这意味着一个线程/进程的工作内存中间中的数据或操作对另一个线程/进程是不可见的,即使我们在一个线程中改变了另一个线程中的一个对象,也有可能会出现另一个线程无法获得这个更改的信息(关于更多可以去了解Java内存模型和Java多线程通信)。Handler的出现是用于解决两个线程或进程之间的通讯的--通常是在另外一个线程中处理任务,然后将处理的数据返回给本线程去处理。其实这里是可以使用接口来实现数据返回的,至于进程间也是可以自己去实现的,但是Handler是Google专门编写的,做了大量的优化,如果自己去实现就需要自己去处理性能优化问题,这不是每个人都能做到的。

接下来说一下MessageQueue

这是一个存储Message的队列,会在Looper.prepare()方法中创建。

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

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

    void quit(boolean safe) {
        if (!mQuitAllowed) {
            throw new IllegalStateException("Main thread not allowed to quit.");
        }

        synchronized (this) {
            if (mQuitting) {
                return;
            }
            mQuitting = true;

            if (safe) {
                removeAllFutureMessagesLocked();
            } else {
                removeAllMessagesLocked();
            }

            // We can assume mPtr != 0 because mQuitting was previously false.
            nativeWake(mPtr);
        }
    }

enqueueMessage()方法是将Message添加进MessageQueue中,next()是从MessageQueue中取出Message消息。quit(boolean)方法是用于移除MessageQueue中的消息

Looper

Looper的任务就是不断地从MessageQueue中取出消息,然后交给Handler去处理。每个线程只能拥有一个Looper对象,Looper中保存有一个MessageQueue对象。

需要关注的成员变量:

    // sThreadLocal.get() will return null unless you've called prepare().
    static final ThreadLocal sThreadLocal = new ThreadLocal();
    private static Looper sMainLooper;  // guarded by Looper.class

    final MessageQueue mQueue;

ThreadLocal用于为线程存储Looper对象,防止多个线程操作一个Looper对象。sMainLooper这是主线程的Looper对象,主线程会自动创建它,所以在主线程中我们不需要调用Looper.prepare()和Looper.loop()方法。

Looper中重要的方法:

prepare()
loop()
myLooper()
prepareMainLooper()
getMainLooper()
myLooper()
quit()

首先我们来看一下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));
    }

其实是调用了重载的prepare()方法,最终还是调用new Looper(quitAllowed)方法,我们来看一下具体实现

    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

很明显的只是创建了一个MessageQueue对象,并且保存了Looper对应的线程的引用。

接着我们来看一下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.");
        }
        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();
        }
    }

首先是判空检查, 然后是一个死循环for(;;),在这个死循环中不断调用MessageQueue的next()方法来取出消息队列中的消息,然后将消息Message交给Handler去分发处理。msg.target.dispatchMessage(msg),其实msg.target就是一个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);
        }
    }

msg.callback是一个Runnable对象,如果不为空,说明这个message是通过post(Runnable)来发送的。然后调用handleCallback来处理Runnable类型的消息。如果不是post(Runnable),而是使用sendMessage(),则判断是否已经设置了相应的处理接口,如果设置了则交给接口(Callback是一个接口,里面定义了handleMessage()方法用于处理消息)去处理。不然就交给Handler本身的处理消息的方法。

myLooper()返回当前线程的Looper对象

    /**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

prepareMainLooper和getMainLooper分别是创建主线程的Looper对象和获取主线程的Looper对象。其实prepareMainLooper这个方法是不用我们来调用的,系统会自动调用,这就是为什么我们在主线程中不需要调用Looper.prepare和Looper.loop方法了。

最后介绍的是退出消息机制的方法quit()和quitSafely()

    /**
     * Quits the looper.
     * 

* Causes the {@link #loop} method to terminate without processing any * more messages in the message queue. *

* Any attempt to post messages to the queue after the looper is asked to quit will fail. * For example, the {@link Handler#sendMessage(Message)} method will return false. *

* Using this method may be unsafe because some messages may not be delivered * before the looper terminates. Consider using {@link #quitSafely} instead to ensure * that all pending work is completed in an orderly manner. *

* * @see #quitSafely */ public void quit() { mQueue.quit(false); } /** * Quits the looper safely. *

* Causes the {@link #loop} method to terminate as soon as all remaining messages * in the message queue that are already due to be delivered have been handled. * However pending delayed messages with due times in the future will not be * delivered before the loop terminates. *

* Any attempt to post messages to the queue after the looper is asked to quit will fail. * For example, the {@link Handler#sendMessage(Message)} method will return false. *

*/ public void quitSafely() { mQueue.quit(true); }

实际上就是调用MessageQueue的quit()方法,而MessageQueue的quit方法就是移除MessageQueue中所有的消息。我们在quit()的注释中看到一句很重要的话

Any attempt to post messages to the queue after the looper is asked to quit will fail.
在调用了Looper的quit()方法之后,任何想要往MessageQueue中添加消息的操作都会失败。

quitSafely会等到MesageQueue中的消息都得到处理之后再做清理工作,而quit则是直接去清理。

接下来说Handler,Handler的主要成员变量

    final MessageQueue mQueue;
    final Looper mLooper;
    final Callback mCallback;
    IMessenger mMessenger;

定义了一个MessageQueue的引用mQueue,其实这个是用在sendMessage或者post(Runnable)中将消息添加进MessageQueue的。mLooper用来获取MessageQueue对象。mCallback用来处理消息的接口。IMessenger这是对Binder的一个封装。

重要的方法


    /**
     * Callback interface you can use when instantiating a Handler to avoid
     * having to implement your own subclass of Handler.
     *
     * @param msg A {@link android.os.Message Message} object
     * @return True if no further handling is desired
     */
    public interface Callback {
        public boolean handleMessage(Message msg);
    }
    
    /**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(Message 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);
        }
    }

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

     /**
     * Returns a new {@link android.os.Message Message} from the global message pool. More efficient than
     * creating and allocating new instances. The retrieved message has its handler set to this instance (Message.target == this).
     *  If you don't want that facility, just call Message.obtain() instead.
     */
    public final Message obtainMessage(){
        return Message.obtain(this);
    }

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

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

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

可以看到Callback是一个接口,定义了handleMessage方法。而Handler中也定义了一个handleMessage方法,但是没有做任何的操作,所以我们应该重写该方法才能实现消息处理。

dispatchMessage是用来分发消息的,首先判断是否是Runnable类型的消息,如果是则调用handleCallback来处理。其实handleCallback就是单纯的调用了Runnable的run方法。如果只是单纯的Message,则判断mCallback是否为空,不为空则交给Callback去处理。否则交给Handler的handleMessage去处理。

obtainMessage实际上也是调用Message的obtain()方法来创建Message对象。

关于sendMessage等方法我就不放出来了,这些方法最终还是调用sendMessageAtTime方法,可以看到在sendMessageAtTime中调用了enqueueMessage方法,而enqueueMessage调用的是MessageQueue的enqueueMessage方法,这样就可以将Message添加进消息队列中了。看源代码可以知道,post(Runnable)也还是会创建并发送Message消息的,只不过这个Message的callback不为空而已。

搞了这么多,还没有说明Handler的整个流程。我们来总结一下:

使用Handler

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

Handler的处理流程

首先hander.sendMessage()或者post(Runnable),这些方法最终都是调用sendMessageAtTime()方法。sendMessageAtTime进而调用MessageQueue的enqueueMessage将消息添加到消息队列。而这时候Looper.loop()是一个监听MesageQueue的死循环。Looper会调用MessageQueue的next()方法不断从消息队列取出消息,然后通过Message获取Handler的引用并且调用Handler的dispatchMessage方法来分发处理消息。

其实Handler还可以通过Messenger来传递消息

/**
 * Reference to a Handler, which others can use to send messages to it.
 * This allows for the implementation of message-based communication across
 * processes, by creating a Messenger pointing to a Handler in one process,
 * and handing that Messenger to another process.
 *
 * 

Note: the implementation underneath is just a simple wrapper around * a {@link Binder} that is used to perform the communication. This means * semantically you should treat it as such: this class does not impact process * lifecycle management (you must be using some higher-level component to tell * the system that your process needs to continue running), the connection will * break if your process goes away for any reason, etc.

*/ public final class Messenger implements Parcelable { private final IMessenger mTarget; /** * Create a new Messenger pointing to the given Handler. Any Message * objects sent through this Messenger will appear in the Handler as if * {@link Handler#sendMessage(Message) Handler.sendMessage(Message)} had * been called directly. * * @param target The Handler that will receive sent messages. */ public Messenger(Handler target) { mTarget = target.getIMessenger(); } /** * Send a Message to this Messenger's Handler. * * @param message The Message to send. Usually retrieved through * {@link Message#obtain() Message.obtain()}. * * @throws RemoteException Throws DeadObjectException if the target * Handler no longer exists. */ public void send(Message message) throws RemoteException { mTarget.send(message); } /** * Retrieve the IBinder that this Messenger is using to communicate with * its associated Handler. * * @return Returns the IBinder backing this Messenger. */ public IBinder getBinder() { return mTarget.asBinder(); } /** * Create a Messenger from a raw IBinder, which had previously been * retrieved with {@link #getBinder}. * * @param target The IBinder this Messenger should communicate with. */ public Messenger(IBinder target) { //这一句你会觉得是曾相识吧,其实就是AIDL机制 mTarget = IMessenger.Stub.asInterface(target); } }

通过Messenger传递消息,消息不会进入MessageQueue而是直接传递到了Handler中,我们只需直接在Handler的handleMessage中处理该消息即可。两个进程间可以通过Messenger来传递消息,只需要获得对方进程的Messenger对象即可。通过Messenger的send(Message)方法来隐藏底层的Binder机制的所有实现。

你可能感兴趣的:(Handler机制的流程分析)