Android Handler 源码以及原理分析

Handler 源码分析

Handler 简介

Handler 是 Android 重要的通信工具,一个 Handler 关联有且仅有一个 Thread 、Looper 和 MessageQueue,它依赖于 Looper 和 MessageQueue 分发 Message 和 Runnable 对象在 Handler 绑定的线程中执行一些操作。创建 Handler 时默认绑定当前所在的 Thread,也可以通过手动绑定 Looper 对象设置 Handler 运行所在的 Thread。Handler 的消息类型分为三种:

1.同步消息 最常见的消息类型

2.异步消息 配合屏障消息使用,如果在这之前 MessageQueue 塞进了屏障消息,则优先处理异步消息

3.屏障消息 阻断当前的 MessageQueue,遍历队列时优先且只处理异步消息,直到移除屏障消息

NOTE: 利用屏障消息和异步消息可以使 Message 插入到之前队列前面达到提高消息优先级的的作用,目前设置屏障消息的方法为系统隐藏方法,App 需要反射调用。最经典的例子是 ViewRootImpl#scheduleTraversals()通过该方法优先执行 View 的绘制流程,代码如下:

@UnsupportedAppUsage
void scheduleTraversals() {
    if (!mTraversalScheduled) {
        mTraversalScheduled = true;
        // 插入屏障消息阻塞主线程 Handler 的消息
        mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
        // 插入异步消息,优先执行 View 的绘制
        mChoreographer.postCallback(
                Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
        if (!mUnbufferedInputDispatch) {
            scheduleConsumeBatchedInput();
        }
        notifyRendererOfFramePending();
        pokeDrawLockIfNeeded();
    }
}

回到主题,放一张图表示 Handler 的工作原理:
在这里插入图片描述

Handler 源码分析

首先从 Handler 的构造方法入手,我们假设是在主线程直接调用的 Handler 的无参构造方法,会调用到以下的方法,这里会检查内存泄漏风险,绑定当前线程的 Looper 对象和 MessageQueue 对象,并且设置默认消息类型都是同步消息

public Handler(@Nullable 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());
        }
    }
    // 绑定当前线程的 Looper 对象
    mLooper = Looper.myLooper();
    if (mLooper == null) {
        throw new RuntimeException(
            "Can't create handler inside thread " + Thread.currentThread()
                    + " that has not called Looper.prepare()");
    }
    // 设置 MessageQueue
    mQueue = mLooper.mQueue;
    mCallback = callback;
    // mAsynchronous = false,默认都是同步消息
    mAsynchronous = async;
}

获取到 Handler 对象后,调用 sendEmptyMessage(int what), Handler 会把 what 封装成 Message 对象入列到 MessageQueue,先看下 Message 的构造,msg 由 Message 的静态方法 obtain() 生成:

public static Message obtain(Handler h, int what) {
    // 获取出一个新的 msg,并不会每次都 new 一个对象,可能会复用回收的 msg 对象
    Message m = obtain();
    // 设置 target,就是一个 Handler 对象,分发到对应的 Handler 当中
    m.target = h;
    m.what = what;

    return m;
}

Message 的设计思想是链表和复用,在以下几个情况下会调用 recycleUnchecked 把消息放进复用队列池:

    1.消息使用完成后,即执行完 handleMessage

    2.删除消息,即 Handler 调用removeMessages

    3.Looper 调用 quit()。实际也是调用的 removeMessages

如果当前的复用对列池不为空,会从中取出一个消息并进行重置。接着将获取到的 msg 插入 MessageQueue,

private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
        long uptimeMillis) {
    msg.target = this;
    msg.workSourceUid = ThreadLocalWorkSource.getUid();
    // 根据 mAsynchronous 统一设置消息是否为异步消息。由于默认设置为 false,所以都为同步消息
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    // 将 msg 插入 MessageQueue 
    return queue.enqueueMessage(msg, uptimeMillis);
}

MessageQueue是个单向链表结构,插入消息时会返回当前列表的头指针 mMessages,遍历列表时也是从该指针开始。如果之前消息队列没有消息在执行,或者当前的队列有屏障消息,插入的新 msg 为异步消息会尝试唤醒线程

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) {
        // 如果调用了quit,打印个异常消息,将消息回收到复用池,返回 false
        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;
        // 如果当前列表为空,或者执行时间早于头指针,则 msg 直接作为头指针
        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;
            // 寻找插入点,根据执行时间,将 msg 插入到队列中
            for (;;) {
                prev = p;
                p = p.next;
                // 队尾或者新 msg 的执行时间早于某一个队列中的消息
                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;
}

至此,一个新消息就插入了 MessageQueue。由于在绑定 Looper 之前执行过 Looper.loop() 开启了个无限循环去索引需要执行的消息,实际是由 MessageQueue#next() 方法中实现,如果没有获取到消息,队列会调用 nativePollOnce 释放 CPU 资源进入到休眠状态,跟主线程执行时间过长引起 ANR 完全是两回事

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

    // .......

    for (;;) {
        // MessageQueue 中获取出执行的消息
        Message msg = queue.next(); // might block
        if (msg == null) {
            // No message indicates that the message queue is quitting.
            return;
        }
        //.......
        try {
            // 执行消息,回调到 Handler#handlerMessage(Message)
            msg.target.dispatchMessage(msg);
            if (observer != null) {
                observer.messageDispatched(token, msg);
            }
            dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
        } catch (Exception exception) {
            if (observer != null) {
                observer.dispatchingThrewException(token, msg, exception);
            }
            throw exception;
        } finally {
            ThreadLocalWorkSource.restore(origWorkSource);
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }
        //.....
        // 执行完 msg,回收 msg 加入到回收池
        msg.recycleUnchecked();
    }
}

接着看 MessageQueue#next() 的实现,主要的工作原理是:

  1. 先判断队列的头指针是否为屏障消息,如果是的话就在队列里面查找异步消息,如果找到异步消息则判断是否到执行时间,如果是则返回异步消息 msg,如果没有找到或者还不到执行时间则查找是否有 IdleHandler。
  2. 如果队列的头指针是普通消息,则查看头指针是否到了执行时间,如果到了则返回头指针 msg,如果没到执行时间则查找是否有 IdleHandler。

    如果上面上面两种情况都不满足则在下一次轮询后调用 nativePollOnce 释放 cpu 资源,线程进入休眠
@UnsupportedAppUsage
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();
        }
        // 释放 cpu 资源,线程进入休眠,与 ptr 参数有关
        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()); // 仅获取出异步消息
            }
            // 这里分为两种情况
            // 第一种:如果当前头指针是屏障消息,并且遍历到队列中有异步消息则拿出异步消息执行,如果没有则表示没有可执行的消息,转而遍历是否有 IdleHandler
            // 第二种:如果当前头指针不是屏障消息,因为消息队列是根据执行时间先后的有序丢lie,则判断当前是否到了头指针的执行时间,如果是则拿出头指针,讲头指针指向下一个消息
            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;
            }
            // 如果消息对列为空,或者没有消息到执行时机,则看有没有 IdleHandler
            // 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;
    }
}

总结

  1. Handler 分为同步消息,屏障消息和异步消息
  2. 如果插入了屏障消息则会阻塞同步消息,只处理异步消息
  3. Message 的设计思想是链表和复用
  4. MessageQueue 的 msg 是根据执行时间先后顺序排序的
  5. MessageQueue 没有 msg 或者 IdleHandler 需要处理时会释放 CPU 资源进入休眠状态,直到有新消息插入或者到达消息的处理时机
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值