携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第25天,点击查看活动详情 >> 希望大家可以帮忙点个赞,谢谢!
前言
前面我们说到dispatchMessage方法,今天我们继续往下看源码。
正篇
首先后面有两个抛弃的方法:
@Deprecated
public Handler() {
this(null, false);
}
@Deprecated
public Handler(@Nullable Callback callback) {
this(callback, false);
}
这两个默认构造方法因为不安全,它们与当前线程的 Looper 相关联,而如果该线程没有 Looper,则该处理程序将无法接收消息,从而会引发异常。 接着我们继续看其他构造方法:
/**
* Use the provided {@link Looper} instead of the default one.
*
* @param looper The looper, must not be null.
*/
public Handler(@NonNull Looper looper) {
this(looper, null, false);
}
/**
* 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(@NonNull Looper looper, @Nullable Callback callback) {
this(looper, callback, false);
}
其中第一个构造函数是使用提供的Looper而不是默认的,且参数looper不能为空;
而第二个构造函数与第一个类似,不过增加了一个回调接口来处理消息,该回调接口可以为null
这里要注意的是这里调用的this()方法中的boolean参数是用来判断是否需要异步处理消息,后面的其他构造函数注释中有相应的解释。
我们接着往下看:
/**
* 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
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
public Handler(boolean async) {
this(null, async);
}
这个构造方法是为当前线程使用 Looper 并设置handler是否应该是异步的。我们在默认情况下,Handlers是同步的,除非使用此构造函数来创建一个严格异步的Handler。注释翻译说: 异步消息表示不需要对同步消息进行全局排序的中断或事件,而且异步消息不受 MessageQueue.enqueueSyncBarrier(long) 引入的同步屏障的影响。
参数:async – 如果为 true,则处理程序为发送给它的每个 Message 或发布给它的 Runnable 调用 Message.setAsynchronous(boolean)。
(未完待续)