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

144 阅读2分钟

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

前言

今天是八月的倒数第二天,Handler类才看了三分之一不到:

image.png 接下来就是我们可以正常调用的Handler类方法了,希望早日完成Handler类的源码阅读。

正篇

我们继续看源码:

/**
 * Returns a string representing the name of the specified message.
 * The default implementation will either return the class name of the
 * message callback if any, or the hexadecimal representation of the
 * message "what" field.
 *  
 * @param message The message whose name is being queried 
 */
@NonNull
public String getMessageName(@NonNull Message message) {
    if (message.callback != null) {
        return message.callback.getClass().getName();
    }
    return "0x" + Integer.toHexString(message.what);
}

这个方法从名称上可知是用来查询Message对象即消息的名称,注释大意是说此方法返回一个表达特定消息名称的字符串。默认实现将返回消息回调的类名(如果有的话)或者消息“what”字段的十六进制表示。而且用了@nonnull表示该方法不为空。而message参数则是用正被查询名称的消息对象。 接着我们看下一个方法:

/**
 * Returns a new {@link android.os.Message Message} from the global message pool. More efficient than
 * creating and allocating new instances. The retrieved message has its handler set to this instance (Message.target == this).
 *  If you don't want that facility, just call Message.obtain() instead.
 */
@NonNull
public final Message obtainMessage()
{
    return Message.obtain(this);
}

方法名可知是用来获取消息的,注释解释道:该方法可以返回一个新的Message对象且器是从全局消息池中获取的,比创建和分配新实例更有效。检索到的消息将其处理程序设置为此实例(Message.target == this)。如果您不想要该功能,只需调用 Message.obtain() 即可。
(未完待续)

总结

Handler类的方法阅读正式开始,后面将会更加深入的看这些方法的写法与如何使用,以及它们所出现的原因等,让我们更容易去理解这个Handler类。