Android Handler原理介绍

来源:互联网 发布:淘宝账号能改名吗 编辑:程序博客网 时间:2024/05/17 07:12

Andriod提供了Handler 和 Looper 来满足线程间的通信。Handler先进先出原则。Looper类用来管理特定线程内对象之间的消息交换(MessageExchange)。UIthread 通常就是main thread,而Android启动程序时会替Looper实例建立一个MessageQueue消息队列。


Looper


Activity启动的时候(OnCreate之前)就会创建一个Looper线程,由它来管理Looper线程里的MessageQueue(消息队列)。 UIThread线程通过Looper.prepare()创建唯一的Looper实例,然后创建该Looper实例中会同时创建一个MessageQueue对象;


对于Looper主要是prepare()loop()两个方法。


1.1prepare() 

因为Looper.prepare()在一个UiThread线程中只能调用一次,所以MessageQueue在一个UIThread线程中只会存在一个。


在Looper.java中


     /** 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()方法会首先判断主线程中是否存在Looper线程(对象),如果有,则抛出异常,如果没有则创建一个新的Looper对象(线程).


1.2loop()

接下来UIThread主线程中会调用Looper.loop()会让当前Looper线程进入一个无限循环,不断的从MessageQueue的队列中读取消息,然后调用msg.target.dispatchMessage(msg)方法分发消息。


在Looper.java文件代码如下

    /**     * 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;//1.此处是获取MessageQueue对象.                             //其实就是和MessageQueue产生一个关联,或者关系,     //为后续操作MessageQueue提供一个对象。        // 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 (;;) {                      //2.此处for无限循环很重要,也就是此处说明了Looper对象是一直无限的在操作MessageQueue            Message msg = queue.next(); // might block 每次循环都先从消息队列中取出一个消息            if (msg == null) {          //如果取出的消息为空,则表明当前MessageQueue没有消息。如果不为就将消息分发出去,进行处理。                // 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 {                msg.target.dispatchMessage(msg);//3.此处是将消息分发出去进行处理,可能你会想msg.target是谁呢?接下来的代码会展示。                //其实就是你在UIThread中创建的handler对象本身。                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();        }    }

这段代码太长了,看起来真是很麻烦,所以我觉着只要抓住我文中的1、2、3三处代码就足够了。总的来说Looper中的loop()方法就是无限的从Message中去取消息,然后判断消息是否为null,如果为空则继续去取消息,再判断是否为null。如果消息不为空就通过dispatchMessage方法将消息分发出去处理。


接下来我们看一下msg.target是个什么东西,首先从msg的定义我们可以看出是Message的一个实例,我们就看Message类


在Message.java中有如下的代码

/** * * Defines a message containing a description and arbitrary data object that can be * sent to a {@link Handler}.  This object contains two extra int fields and an * extra object field that allow you to not do allocations in many cases. * * <p class="note">While the constructor of Message is public, the best way to get * one of these is to call {@link #obtain Message.obtain()} or one of the * {@link Handler#obtainMessage Handler.obtainMessage()} methods, which will pull * them from a pool of recycled objects.</p> */public final class Message implements Parcelable {...../*package*/ Handler target;.....}

由此我们可以看出,原来msg.target就是Handler,也就是你在UIThread中创建的handler对象本身.至于这个msg.target在什么时候被赋值为handler对象本身的呢?后续讲解会解答这个问题.接下来我们继续看dispatchMessage。从上知道msg.target.dispatchMessage(msg)自然就是Handler.dispatchMessage(msg)。那么我们看一下Handler中的dispatchMessage方法


在Handler.java中

    /**     * 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);//有没有觉着此方法很熟悉?       //其实这就是你在创建Handler对象的时候所重写的handleMessage方法       //到此处我们知道了,原来是消息被取出来之后,       //就是调用我们的重写的handleMessage方法        }    }



2 MessageQueue

其实MessageQueue没有啥可说的,就是在创建Looper对象实例的时候,创建了该消息队列。他就是类似于水管的东西,只不过水管中装的是水,但是MessageQueue装的是一个一个的Message对象罢了。


Looper.java中

    /**     * Return the {@link MessageQueue} object associated with the current     * thread.  This must be called from a thread running a Looper, or a     * NullPointerException will be thrown.     */    public static @NonNull MessageQueue myQueue() {        return myLooper().mQueue;    }    private Looper(boolean quitAllowed) {        mQueue = new MessageQueue(quitAllowed);        mThread = Thread.currentThread();    }

在Looper的构造方法中,可以看出在创建Looper对象的时候,创建了MessageQueue对象。


Looper主要作用
1、LooperUIThread线程绑定,并且一个UIThread线程只有一个Looper实例。创建一个Looper实例过程中会创建一个MessageQueue对象。所以一个Looper实例也保证了只有一个MessageQueue实例。


2、Looper的loop()方法,不断从MessageQueue中取消息,交给消息的target属性的dispatchMessage去处理。

好了,我们的异步消息处理线程已经有了消息队列(MessageQueue),也有了在无限循环体中取出消息的Looper,现在缺的就是发送消息的对象了。接下来就是Handler的创建了.


3 Handler


3.1 创建Handler的实例的时候,在Handler构造方法,会首先得到当前线程中保存的Looper实例,进而与Looper实例中的MessageQueue关联。


在Handler.java中


    /**     * Use the {@link Looper} for the current thread with the specified callback interface     * and set whether the handler should be asynchronous.     *     * Handlers are synchronous by default unless this constructor is used to make     * one that is strictly asynchronous.     *     * Asynchronous messages represent interrupts or events that do not require global ordering     * with respect to synchronous messages.  Asynchronous messages are not subject to     * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.     *     * @param callback The callback interface in which to handle messages, or null.     * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for     * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.     *     * @hide     */    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;    }

3.2 Handler的sendMessage方法,会给msg的target赋值为handler自身,然后加入MessageQueue中。


在Handler.java中


    /**     * Pushes a message onto the end of the message queue after all pending messages     * before the current time. It will be received in {@link #handleMessage},     * in the thread attached to this handler.     *       * @return Returns true if the message was successfully placed in to the      *         message queue.  Returns false on failure, usually because the     *         looper processing the message queue is exiting.     */    public final boolean sendMessage(Message msg)    {        return sendMessageDelayed(msg, 0);    }    /**     * Enqueue a message into the message queue after all pending messages     * before (current time + delayMillis). You will receive it in     * {@link #handleMessage}, in the thread attached to this handler.     *       * @return Returns true if the message was successfully placed in to the      *         message queue.  Returns false on failure, usually because the     *         looper processing the message queue is exiting.  Note that a     *         result of true does not mean the message will be processed -- if     *         the looper is quit before the delivery time of the message     *         occurs then the message will be dropped.     */    public final boolean sendMessageDelayed(Message msg, long delayMillis)    {        if (delayMillis < 0) {            delayMillis = 0;        }        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);    }    /**     * Enqueue a message into the message queue after all pending messages     * before the absolute time (in milliseconds) <var>uptimeMillis</var>.     * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>     * Time spent in deep sleep will add an additional delay to execution.     * You will receive it in {@link #handleMessage}, in the thread attached     * to this handler.     *      * @param uptimeMillis The absolute time at which the message should be     *         delivered, using the     *         {@link android.os.SystemClock#uptimeMillis} time-base.     *              * @return Returns true if the message was successfully placed in to the      *         message queue.  Returns false on failure, usually because the     *         looper processing the message queue is exiting.  Note that a     *         result of true does not mean the message will be processed -- if     *         the looper is quit before the delivery time of the message     *         occurs then the message will be dropped.     */    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);    }

走了这么大一圈,代码这么多,但是最终就是将消息加到了消息队列中。此处也刚好回到了刚才我们所说的msg.target是什么时候赋值为Handler对象本身的,就是在你调用sendMessage的时候,将msg.target赋值为handler的对象.


3.3 在构造Handler实例时,我们会重写handleMessage方法,也就是msg.target.dispatchMessage(msg)最终调用的方法。此部分代码就是我们要实现的handlermessage内容了,不同的需求实现的代码不同,所以接下来的就看各位自己怎么实现了。


总结一下

1、首先Looper.prepare()在UIThread线程中创建一个Looper实例,然后该实例中创建一个MessageQueue对象;因为Looper.prepare()在一个线程中只能调用一次,所以MessageQueue在一个线程中只会存在一个。


2、Looper.loop()会让当前Looper线程进入一个无限循环,不停地从MessageQueue的实例中取消息msg,然后调msg.target.dispatchMessage(msg)方法将消息分发出去。


3、Handler的构造方法,会首先关联当前UIThread线程中保存的Looper实例,进而与Looper实例中的MessageQueue关联。


4、Handler的sendMessage方法,会给msg的target赋值为handler自身,然后将消息msg加入MessageQueue中。


5、创建对象Handler时,我们会重写handleMessage方法,也就是msg.target.dispatchMessage(msg)最终调用的方法。


好了,总结完成,大家可能还会问,那么在Activity中,我们并没有显示的调用Looper.prepare()和Looper.loop()方法,为啥Handler可以成功创建呢,这是因为在Activity的启动代码中,已经在当前UI线程调用了Looper.prepare()和Looper.loop()方法。

原创粉丝点击