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

113 阅读2分钟

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

前言

今天是活动的最后一天啦,后面更文节奏可以舒缓一些了,每篇文章的篇幅也会长些许。 废话不多说,我们继续看Handler类。

正篇

上一篇我们看了不带参数的obtainMessage方法,现在我们来看看带参的:

/**
 * Same as {@link #obtainMessage()}, except that it also sets the what member of the returned Message.
 * 
 * @param what Value to assign to the returned Message.what field.
 * @return A Message from the global message pool.
 */
@NonNull
public final Message obtainMessage(int what)
{
    return Message.obtain(this, what);
}

该方法的参数what是分配给返回的 Message.what 字段的值,通俗来说就是message对象的key、名称,当然这个方法和obtainMessage()一样,是返回一个从全局消息池中的Message对象。 接下来的方法又在此基础上增加了一个参数@Nullable Object obj,即一个不为空的对象obj 成员:

/**
 * 
 * Same as {@link #obtainMessage()}, except that it also sets the what and obj members 
 * of the returned Message.
 * 
 * @param what Value to assign to the returned Message.what field.
 * @param obj Value to assign to the returned Message.obj field.
 * @return A Message from the global message pool.
 */
@NonNull
public final Message obtainMessage(int what, @Nullable Object obj) {
    return Message.obtain(this, what, obj);
}

此外,还有两个带参obtainMessage方法:

/**
 * 
 * Same as {@link #obtainMessage()}, except that it also sets the what, arg1 and arg2 members of the returned
 * Message.
 * @param what Value to assign to the returned Message.what field.
 * @param arg1 Value to assign to the returned Message.arg1 field.
 * @param arg2 Value to assign to the returned Message.arg2 field.
 * @return A Message from the global message pool.
 */
@NonNull
public final Message obtainMessage(int what, int arg1, int arg2)
{
    return Message.obtain(this, what, arg1, arg2);
}

/**
 * 
 * Same as {@link #obtainMessage()}, except that it also sets the what, obj, arg1,and arg2 values on the 
 * returned Message.
 * @param what Value to assign to the returned Message.what field.
 * @param arg1 Value to assign to the returned Message.arg1 field.
 * @param arg2 Value to assign to the returned Message.arg2 field.
 * @param obj Value to assign to the returned Message.obj field.
 * @return A Message from the global message pool.
 */
@NonNull
public final Message obtainMessage(int what, int arg1, int arg2, @Nullable Object obj) {
    return Message.obtain(this, what, arg1, arg2, obj);
}

通过带不同的参数去获取不同的消息,该方法到此结束。
(未完待续)

总结

今天主要将obtainMessage方法看完,下一次将去看我们安卓使用较为常见也是Handler极为重要的方法post()方法,去体会不同的post方法的功能与官方所给的注释大意。