handler
Looper 轮询器
MessageQueue 消息对象 1 主线程在一创建的时候就会调用, public static void prepareMainLooper() {}构造方法。 public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
} 2 在prepareMainLooper(){} 内部调用了 prepare(false);方法,这就是在子线程中new Handler()会抱错的关键 prepare(quitAllowed) {}方法里面设置了一个Looper对象。假设已经有了 Looper 对象,会抛出异常 Only one Looper may be created per thread
所以说一个 Handler仅仅能有一个Looper对象
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));//创建一个 Looper构造器
} 3 在 Looper 的构造器中
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);//创建了 MessageQueue对象
mRun = true;
mThread = Thread.currentThread();//线程对象
} 4 可是在 handler(){}的源代码构造方法中
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;
} 5 查看 Looper.myLooper();
public static Looper myLooper() {
return sThreadLocal.get();//返回的是一个 Looper对象。这里就跟 2的结果一样了
}
所以在4 中抛出异常。跟2 也一样了
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
所以敢肯定(1 2 3)的原理就是主线程 Handler的工作原理
而 (4 5)就是我们手动创建 Handler的时候的工作原理。 handler.sendMessage(msg);他做的是将消息入队操作
6 经过源代码跟踪。会发如今调用enqueueMessage(){}构造方法的时候。所做的事情就是将消息即可。入栈处理
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);//注意这里。想必从字面意思理解,enqueueMessage就是入栈的意思吧
} 7 看enqueueMessage()所做的事情
final boolean enqueueMessage(Message msg, long when) {
if (msg.isInUse()) {
throw new AndroidRuntimeException(msg + " This message is already in use.");
}
if (msg.target == null) {
throw new AndroidRuntimeException("Message must have a target.");
} boolean needWake;
synchronized (this) {
if (mQuiting) {
RuntimeException e = new RuntimeException(
msg.target + " sending message to a Handler on a dead thread");
Log.w("MessageQueue", e.getMessage(), e);
return false;
} msg.when = when;
Message p = mMessages;
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg; //将消息对象的引用赋值给 Message
needWake = mBlocked;
} else {
// Inserted within the middle of the queue. Usually we don't have to wake
// up the event queue unless there is a barrier at the head of the queue
// and the message is the earliest asynchronous message in the queue.
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
msg.next = p; // invariant: p == prev.next
prev.next = msg; //将消息对象的引用赋值给 Message
}
}
if (needWake) {
nativeWake(mPtr);
}
return true;
}
8 那么问题来了。消息引用都传递给Message对象了。那是怎样从 Message中吧消息分发出去。并响应呢?这就得看 Looper的源代码中的 public static void loop() {}方法
事实上 loop就是一个轮询器,在不断的从 MessageQueue中获取消息,能够看 loop()中的 Message msg = queue.next(); 内部实现源代码,next() 方法就是消息队列的出队方法。 只是因为这种方法的代码略微有点长,我就不贴出来了,它的简单逻辑就是假设当前MessageQueue中存在mMessages(即待处理消息),就将这个消息出队,然后让下一条消息成为mMessages。否则就进入一个堵塞状态,一直等到有新的消息入队
public static void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue; // Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity(); for (;;) {//天呐,在这里竟然是 for的空循环
//queue.next() 出现了,有兴趣的能够点进去看看
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
} // This must be in a local variable, in case a UI event sets the logger
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
} msg.target.dispatchMessage(msg);//我们又发现了什么?对。msg.target代表的是Handler,调用了dispatchMessage方法
// 这样我相信大家就都明确了为什么handleMessage()方法中能够获取到之前发送的消息了吧! if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
} // Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed from 0x"
+ Long.toHexString(ident) + " to 0x"
+ Long.toHexString(newIdent) + " while dispatching to "
+ msg.target.getClass().getName() + " "
+ msg.callback + " what=" + msg.what);
} msg.recycle();
}
}

handler 源代码分析的更多相关文章

  1. Android之Handler源代码深入解析

    闲着没事.就来看看源代码,看看源代码的各种原理,会用仅仅是简单的,知道为什么才是最牛逼的. Handler源代码分析那,从使用的步骤来边用边分析: 1.创建一个Handler对象:new Handle ...

  2. hostapd源代码分析(二):hostapd的工作机制

    [转]hostapd源代码分析(二):hostapd的工作机制 原文链接:http://blog.csdn.net/qq_21949217/article/details/46004433 在我的上一 ...

  3. Hadoop源代码分析

    http://wenku.baidu.com/link?url=R-QoZXhc918qoO0BX6eXI9_uPU75whF62vFFUBIR-7c5XAYUVxDRX5Rs6QZR9hrBnUdM ...

  4. Android应用程序消息处理机制(Looper、Handler)分析

    文章转载至CSDN社区罗升阳的安卓之旅,原文地址:http://blog.csdn.net/luoshengyang/article/details/6817933 Android应用程序是通过消息来 ...

  5. Android系统默认Home应用程序(Launcher)的启动过程源代码分析

    在前面一篇文章中,我们分析了Android系统在启动时安装应用程序的过程,这些应用程序安装好之后,还需要有一个 Home应用程序来负责把它们在桌面上展示出来,在Android系统中,这个默认的Home ...

  6. Android应用程序进程启动过程的源代码分析

    文章转载至CSDN社区罗升阳的安卓之旅,原文地址: http://blog.csdn.net/luoshengyang/article/details/6747696 Android 应用程序框架层创 ...

  7. Android应用程序绑定服务(bindService)的过程源代码分析

    文章转载至CSDN社区罗升阳的安卓之旅,原文地址:http://blog.csdn.net/luoshengyang/article/details/6745181 Android应用程序组件Serv ...

  8. Android 消息处理源代码分析(1)

    Android 消息处理源代码分析(1) 在Android中,通常被使用的消息队列的代码在文件夹\sources\android-22\android\os下,涉及到下面几个类文件 Handler.j ...

  9. Memcached源代码分析 - Memcached源代码分析之消息回应(3)

    文章列表: <Memcached源代码分析 - Memcached源代码分析之基于Libevent的网络模型(1)> <Memcached源代码分析 - Memcached源代码分析 ...

随机推荐

  1. Linux修改时区的正确方法

    CentOS和Ubuntu的时区文件是/etc/localtime,但是在CentOS7以后localtime以及变成了一个链接文件 [root@centos7 ~]# ll /etc/localti ...

  2. JS5模拟类

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  3. PHPMailer < 5.2.18 远程代码执行漏洞(CVE-2016-10033)

    PHPMailer < 5.2.18 Remote Code Execution 本文将简单展示一下PHPMailer远程代码执行漏洞(CVE-2016-10033)的利用过程,使用的是别人已经 ...

  4. 解决autocad闪退

    1.进入注册表,regedit 2.找到ROOT\installer\Products ,找到以7D2F开头的键值,这里有两个都得删除 3.删除programdata目录下的AutoDesk目录,及f ...

  5. Maven 编译错误 Dynamic Web Module 3.0 requires Java 1.6 or newer 解决方案

    Eclipse Maven 开发一个 jee 项目时,编译时遇到以下错误:Description Resource Path Location TypeDynamic Web Module 3.0 r ...

  6. spirngMVC的搭建

    1 springMVC的搭建肯定是需要用到一系列的jar包的,那么第一步就是去spring官网下载对应版本的jar包 可以通过 http://www.cnblogs.com/imentors/p/49 ...

  7. Redis Save 与 BGSAVE 的区别

    一,save保存数据到磁盘的方式: Redis Save 命令执行一个同步保存操作,将当前 Redis 实例的所有数据快照(snapshot)以 RDB 文件的形式保存到硬盘. 语法redis Sav ...

  8. Unity3D高性能战争迷雾实现

    效果图 先上效果图吧,这是为了吸引到你们的ヽ(。◕‿◕。)ノ゚ 战争迷雾效果演示图 战争调试界面演示图 由于是gif录制,为了压缩图片,帧率有点低,实际运行时,参数调整好是不会像这样一卡一顿的. 战争 ...

  9. Microsoft SQL Server 2008 R2数据库备份 - 人工备份

    业务介绍 数据库人工备份是指由相关管理人员通过主动的手工方式备份数据库文件.在一些特殊的时间节点,如重要资料的录入完成.软硬件环境更新前等需要特别关注数据库安全的时候,一定要进行数据库的人工备份,以保 ...

  10. ASP.NET Core教程【三】实体字段属性、链接标签、并发数据异常、文件上传及读取

    前文索引:ASP.NET Core教程[二]从保存数据看Razor Page的特有属性与服务端验证ASP.NET Core教程[一]关于Razor Page的知识 实体字段属性 再来看看我们的实体类 ...