Android Handler原理实践解析

作者: 881ef7b85f62 | 来源:发表于2019-04-01 20:49 被阅读131次

    前言

    Handler消息处理机制在Android开发中起着举足轻重的作用,我们有必要好好理解下其原理,下面我们先从一个简单的例子出发

    一、日常使用

    假设我们有这么一个需要,请求网络然后将图片展示出来,我们知道网络请求是不允许在主线程执行的,而UI是不能在子线程(具体是不允许在非创建UI的原始线程)更新的,因此我们需要在子线程请求网络获得了数据以后再切换回主线程更新UI,这个例子中Handler就是起着切换线程的作用,下面的代码演示了这个例子

    class MainActivity : AppCompatActivity() {
        private lateinit var mImageView: ImageView
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            mImageView = findViewById(R.id.iv)
            loadImage()
        }
        private fun loadImage() {
            Thread {
                val url = URL("https://img-my.csdn.net/uploads/201309/01/1378037235_7476.jpg")
                val conn = url.openConnection()
                val bitmap = BitmapFactory.decodeStream(conn.inputStream)
                runOnUiThread {
                    mImageView.setImageBitmap(bitmap)
                }
            }.start()
        }
    }
    

    咦!,说好的Handler去哪了?这里的runOnUIThread方法内部实现其实就是利用了Handler,我们来看看它的源码

    public final void runOnUiThread(Runnable action) {
        if (Thread.currentThread() != mUiThread) {
            mHandler.post(action);
        } else {
            action.run();
        }
    }
    

    该方法首先判断了当前线程是否是主线程,如果不是主线程就调用mHandler.post(),如果当前线程就是主线程就直接运行,下面我们来分析看看Handler的原理

    二、Handler原理

    要想分析Handler的原理,我们先从Handler的创建过程开始分析

    Handler的创建

    Activity的这个mHandler是怎么来的呢?原来mHandler是Activity的成员变量,在Activity实例创建的时候就创建了

    final Handler mHandler = new Handler();
    

    接着看看Handler的构造方法

    public Handler() {
        this(null, false);
    }
    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;
    }
    

    首先判断了该Handler派生类是否是非静态内部类,如果是的话就打印出日志提示可能导致内存泄露,然后调用了Looper.myLooper获取到当前线程的Looper对象,如果当前线程没有Looper就会抛出异常,最后将Looper中的MessageQueue对象赋值给mQueue,callback赋值给mCallback,aync赋值给mAsynchronous,我们来看看Looper.myLooper做了些什么

    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }
    

    从ThreadLocal里面去Looper,那么是在哪里把Looper设置到ThreadLocal里面去的呢?其实Looper提供了prepare方法来创建当前线程的Looper,我们来看看代码

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

    只有在当前线程拿不到Looper的时候才会去创建Looper对象并将其设置到ThreadLocal中去,不然就抛出异常说一个线程只能拥有一个Looper,继续看看Looper的构造方法

    // 这里的quitAllowed是true
    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }
    

    又创建了一个MessageQueue对象,继续看看它的构造方法

    // 这里的quitAllowed是true
    MessageQueue(boolean quitAllowed) {
        mQuitAllowed = quitAllowed;
        mPtr = nativeInit();
    }
    

    调用了一个Native方法就结束了,其实mPtr是NativeMessageQueue与MessageQueue之间的桥梁内部会调用epoll.create()epoll.ctl(),暂时不看native层代码

    源码看到这里就会产生一个疑问,既然创建Handler的时候判断了当前线程的Looper是否为null,为null就会抛出异常,那么Activity的Handler是怎么创建成功的呢?其实在Activity实例创建前主线程就已经有Looper对象了,这个得从ActivityThread开始说起。ActivityThread是一个应用程序的入口里面有一个main方法,我们来看看

    // 忽略其它代码
    public static void main(String[] args) {
        ...
        Looper.prepareMainLooper();
        Looper.loop();
        ...
    }
    

    Looper.loop()后面会讲到先忽略,main方法内部调用了Looper.prepareMainLooper()这个方法跟上面讲到的Looper.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();
        }
    }
    

    prepare方法前面已经分析过了但是主线程是不允许退出的,所以传入了false,后面判断了如果sMainLooper不为空那么就抛出异常,至此主线程的Looper创建成功这也就解释了为什么Activity中可以直接创建Handler,接着我们分析那个post方法干了些什么事情

    Handler的消息发送

    Handler提供了很多方法用于发送消息,比如以下几种

    • sendEmptyMessage(int what) 发送一个空消息,what用于判断消息类别
    • sendEmptyMessageDelayed(int what, long delayMillis) 发送一个空消息,延迟delayMillis毫秒执行,what用于判断消息类别
    • sendEmptyMessageAtTime(int what, long uptimeMillis) 发送一个空消息,在uptimeMillis的时候执行,what用于判断消息类别
    • sendMessageDelayed(Message msg, long delayMillis) 发送一个消息,延迟delayMillis毫秒执行
    • sendMessageAtTime(Message msg, long uptimeMillis) 发送一个消息,在uptimeMillis的时候执行
    • sendMessageAtFrontOfQueue(Message msg) 发送一个消息,该消息会排在消息队列的队首
    • executeOrSendMessage(Message msg) 如果Handler中的Looper与当前线程的Looper一致就直接分开消息,不然就发送一个消息

    我们继续着看post方法的实现

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

    其实post方法内部也就是发送了一个消息

    private static Message getPostMessage(Runnable r) {
        // message内部维护了一个Message链表,以达到复用的目的,记得不要直接new
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }
    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);
    }
    

    最终调用到了sendMessageAtTime,其实几乎所有发送消息的方法最终都会调用到该方法,继续看enqueueMessage的实现

    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
    

    这里将本Handler的实例赋值给了msg.target,这个很重要以后会用到,然后判断下当然Handler是否是异步的,是的话就将消息设置成异步,我们这里不是异步的,接着继续看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 {
                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;
            }
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }
    

    该方法首先判断了msg.target是否为空,这个我们刚才看到已经设置了,然后判断msg是否正在被使用,然后再判断消息队列是否已经退出了,如果已经退出了就将msg回收并抛出个异常,下面那个同步代码块其实处理的逻辑就是将msg放入到消息队列中去,插入过程分为以下两步,至于needWake是用于判断是否要唤醒处于nativePollOnce而阻塞的Message.next方法

    • 如果满足p == null || when == 0 || when < p.when其实也就是如果消息队列的头指针为空,或者当前消息的执行时间为0,或者当前消息的执行时间先与消息队列队首的执行时间,那么将当前msg当做头指针
    • 如果不满足第一种情况就根据当前msg.when决定插入的位置

    现在已经将消息放到的消息队列中,但是什么时候这个消息才能得到执行呢?这就要看看前面跳过的ActivityThread的main方法中的Looper.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;
        boolean slowDeliveryDetected = false;
        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                return;
            }
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }
            final long traceTag = me.mTraceTag;
            long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
            long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
            if (thresholdOverride > 0) {
                slowDispatchThresholdMs = thresholdOverride;
                slowDeliveryThresholdMs = thresholdOverride;
            }
            final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
            final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);
            final boolean needStartTime = logSlowDelivery || logSlowDispatch;
            final boolean needEndTime = logSlowDispatch;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
            final long dispatchEnd;
            try {
                msg.target.dispatchMessage(msg);
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (logSlowDelivery) {
                if (slowDeliveryDetected) {
                    if ((dispatchStart - msg.when) <= 10) {
                        Slog.w(TAG, "Drained");
                        slowDeliveryDetected = false;
                    }
                } else {
                    if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
                            msg)) {
                        // Once we write a slow delivery log, suppress until the queue drains.
                        slowDeliveryDetected = true;
                    }
                }
            }
            if (logSlowDispatch) {
                showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg);
            }
            if (logging != null) {
                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
            }
            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不包含就抛出异常
    • 调用MessageQueue的next方法获取Message,如果返回了null,标志了MessageQueue已经退出了,所以Looper也要退出
    • 获取Looper中的mLogging用于打印日志,我们可以通过setMessageLogging进行设置,设置后每次收到消息和消息处理完毕都会有日志我们可以根据这些日志分析ANR是由于处理哪个消息超时造成的
    • 设置慢分发时间和慢交付时间,可以通过adb进行设置,慢分发时间表示如果这个消息的实际执行时间比其设置的slowDeliveryThresholdMs要长就会打印警告日志,慢交付时间表示这个消息从消息队列取出时间比其设置的when超过slowDispatchThresholdMs就会打印警告日志
    • 记录开始分发的时间
    • 调用msg.target.dispatchMessage进行分发消息,其中msg.target就是一个Handler实例,上文说到过的
    • 记录结束分发的时间
    • 根据实际情况打印日志
    • 回收msg

    loop方法调用queue.next取出消息,我们来看看该方法的实现

    Message next() {
        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) {
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                if (msg != null && msg.target == null) {
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
                if (msg != null) {
                    if (now < msg.when) {
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        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;
                }
                if (mQuitting) {
                    dispose();
                    return null;
                }
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    mBlocked = true;
                    continue;
                }
                if (mPendingIdleHandlers == null) {
                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
                }
                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
            }
            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);
                    }
                }
            }
            pendingIdleHandlerCount = 0;
            nextPollTimeoutMillis = 0;
        }
    }
    
    

    该方法主要流程如下

    • 调用nativePollOnce,阻塞等待下一个可执行消息,该方法离开阻塞
    • 判断第一个消息的target是否为空,如果不为空表示是一个普通的消息,如果为空则表示是一个同步屏障消息(在屏幕刷新的时候会发送),遍历消息队列找到第一个异步消息赋值给msg
    • 判断msg是否为空,如果为空那么进行无超时的等待,直到被唤醒
    • 判断msg是否到了执行时间,如果不到就执行阻塞等待msg.when - now,如果已经到了就将该消息返回
    • 如果消息队列已经退出就返回null

    拿到了消息以后就调用了handler.dispatchMessage我们来看看其实现

    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }
    

    首先判断是否该Message是否设置了callBack,设置了就直接运行,然后判断Handler是否设置了callBack,设置了就调用callback.handleMessage如果返回false,继续调用handleMessage

    三、总结

    • Handler的作用就是把想要执行的操作从当前线程切换到Handler中Looper所在的线程进行执行
    • 每次通过Handler发送消息其实就是把消息插入到了消息队列中,然后根据情况判断是否要唤醒处于调用nativePollOnce阻塞状态的线程

    相关文章

      网友评论

        本文标题:Android Handler原理实践解析

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