/*
* Set this flag to true to detect anonymous, local or member classes
* that extend this Handler class and that are not static. These kind
* of classes can potentially create leaks.
* 将此标志设置为true以检测此 Handler 类不是静态的匿名,本地或成员类。这些类
* 可能会产生泄漏。
*/
private static final boolean FIND_POTENTIAL_LEAKS = false;
/**
* Callback interface you can use when instantiating a Handler to avoid
* having to implement your own subclass of Handler.
* 你可以在你实例化一个 Handler 的时候使用 Callback 接口(就是我们说的回调接口)
* 避免必须实现一个 Handler 的子类。
*
* @param msg A {@link android.os.Message Message} object
* @return True if no further handling is desired
*/
public interface Callback {
public boolean handleMessage(Message msg);
}
/**
* Subclasses must implement this to receive messages.
* 子类必须实现这个方法来接受 Message 对象
*/
public void handleMessage(Message msg) {
}
/**
* Handle system messages here.
* 该方法用于处理系统的 Message
*/
public void dispatchMessage(Message msg) {
// 如果传入的 Message 的回调函数不为空
if (msg.callback != null) {
// 调用 handleCallback 方法
handleCallback(msg);
} else { // 不为空
if (mCallback != null) { // 如果 Handler 的 Callback 不为空
if (mCallback.handleMessage(msg)) { // 返回值为 true 调用 return
return;
}
}
handleMessage(msg);// 调用 handleMessage() 上面有介绍
}
}
/**
* Default constructor associates this handler with the {@link Looper} for the
* current thread.
*
* If this thread does not have a looper, this handler won't be able to receive messages
* so an exception is thrown.
* 默认的构造函数,通过当前线程的 Lopper 对象关联当前 Handler。
* 如果这个线程没有 Lopper,那么该 Handler 将无法接受 Message,因此会抛出一个异常。
*/
public Handler() {
this(null, false);
}
/**
* Constructor associates this handler with the {@link Looper} for the
* current thread and takes a callback interface in which you can handle
* messages.
*
* If this thread does not have a looper, this handler won't be able to receive messages
* so an exception is thrown.
*
* @param callback The callback interface in which to handle messages, or null.
* 处理 Message 的回调接口,或者传 null
* 相对于默认构造函数,添加了一个 Callback 参数,表示会通过该 Callback 对象处理 Message
*/
public Handler(Callback callback) {
this(callback, false);
}
/**
* Use the provided {@link Looper} instead of the default one.
*
* @param looper The looper, must not be null.
* Looper 对象,不能传入 null
* 使用传入的 Looper 代替默认的 Looper
*/
public Handler(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.
* 使用传入的 Looper 代替默认的,并且传入 Callback 用于处理 Message
*/
public Handler(Looper looper, Callback callback) {
this(looper, callback, false);
}
/**
* 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
* 使用当前线程默认的 Looper 并且设置该 Handler 是否需要是异步的。
* Handler 是默认同步的,除非你调用该构造函数设置表示使用异步。
* 异步消息相对于同步消息,不需要对消息进行同步排序,并且不受 MessageQueue 的 enqueueSyncBarrier(long) 所带来的同步障碍影响。
*/
public Handler(boolean async) {
this(null, async);
}
前面所有的构造函数本质上都是调用了下面两个构造函数,我们来看看构造函数到底做了什么?
/**
* Use the {@link Looper} for the current thread with the specified callback interface
* 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 callback The callback interface in which to handle messages, or null.
* @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.
* 使用当前默认 Looper 和传入的 Callback ,传入 boolean 来设置该 Handler 是否需要是异步的。
* @hide
*/
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"该 Handler 应该为 static ,否则可能会导致内存泄漏"
Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
klass.getCanonicalName());
}
}
// 获取 Looper
mLooper = Looper.myLooper();
if (mLooper == null) { // 获取到为 null 抛出异常 “无法在线程内部创建没有调用
// Looper.prepare() 方法的 handler”
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
// 从 Looper 获取 MessageQueue
mQueue = mLooper.mQueue;
// mCallback赋值
mCallback = callback;
// mAsynchronous 赋值
mAsynchronous = async;
}
/**
* Use the provided {@link Looper} instead of the default one and take a callback
* interface in which to handle messages. Also 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 looper The looper, must not be null.
* @param callback The callback interface in which to handle messages, or null.
* @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
* 添加了 Looper 参数指定 Looper,其余跟上一个一样。
*/
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
下面是各个方法的解读
getMessageName(Message message):
该方法返回一个 Message 的指定名称(大概就是说返回一个唯一标识)。默认返回Message 的 Callback 的类名,如果 message.callback 为空,返回 Message.what 的十六进制数。obtainMessage():
该方法从全局的 Message Pool(消息池)返回一个 Message 对象。这样的效率比重新创建一个实例要高。并设置 Message.target == this。如果你不想用这种方法,可以直接调用 Message.obtain()。obtainMessage(int what):
和 obtainMessage() 一样,但是给返回的 Message 对象设置了 what 。obtainMessage(int what, Object obj):
obtainMessage(int what, int arg1, int arg2):
obtainMessage(int what, int arg1, int arg2, Object obj):
与 obtainMessage() 相同,但是设置了 whta 和 obj 两个属性。public final boolean post(Runnable r):
添加 Runnable 对象到 MessageQueue 中。该 Runnable 对象将会在该 Handler bain绑定到的 Thread 上运行。public final boolean postAtTime(Runnable r, long uptimeMillis):
添加 Runnable 对象到 MessageQueue 中。该 Runnable 对象将会在给定的时间点运行。返回:true 表示该 Runnable 成功添加到 MessageQueue 中,否则返回 false,通常是因为 Looper 处理 MessageQueue 正在退出。注意,返回 true 并不意味着该 Runnable 一定会被执行 -- 如果 Looper 在 Message 送达时间之前 quit,那么 Message 将会丢失。