美文网首页
【Android】Handler原理解析

【Android】Handler原理解析

作者: 王小二的王 | 来源:发表于2018-09-11 18:01 被阅读20次

    要分析Handler的原理,首先需要了解Message和Looper,所以我们先来分析一下Message和Looper的源码。

    Message

    首先根据注释来看一下Message的定义:

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

    定义一个包含描述和任意数据对象的对象,将这个对象发送给Handler处理。这个对象包含两个额外的int字段和一个额外的object字段,但在很多情况下,这些字段并要求你必须给他们赋值。同时提醒我们,虽然Message的构造函数是public的,但是最好是调用Message.obtain()方法,这个方法会从回收池里获取Message对象。obtain方法是怎么回收利用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();
    }
    

    1、这里的sPoolSync是一个Object实例,sPool是一个Message对象,如果sPool不为null的话,会将sPool赋值给一个新的Message对象,并将m.next赋值给sPool,m.next也是一个Message,同时,最终返回m。由于取出了一个Message,所以sPoolSize--,如果有另外线程调用Message.obtain,则会直接创建一个新的Message返回;

    /**
     * Same as {@link #obtain()}, but copies the values of an existing
     * message (including its target) into the new one.
     * @param orig Original message to copy.
     * @return A Message object from the global pool.
     */
    public static Message obtain(Message orig) {
        Message m = obtain();
        m.what = orig.what;
        m.arg1 = orig.arg1;
        m.arg2 = orig.arg2;
        m.obj = orig.obj;
        m.replyTo = orig.replyTo;
        m.sendingUid = orig.sendingUid;
        if (orig.data != null) {
            m.data = new Bundle(orig.data);
        }
        m.target = orig.target;
        m.callback = orig.callback;
    
        return m;
    }
    

    2、根据注释可以看出,该方法与obtain()方法一样,不同之处在于,这个方法的参数是一个已存在的Message,它首先调用botain()方法,获取一个已存在的Message,然后将参数Message的值赋值给m对应的属性,最终返回m。其他几个obtain方法都是多了一些传参,对m的某些值做了修改,就不多做赘述了,Message内部还有一些其他方法,但是一般在使用Handler时不会使用,所以就不予以描述了。

    Looper

    Looper对与Handler来说,是一个很重要的概念,不了解Looper就不能真正弄懂Handler的机制,所以,先来了解一下Looper,先看一下官方对与Looper的定义。

    /**
      * Class used to run a message loop for a thread.  Threads by default do
      * not have a message loop associated with them; to create one, call
      * {@link #prepare} in the thread that is to run the loop, and then
      * {@link #loop} to have it process messages until the loop is stopped.
      *
      * <p>Most interaction with a message loop is through the
      * {@link Handler} class.
      *
      * <p>This is a typical example of the implementation of a Looper thread,
      * using the separation of {@link #prepare} and {@link #loop} to create an
      * initial Handler to communicate with the Looper.
      *
      * <pre>
      *  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();
      *      }
      *  }</pre>
      */
    

    官方对与Looper的定义为,针对一个线程运行的消息循环。线程默认是没有消息循环相关联的,要创建一个消息循环,就要调用Looper的prepare方法,然后调用Looper的loop方法来循环处理消息,直到循环停止。下边官方也说明大多数与消息循环的交互是通过Handler来实现的。最后官方给出了一个创造包含消息循环的线程的例子。下边看一下Looper具体的代码:

     /** 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.loop()方法之前调用,最后要调用quit()方法退出循环。这两个方法
    唯一的不同就是多了一个boolean类型的参数。无参的prepare方法调用了有参的prepare方法,并默认参数为true。从有参的prepare方法中可以看到,有个sThreadLocal对象,并调用了该对象的get方法,我们看下它的get方法最终会返回什么:

    /**
     * Returns the value in the current thread's copy of this
     * thread-local variable.  If the variable has no value for the
     * current thread, it is first initialized to the value returned
     * by an invocation of the {@link #initialValue} method.
     *
     * @return the current thread's value of this thread-local
     */
    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }
    

    首先,该方法会获取当前线程,并获取当前线程的ThreadLocalMap,ThreadLocal是一个定制的HashMap,是为了维护线程本地值而诞生的,如果当前线程的ThreadlocalMap不为null,则根据key,获取Entry,将Entry.value返回。如果map为null,则调用setInitialValue方法,再看这个方法是用来干什么的:

    /**
     * Variant of set() to establish initialValue. Used instead
     * of set() in case user has overridden the set() method.
     *
     * @return the initial value
     */
    private T setInitialValue() {
        T value = initialValue();
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
        return value;
    }
    
    protected T initialValue() {
        return null;
    }
    
    /**
     * Create the map associated with a ThreadLocal. Overridden in
     * InheritableThreadLocal.
     *
     * @param t the current thread
     * @param firstValue value for the initial entry of the map
     */
    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }
    

    可以看到,setInitialValue方法是将null作为value传入了当前线程的ThreadLocalMap中,在get方法中,若map为null,最终返回的值为null。如果get方法返回不为null,则会抛出异常:每个线程只能创建一个Looper。若get方法返回为null,则ThreadLocal中会存入一个新创建的Looper对象。接下来,看一下Looper的构造函数:

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

    在构造函数中,创建一个MessageQueue对象,同时将当前线程赋值给mThread。其中quitAllowed参数是MessageQueue调用quit()方法时会用到,若该参数值为false,则会抛出异常:Main thread not allowed to quit。所以创建一个包含Looper的子线程时,需要调用无参或者参数值为true的prepare方法。接下来就是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
             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);
                 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();
         }
     }
    

    首先调用Looper的myLooper方法,获取Looper对象,若为null,则说明没有调用Looper的prepare方法创建Looper对象,抛出异常。接着获取Looper对应的MessageQueue,后边会用到。然后调用两次Binder的native方法:clearCallingIdentity,一次用作标识,一次是获取具体的标识,就不多做详解了。接下来就是一个循环,这个循环就是用来遍历MessageQueue中的Message的,首先用MessageQueue的next方法获取Message,这里看一下MessageQueue的next方法:

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

    首先是将成员变量mPtr赋值给局部变量ptr,这个mPtr是从何而来的呢?通过MessageQueue的构造函数可以看到,是通过native方法,nativeInit来初始化的一个值,看一下nativeInit的代码:

    static jlong android_os_MessageQueue_nativeInit(JNIEnv* env, jclass clazz) {
        NativeMessageQueue* nativeMessageQueue = new NativeMessageQueue();
        if (!nativeMessageQueue) {
            jniThrowRuntimeException(env, "Unable to allocate native queue");
            return 0;
        }
    
        nativeMessageQueue->incStrong(env);
        return reinterpret_cast<jlong>(nativeMessageQueue);
    }
    

    以上代码表示,若指针为空,抛出异常,返回0,否则,将指针强转为Long类型,返回。同时,在next方法中可以看到,若prt=0,直接返回null。接着定义了两个int类型的值,具体作用用到了再看。接下来是个for循环,用于循环获取Message。若nextPollTimeoutMillis不为0,则调用Binder的native方法来刷新进程间通信线程的状态,具体代码不作详解。下边又是一个MessageQueue的native方法,来看一下具体代码:

    static void android_os_MessageQueue_nativePollOnce(JNIEnv* env, jobject obj,
            jlong ptr, jint timeoutMillis) {
        NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr);
        nativeMessageQueue->pollOnce(env, obj, timeoutMillis);
    }
    
    void NativeMessageQueue::pollOnce(JNIEnv* env, jobject pollObj, int timeoutMillis) {
        mPollEnv = env;
        mPollObj = pollObj;
        mLooper->pollOnce(timeoutMillis);
        mPollObj = NULL;
        mPollEnv = NULL;
    
        if (mExceptionObj) {
            env->Throw(mExceptionObj);
            env->DeleteLocalRef(mExceptionObj);
            mExceptionObj = NULL;
        }
    }
    

    可以看到内部是一些赋值操作,具体用到这些值的时候再做具体分析。继续往下分析next方法,可以看到一个同步代码块,首先获取当前时间,接着将null赋值给prevMsg,将mMessages赋值给msg。判断如果msg不为null,且msg.target为null,即msg没有对应的Hanlder时,说明当前msg不应该被处理,就将msg赋值给prevMsg,将msg.next赋值给msg,同时进入循环,若msg不为null,且msg是同步消息,则继续执行msg赋值给prevMsg,msg.next赋值给msg。代码继续执行,判断msg是否为null,若为null则将nextPollTimeoutMillis赋值为-1,代表没有Message,若不为null,则比较当前时间和msg.when,若当前时间小于msg.when,则说明下一条Message没有准备好,将msg.when-now和Integer.MAX_VALUE间的最小值赋值给nextPollTimeoutMillis,在其他方法中,会在该值到0后,调用nativeWake方法唤醒Looper,处理该条消息。如果now大于等于msg.when,说明获取到需要处理的Message,将false赋值给mBlocked,该值会在其他方法用到。如果prevMsg不为null的话,说明进入了上边do-while循环中,msg为下一条异步消息,但是不是头节点,则将msg.next赋值给prevMsg.next,若prevMsg为null,说明msg为头节点,将msg.next赋值给mMessages。将null赋值给msg.next,并将msg标识为正在使用中,最后返回msg。分析完MessageQueue的next方法,再继续分析Looper的loop方法。

    通过next方法获取Message后,如果Message为null,说明消息队列里边没有消息了,则return结束轮询。后续大部分代码是打印log相关的,中间有一行代码: msg.target.dispatchMessage(msg);这里可以看到,调用了Hanlder的dispatchMessage方法来处理消息。最后调用了Message的recycleUnchecked方法来回收消息。接着再看一下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(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;
    }
    

    首先是两个判断,如果target为null,说明没有Handler来处理消息,则抛出异常,再判断消息是否正在被使用,若是,则抛出异常。下来是一个同步代码块,首先判断mQuitting是否为true,该值在调用quit方法是会赋值为true,若为true,说明已经调用quit方法,则调用Message的recycle方法,并返回false。如果mQuitting为false,首先用markInUse将Message标识为使用中,并将参数中的when赋值给msg.when。接下来将mMessages赋值给p。然后定义一个boolean类型的值,用于标识是否需要唤醒Looper。接下来判断,若p为null,说明消息队列中没有消息,若when为0,则说明该消息需要立即处理,若when小于p.when,说明插入消息要比当前链表头的处理时间要早,三种判断有一种为true,则将新插入的消息插入到链表头,反之,三种判断都为false的话,将mBlocked && p.target == null && msg.isAsynchronous()赋值给needwake,用于判断是否唤醒Looper,接着用for循环来对比消息队列中的Message的when和新插入消息的when,来找出新插入消息插入的位置。最后判断是否需要唤醒,若需要,则调用native方法nativeWake即可。Message和Looper分析完了,接下来正式分析Handler。

    Handler

    查看Handler源码,该类首先定义了三个成员变量。

    /*
     * Set this flag to true to detect anonymous, local or member classes
     * that extend this Handler class and that are not static. These kind
     * of classes can potentially create leaks.
     */
    private static final boolean FIND_POTENTIAL_LEAKS = false;
    private static final String TAG = "Handler";
    private static Handler MAIN_THREAD_HANDLER = null;
    

    其中TAG很容易理解,MAIN_THREAD_HANDLER根据名字就可以看出来是主线程的Handler,但是FIND_POTENTIAL_LEAKS是做什么用的呢?根据注释,如果将这个变量值设为true时,就可以检测继承自Handler的非静态匿名类、局部类和成员类可能造成的泄露。至于怎么检测,后边分析到了再说。

    Callback

    接下来定义了一个接口Callback:

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

    根据注释可知,该接口是在实例化Handler时使用的,以避免必须实现自己的Handler子类。该接口与Handler的关系就跟Thread和Runnable的关系类似。以代码为例,通常我们使用Handler会写一个Hanlder的子类:

    private static class MyHandler extends Handler {
        WeakReference<Activity> mWeakReference;
    
        public MyHandler(Activity activity) {
            mWeakReference = new WeakReference<>(activity);
        }
    
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    }
    

    但使用Callback的话,就不需要继承Hanlder了,代码如下:

    class MyCallback implements Handler.Callback {
        @Override
        public boolean handleMessage(Message msg) {
            //处理消息
            return true;
        }
    }
    
    //使用时直接作为参数传进去即可
    Handler handler = new Handler(new MyCallback());
    

    可以看到Callback的handleMessage有个boolean类型的返回值,该值的作用就是判断是否处理Hanlder自己的handleMessage,如果为true,表示消息已经处理完,则不会调用Hanlder的handleMessage,反之,则会调用Hanlder的handleMessage。具体逻辑在dispatchMessage方法中,后续会讲该方法。
    这种方法虽然编译器不会提示会发生内存泄露,但实际还是会发生内存泄露,一般在Activity中推荐使用继承Handler。

    构造函数

    Handler总共有7个构造函数,我们逐一分析:

    /**
     * Default constructor associates this handler with the {@link Looper} for the
     * current thread.
     *
     * If this thread does not have a looper, this handler won't be able to receive messages
     * so an exception is thrown.
     */
    public Handler() {
        this(null, false);
    }
    

    1、第一个构造函数,不需要传任何参数,它调用了另外一个两个参数的构造函数,两个参数分别为:Callback和一个boolean类型的值,根据其名称,可以看出它跟是否异步相关,这个值具体有什么用,后边用到后再进行了解,先记住有这么一个值,该构造函数传递的两个值分别为null和false,根据注释,使用该构造函数实例化Handler的话,Handler对象将于当前线程中的Looper关联,如果当前线程没有Looper,则会抛出异常。

    /**
     * Constructor associates this handler with the {@link Looper} for the
     * current thread and takes a callback interface in which you can handle
     * messages.
     *
     * If this thread does not have a looper, this handler won't be able to receive messages
     * so an exception is thrown.
     *
     * @param callback The callback interface in which to handle messages, or null.
     */
    public Handler(Callback callback) {
        this(callback, false);
    }
    

    2、第二个构造函数相较第一个构造函数,多了一个Callback参数,内部调用的跟第一个构造函数一样,不同之处第一个构造函数Callback为null,第二个构造函数Callback是作为参数传进来的。

    /**
     * Use the provided {@link Looper} instead of the default one.
     *
     * @param looper The looper, must not be null.
     */
    public Handler(Looper looper) {
        this(looper, null, false);
    }
    

    3、第三个构造函数跟第一个构造函数的区别在于,多了一个Looper参数,其内部调用的也是一个三参数的构造函数,无参的构造函数使用的是当前线程的Looper,这个构造函数使用的是参数传过来的Looper。

    /**
     * Use the provided {@link Looper} instead of the default one and take a callback
     * interface in which to handle messages.
     *
     * @param looper The looper, must not be null.
     * @param callback The callback interface in which to handle messages, or null.
     */
    public Handler(Looper looper, Callback callback) {
        this(looper, callback, false);
    }
    

    4、该构造函数有两个参数,分别为Looper和Callback,与只有Callback的构造函数不同点在于Looper。

    /**
     * Use the {@link Looper} for the current thread
     * 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 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(boolean async) {
        this(null, async);
    }
    

    5、该构造函数有一个boolean类型的参数,这个参数是用来设置Handler是否异步的,根据注释可以看出,Handler默认是异步的,除非调用这个构造函数,可以修改Hanlder为同步的。

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

    6、该构造函数是使用当前线程的Looper的所有构造函数最终调用的函数。在这个函数中,看到了前面提到过的FIND_POTENTIAL_LEAKS,如果该值为true,首先通过getClass获取Handler的子类,接着判断该类是否是匿名类、成员类或者局部类并且是非静态的,就会输出log,提示Handler类应该为静态否则可能导致内存泄漏。接着根据Looper.myLooper()获取当前线程的Looper,如果Looper为null,则抛出异常,在异常里可以看到有个Looper.prepare()方法,该方法会在当前线程没有Looper时新建一个Looper实例。下边就是三个赋值操作,分别将Looper的MessageQueue、callback参数、async参数赋值给对应的成员变量。

    /**
     * Use the provided {@link Looper} instead of the default one and take a callback
     * interface in which to handle messages.  Also 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 looper The looper, must not be null.
     * @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(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }
    

    7、该构造函数与上个构造函数的不同在于Looper不是使用当前线程的Looper,而是使用参数中提供的Looper,该函数里边只有四个赋值操作,分别将looper参数、looper中的MessageQueue、callback参数、async参数赋值给对应的成员变量。

    dispatchMessage与handleMessage

    首先讲一下这两方法有啥区别,dispatchMessage是用于分发处理消息,通常我们不用实现该方法,而是用handleMessage来处理我们自己的方法。从代码看:

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

    可以看到,dispatchMessage内本身有一些逻辑,首先判断msg的callback是否为null,callback是一个Runnable接口,若不为bull,则调用handleCallback方法,该方法内部实现很简单,就是调用了callback的run方法,若为null,则判断Handler的Callback是否为null,若不为null,则调用Callback的handleMessage,若Callback的handleMessage返回true,说明不需要再进一步处理,则return,反之,调用handleMessage。Looper.loop中,循环取出消息后,就是调用的dispatchMessage方法来处理消息。

    发送消息

    首先整理一下Handler对外暴露的可以发送消息的方法,分别为:post(Runnable r)、postAtTime(Runnable r, long uptimeMillis)、postAtTime(Runnable r, Object token, long uptimeMillis)、postDelayed(Runnable r, long delayMillis)、sendEmptyMessage(int what)、sendEmptyMessageDelayed(int what, long delayMillis)、sendEmptyMessageAtTime(int what, long uptimeMillis)、sendMessageDelayed(Message msg, long delayMillis)、sendMessageAtTime(Message msg, long uptimeMillis),可以看到,可以发送消息的方法很多,主要分为两种,一种是参数为Message的,一种是参数为Runnable的。下边我们分析一下两者有何区别:

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

    可以看到,最终也是调用了sendMessageDelayed(Message msg, long delayMillis)这个方法,通过getPostMessage(r)方法获取到了Message,将r赋值给Message的callback,也就是说,最终处理消息时,不会执行handleMessage方法,而是执行Runnable的run方法。这就是两种参数发送消息之间的区别,上述方法最终调用的都是sendMessageAtTime(Message msg, long uptimeMillis)方法,来看一下这个方法:

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

    可以看到,其实最终调用的就是MessageQueue的enqueueMessage方法。这个方法对插入消息的处理我们上边也已经分析过了。Handler也就分析完了,可以看到其实Handler的源码本身是没有多少的,大部分内容是在Looper和MessageQueue中的。Handler的原理到此就算是分析完成了,中间若有不对的地方,希望各位大佬可以提出来。

    代码中的彩蛋:算是一个彩蛋吧,是在Looper的源码中发现的,在打印log时,有这么一个方法,Log.wtf,看源码解释是What a Terrible Failure,但我想,应该也是包含what the fuck的意思吧,哈哈哈。

    相关文章

      网友评论

          本文标题:【Android】Handler原理解析

          本文链接:https://www.haomeiwen.com/subject/ryaugftx.html