转载

从源码去理解Handler

handler是所有Android工程师都十分常用的工具,功能丰富,既可以用于线程间的消息传递、组件间通讯,也可以实现定时任务、重复任务。本文将从源码角度理解handler的实现。

  • 1.handler的创建

//frameworks/base/core/java/android/os/Handler.java
//创建方法1
Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                //do Something
            }
        };
      
//创建方法2  通常用于子线程中操作UI时使用  传入主线程的loop  
Handler handler = new Handler(Looper.getMainLooper());
复制代码

除了上面两种创建方式之外handler还有好几种构造方法,但是最终调用的只有如下两个方法。

//frameworks/base/core/java/android/os/Handler.java
//上面创建方法1最终所调用的方法
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 " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }
    
//上面创建方法2最终所调用的方法
public Handler(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

复制代码

可以看到带有loop的构造方法大致只是做了一个赋值,其中loop是传入的已存在的looper,callback是Handler中的一个interface。

//frameworks/base/core/java/android/os/Handler.java
public interface Callback {
        /**
         * @param msg A {@link android.os.Message Message} object
         * @return True if no further handling is desired
         */
        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();
    }
复制代码

可以看到在Handler在处理msg的时候首先判断msg里面的callback是否为空,不为空就直接handleCallback了,为空再走callback的handleMessage和Handler本身的成员方法handleMessage,再看handleCallback方法,是不是恍然大悟,我们常用的handler.post(Runnable r)方法。我们在源码里再验证下我们的想法。

//frameworks/base/core/java/android/os/Handler.java
//handler中的post方法
public final boolean post(Runnable r)
{
   return  sendMessageDelayed(getPostMessage(r), 0);
}
//通过Message.obtain()拿到了Message对象m,并将r赋值给m.callback
private static Message getPostMessage(Runnable r) {
    Message m = Message.obtain();
    m.callback = r;
    return m;
}
复制代码

终于到最后一个参数了,async,中文是异步的。看看赋值之后在哪里被使用

//frameworks/base/core/java/android/os/Handler.java
    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
复制代码

最终还是到了Message身上,msg.setAsynchronous(true);设置message是否是异步的,这是message的一个属性。同一个Thread只有一个Looper,一个MessageQueue,但是可以有很多个Handler,如果Handler初始化的时候async参数是true,那么这个Handler所post的所有的message都会带上异步的属性。可以通过MessageQueue的postSyncBarrier(long when)来向队列中插入一个同步分割栏,同步分割栏是一个特殊的message,这种message的target=null,就像一个卡子,当他被插入时,会卡住在这之后的所有的同步的message,只会摘取异步的message。当然也可以通过MessageQueue的removeSyncBarrier(int token)来移除这个同步分割栏,token就是postSyncBarrier方法的返回值。但是目前这两个方法都被hide了。所以大家一般用到的都只是普通的Message。

到现在终于可以看一眼比较复杂的创建方法1了。

//frameworks/base/core/java/android/os/Handler.java
//上面创建方法1最终所调用的方法
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 " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }
复制代码

第一个if,找到潜在的泄漏,看看判断的条件,是否是匿名内部类、成员内部类、局部内部类并且不是static。想想看,有点意思,Java的特性:非静态的内部类和匿名内部类都会隐式的持有一个外部类的引用,所以这才是导致可能发生内存泄漏的关键,在我们日常编程中要注意这点,不然很可能会GG。继续往下,由于没有传Looper进来,所以拿到自己的Looper,这里可能抛出一个异常,大家应该遇到过,当你在一个新的线程中使用handler的时候,要先Looper.prepare(),不然就会抛出上面的异常,我们再去看下Looper.prepare()干了啥。

//frameworks/base/core/java/android/os/Looper.java
    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));
    }

    /**
     * Initialize the current thread as a looper, marking it as an
     * application is main looper. The main looper for your application
     * is created by the Android environment, so you should never need
     * to call this function yourself.  See also: {@link #prepare()}
     */
    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }
    
    /**
     * 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();
    }
复制代码

可以看到就是新建了一个Looper然后设置到了sThreadLocal中,其中new Looper(quitAllowed)时传入了一个参数quitAllowed。

//frameworks/base/core/java/android/os/Looper.java
    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }
    
//frameworks/base/core/java/android/os/MessageQueue.java
  MessageQueue(boolean quitAllowed) {
        mQuitAllowed = quitAllowed;
        mPtr = nativeInit();
    }
    
    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);
        }
    }
复制代码

可以看到这个参数控制这MessageQueue是否可以清空,如果调用了quitAllowed=true的Looper的quitSafely()方法,将清空所有Message,并且拒绝接收新的Message。prepareMainLooper()方法中quitAllowed参数为false,所以我们没办法让主线程的MessageQueue清空并拒绝插入Message,这也符合Android主线程的设计。

  • 2.handler发送Message

//frameworks/base/core/java/android/os/Handler.java
    public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }
    
    public final boolean postAtTime(Runnable r, long uptimeMillis)
    {
        return sendMessageAtTime(getPostMessage(r), uptimeMillis);
    }
    
    public final boolean postAtTime(Runnable r, Object token, long uptimeMillis)
    {
        return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
    }
    
    public final boolean postDelayed(Runnable r, long delayMillis)
    {
        return sendMessageDelayed(getPostMessage(r), delayMillis);
    }
    
    public final boolean postAtFrontOfQueue(Runnable r)
    {
        return sendMessageAtFrontOfQueue(getPostMessage(r));
    }

    public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }

    public final boolean sendEmptyMessage(int what)
    {
        return sendEmptyMessageDelayed(what, 0);
    }

    public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageDelayed(msg, delayMillis);
    }

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

    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);
    }
    public final boolean sendMessageAtFrontOfQueue(Message msg) {
        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, 0);
    }
复制代码

上面是所有Handler发送消息的方法,不管是什么方法,最终都是来到了enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis)方法。

//frameworks/base/core/java/android/os/Handler.java
    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
    
//frameworks/base/core/java/android/os/MessageQueue.java
    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 do not 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;
    }
复制代码

可以看到第一个方法中 msg.target = this;将当前Handler赋值给了msg.target,这是区分由哪个handler处理的关键。再看Message Queue中的方法,首先判断msg的target是否为空以及当前msg是否已经被使用,接着一个大的synchronized块,首先判断mQuitting的值,如果true则释放这个message并且return false。mQuitting这个值的设置就在在之前MessageQueue的quit(boolean safe),这里也说明了一旦调用了这个方法,MessageQueue则不会再接收任何消息。接下来第一个if的判断,p == null代表当前没有要处理的Message、when == 0代表立马插入、when < p.when代表传入msg的when比当前要处理的Message的时间还要提前,所以满足上面的条件之一的都会被插入到消息队列的首部。那下面else部分就是判断传入的msg该插入到队列中的哪个部分,里面的for循环就是完成了这么一件事情。但是其中有个needWake,字面意思是需要被唤醒,两个赋值的地方:if块里 needWake = mBlocked,直接赋值,如果当前状态是blocked,需要唤醒,没毛病。 else块里needWake = false,如果需要唤醒并且p是异步的,注意一点能走到这里的代表p不是第一个消息。说明即便msg是异步的,也不是链表中第一个异步消息,所以没必要唤醒了。

  • 3.Message的处理

在前面只说到了Message被插入到了消息队列中,那么Message又是怎么被取出来,又是怎么处理的呢,上面丝毫未提,但是回想一下,我们在Looper.prepare()之后是不是有个必做的方法Looper.loop()。看来应该都在这里面了。

//frameworks/base/core/java/android/os/Looper.java
    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 was not 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();
        }
    }
复制代码

大部分都是Log,可以看到一个死循环,通过Message msg = queue.next(),拿到了要处理的msg,这个next()可能会引起中断,通过 msg.target.dispatchMessage(msg);实现了处理。msg.target就是之前设置进去的handler,所以就是调用handler的dispatchMessage,这个方法已经在上面分析过了。那么现在就简单了,我们看下MessageQueue的next()方法。

//frameworks/base/core/java/android/os/MessageQueue.java
    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;
        }
    }
复制代码

看这代码,不出所料(没有其他可能了) nativePollOnce(ptr, nextPollTimeoutMillis);这句就是中断用的了,然后我们看第一个地方,msg != null && msg.target == null,是不是同步分割栏,看代码,如果当前的msg是同步分割栏,那么就找到后面是有异步属性的msg。第二个地方,首先判断msg应该执行的时间,有dealy就计算delay的时间,delay最大不超过Integer.MAX_VALUE。没有delay就拿到了msg,就直接return回去了。第三个方法说明此时已经没了msg,nextPollTimeoutMillis= -1,当运行nativePollOnce时就代表一直阻塞。第四个地方说明调用了quit()方法,丢弃msg并返回空。第五个地方,看注释,如果第一次空闲,则获取要运行的idlers数量。仅当队列为空或第一条消息在队列中(可能是屏障)将在将来处理。要是没有要运行的就直接设置mBlocked为true,然后continue了,接着就阻塞了。然后把mIdleHandlers拷贝到mPendingIdleHandlers里,就到了第六个地方,就开始执行idler.queueIdle()了,根据idler的返回值判断要不要从mIdleHandlers中移除,如果不移除那么以后每次空闲都就会运行。第七个地方,将pendingIdleHandlerCount赋值为0,避免再执行(在这一次的MessageQueue的next()方法中最多只执行一次)。将nextPollTimeoutMillis赋值为0,因为不知道在所有的mIdleHandlers都执行完成之后msg的when到了没了,所以设置成0,直接再来一次,看到这里终于理解如何利用handler来做延迟加载了,其间奥秘全在mIdleHandlers里。

原文  https://juejin.im/post/5c9b198ff265da612f1baa9e
正文到此结束
Loading...