从源码与官方文档看之Handler篇(五)

83 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第27天,点击查看活动详情 >> 希望大家可以帮忙点个赞,谢谢!

前言

尽管前路坎坷,可我们还是继续走了下去,一转眼已经又到了第五篇了,每篇内容较少,所以后面整理完时,会汇总成一篇文章,相信这样做会更具有可读性。

正篇

首先我们继续看代码:

/**
 * Create a new Handler whose posted messages and runnables are not subject to
 * synchronization barriers such as display vsync.
 *
 * <p>Messages sent to an async handler are guaranteed to be ordered with respect to one another,
 * but not necessarily with respect to messages from other Handlers.</p>
 *
 * @see #createAsync(Looper, Callback) to create an async Handler with custom message handling.
 *
 * @param looper the Looper that the new Handler should be bound to
 * @return a new async Handler instance
 */
@NonNull
public static Handler createAsync(@NonNull Looper looper) {
    if (looper == null) throw new NullPointerException("looper must not be null");
    return new Handler(looper, null, true);
}

从方法名可以看出,这是用来创建异步的Handler的方法,方法内容可看出这是这个方法能对Looper线程判空。注释的大意如下:
创建一个新的 Handler,其发布的消息和可运行对象不受同步障碍(例如显示 vsync(垂直同步))的影响。 保证发送到异步处理程序的消息是相对于彼此排序的,但不一定相对于来自其他处理程序的消息。
参数: looper – 新 Handler 应该绑定到的 Looper 回报: 一个新的异步处理程序实例 也可以看看: 使用自定义消息处理创建异步处理程序。

接着我们看下一个方法:

/**
 * Create a new Handler whose posted messages and runnables are not subject to
 * synchronization barriers such as display vsync.
 *
 * <p>Messages sent to an async handler are guaranteed to be ordered with respect to one another,
 * but not necessarily with respect to messages from other Handlers.</p>
 *
 * @see #createAsync(Looper) to create an async Handler without custom message handling.
 *
 * @param looper the Looper that the new Handler should be bound to
 * @return a new async Handler instance
 */
@NonNull
public static Handler createAsync(@NonNull Looper looper, @NonNull Callback callback) {
    if (looper == null) throw new NullPointerException("looper must not be null");
    if (callback == null) throw new NullPointerException("callback must not be null");
    return new Handler(looper, callback, true);
}

注释大意:
创建一个新的 Handler,其发布的消息和可运行对象不受同步障碍(例如显示 vsync)的影响。
保证发送到异步处理程序的消息是相对于彼此排序的,但不一定相对于来自其他Handler的消息。
参数:
looper – 新创建的Handler 应该绑定到的 Looper线程
返回:
一个新的异步处理程序实例 也可以看看: 创建一个没有自定义消息处理的异步处理程序。 (未完待续)