Android Handler机制(四)---Handler源码解析
Handler的主要用途有两个:(1)、在将来的某个时刻执行消息或一个runnable,(2)把消息发送到消息队列。
主要依靠post(Runnable)、postAtTime(Runnable, long)、postDelayed(Runnable, long)、sendEmptyMessage(int)、sendMessage(Message)、sendMessageAtTime(Message)、sendMessageDelayed(Message, long)这些方法来来完成消息调度。post方法是当到Runable对象到达就被插入到消息队列;sendMessage方法允许你把一个包含有信息的Message插入队列,而且它会Handler的handlerMessage(Message)方法中执行(该方法要求在Handler的子类中实现)。
1.构造方法
/** 默认的构造方法,handler是和当前线程的队列关联在一起,如果队列不存在,那么handler就不能接受消息。
* Default constructor associates this handler with the {@link Looper} for the
* current thread.
* 如果线程没有looper,就会抛出异常
* If this thread does not have a looper, this handler won't be able to receive messages
* so an exception is thrown.
*/
public Handler() {
this(null, false);
}
//传入一个callback接口用于处理handler传递的Message。
public Handler(Callback callback) {
this(callback, false);
} //给变量赋值
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.w(TAG, "The following Handler class should be static or leaks might occur: " +
klass.getCanonicalName());
}
} mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
} public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
方法都差不多,主要是完成了赋值的过程,还有几个没粘贴,但是都差不多。。。
2.变量
/*
设置这个标记为true来检测不是静态的匿名,本地或成员类继承Handler类。这些类型的类可以带来潜在的泄漏。在Handler的构造方法里面使用到了这个参数,目的就如上所述。
*/
private static final boolean FIND_POTENTIAL_LEAKS = false;
final MessageQueue mQueue;
final Looper mLooper;
final Callback mCallback; //回调接口
final boolean mAsynchronous;
IMessenger mMessenger;
接着下面就是Callback接口:
/**
* Callback interface you can use when instantiating(实例化) a Handler to avoid
* having to implement(实现) your own subclass of 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);
}
callback接口你可以在实例化的时候用,避免去实现你自己的handler子类
这个Callback接口里只有一个handleMessage方法返回boolean值,在后面Handler的ctor会用到,一般情况下都是null。这个接口的存在
没什么特殊的含义,只是为了让你不extends Handler就能处理消息而已(正如此方法的doc所说),类似Thread和Runnable接口的关系。
3.handleMessage
/**
* Subclasses must implement this to receive messages.
*/
public void handleMessage(Message msg) {
}
子类需要实现这个方法,因为这是个空方法。
4.dispatchMessage
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
private static void handleCallback(Message message) {
message.callback.run();
}
它的处理是如果message自身设置了callback,则
直接调用callback.run()方法,否则Callback接口的作用就显现了;如果我们传递了Callback接口的实现,即mCallback非空,则调用它处理
message,如果处理了,返回true,则直接返回,否则接着调用Handler自己的handleMessage方法,其默认实现是do nothing,如果你
是extends Handler,那么你应该在你的子类中为handleMessage提供自己的实现。
5.一系列obtainMessage
public final Message obtainMessage()
{
return Message.obtain(this);
}
public final Message obtainMessage(int what)
{
return Message.obtain(this, what);
}
public final Message obtainMessage(int what, int arg1, int arg2, Object obj)
{
return Message.obtain(this, what, arg1, arg2, obj);
}
从上面可以看出来还是调用的Message的obtain方法,来构造message。
6.一系列postXXX方法:
/**
* Causes the Runnable r to be added to the message queue.
* The runnable will be run on the thread to which this handler is
* attached.
*
* @param r The Runnable that will be executed.
*
* @return Returns true if the Runnable was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*/
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
public final boolean postAtTime(Runnable r, long uptimeMillis)
{
return sendMessageAtTime(getPostMessage(r), uptimeMillis);
}
public final boolean postAtTime(Runnable r, Object token, long uptimeMillis)
{
return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
}
public final boolean postDelayed(Runnable r, long delayMillis)
{
return sendMessageDelayed(getPostMessage(r), delayMillis);
}
public final boolean postAtFrontOfQueue(Runnable r)
{
return sendMessageAtFrontOfQueue(getPostMessage(r));
}
上面方法的作用就是:把Runnable发送到消息队列,执行的时候实行Runnable的run方法。。
下面看一系列sendXXX方法,和上边对应的。。。
//把消息入队
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
MessageQueue queue = mQueue;
if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
return false;
}
return enqueueMessage(queue, msg, uptimeMillis);
}
public final boolean sendEmptyMessage(int what)
{
return sendEmptyMessageDelayed(what, 0);
上面所有的postXXX,sendXXX方法最后都会调用这个方法:enqueueMessage
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
最后调用queue的enqueueMessage方法把msg入队,对这个方法不了解的,可以看前边的MessageQueue源码解析。
SystemClock.uptimeMillis(),就是表示系统开机到当前的时间总数,如果有延迟,就加上延迟时间,分析到现在,我们也能发现,postDelayed不是延迟多少秒发送消息,这个消息是直接发送给队列的,不过在MessaegQueue中,消息按时间排放的,不到时间不会把它取出来,所以应该说延迟多少秒取出消息更合适。。
至于上边的getPostMessage(r)就是把r设置给callback。
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
removeCallbacks:
调用MQ的removeMessages方法。就是移出messageQueue中所有满足条件的message,当然前提是消息还没取走。
/**
* Remove any pending posts of Runnable r that are in the message queue.
*/
public final void removeCallbacks(Runnable r)
{
mQueue.removeMessages(this, r, null);
}
/**
* Remove any pending posts of Runnable <var>r</var> with Object
* <var>token</var> that are in the message queue. If <var>token</var> is null,
* all callbacks will be removed.
*/
public final void removeCallbacks(Runnable r, Object token)
{
mQueue.removeMessages(this, r, token);
}
分析结束,鼓励自己下。。哈哈哈。。。。
前三篇传送门: Looper源码解析: http://www.cnblogs.com/jycboy/p/5787443.html
MessageQueue源码解析:http://www.cnblogs.com/jycboy/p/5786682.html
Message源码解析:http://www.cnblogs.com/jycboy/p/5786551.html
Android Handler机制(四)---Handler源码解析的更多相关文章
- Android Handler机制(三)----Looper源码解析
一.Looper Looper对象,顾名思义,直译过来就是循环的意思,从MessageQueue中不断取出message. Class used to run a message loop for a ...
- Android Handler机制(二)---MessageQueue源码解析
MessageQueue 1.变量 private final boolean mQuitAllowed;//表示MessageQueue是否允许退出 @SuppressWarnings(" ...
- Handler机制原理图、源码、使用!!!!!
android的消息处理机制——Looper,Handler,Message (原理图.源码) 转自:http://my.oschina.net/u/1391648/blog/282892 在开始讨 ...
- Android IntentService使用介绍以及源码解析
版权声明:本文出自汪磊的博客,转载请务必注明出处. 一.IntentService概述及使用举例 IntentService内部实现机制用到了HandlerThread,如果对HandlerThrea ...
- 【Android应用开发】EasyDialog 源码解析
示例源码下载 : http://download.csdn.net/detail/han1202012/9115227 EasyDialog 简介 : -- 作用 : 用于在界面进行一些介绍, 说明; ...
- Android事件总线(四)源码解析otto
前言 上一篇文章中讲到了otto的用法,这一篇我们来讲一下otto的源码.可能有人觉得otto过时了,但是通过源码我们学习的是高手设计otto时的设计理念,这种设计理念是不过时的. otto各个类的作 ...
- Android FM 模块学习之四 源码解析(1)
Normal 0 7.8 磅 0 2 false false false EN-US ZH-CN X-NONE MicrosoftInternetExplorer4 前一章我们了解了FM手动调频,接下 ...
- Android HandlerThread使用介绍以及源码解析
摘要: 版权声明:本文出自汪磊的博客,转载请务必注明出处. 一.HandlerThread的介绍及使用举例 HandlerThread是什么鬼?其本质就是一个线程,但是Han ...
- Android FM模块学习之四源码解析(一)
转自:http://blog.csdn.net/tfslovexizi/article/details/41516149?utm_source=tuicool&utm_medium=refer ...
随机推荐
- Azure China (12) 域名备案问题
<Windows Azure Platform 系列文章目录> (1) 默认情况下,我们在创建的Azure 服务,默认使用的DNS地址为: http://xxx.chinacloudapi ...
- SQL Server代理(3/12):代理警报和操作员
SQL Server代理是所有实时数据库的核心.代理有很多不明显的用法,因此系统的知识,对于开发人员还是DBA都是有用的.这系列文章会通俗介绍它的很多用法. 如我们在这个系列的文章里所见,SQL Se ...
- 总结Unity IOC容器通过配置实现类型映射的几种基本使用方法
网上关于Unity IOC容器使用的方法已很多,但未能做一个总结,故我这里总结一下,方便大家选择. 首先讲一下通过代码来进行类型映射,很简单,代码如下: unityContainer = new Un ...
- 学习ASP.NET Web API框架揭秘之“HTTP方法重写”
最近在看老A的<ASP.NET Web API 框架揭秘>,这本书对于本人现阶段来说还是比较合适的(对于调用已经较为熟悉,用其开发过项目,但未深入理解过很多内容为何可以这样“调用”).看到 ...
- 解决360、猎豹浏览器等极速模式下css3兼容问题
有时候你会发现你写的animation动画的css3效果,在IE.谷歌.火狐等主流的新版本的浏览器的是没有什么兼容问题的,即便你不写前缀,也是可以显示动画效果的.然后,你本地在360浏览器或猎豹浏览器 ...
- Python语言特性之1:函数参数传递
问题:在Python文档中好像没有明确指出一个函数参数传递的是值传递还是引用传递.如下面的代码中"原始值"是不放生变化的: class PassByReference: def _ ...
- 用php怎么写一个用户注册登录的页面呢?
想写就会尽快去写.如果用php写了就一定要用nodejs写出来啊,不写是小狗啊! 补充一下,想要实现的功能: 1.用户名重复检测 2.检测信息填写是否完整 3.邮箱是否已经被注册 4.实现ajax无刷 ...
- C语言学习008:标准错误
在上一节中的数据文件中(C语言学习007:重定向标准输入和输出),如果文件中的数据包含非法数据,如何让程序显示一条错误的提示消息呢?就需要用到标准错误 #include <stdio.h> ...
- 代码生成工具Database2Sharp中增加视图的代码生成以及主从表界面生成功能
在代码生成工具的各种功能规划中,我们一向以客户的需求作为驱动,因此也会根据需要增加一些特殊的功能或者处理.在实际的开发中,虽然我们一般以具体的表进行具体业务开发,但是有些客户提出有时候视图开发也是很常 ...
- Oracle 表分组 group by和模糊查询like
分组group by写法 select 字段名 from 表名 group by 字段名 查询这个字段名里的种类分组后可以加聚合函数select 字段名,聚合函数 from 表名 group by 字 ...