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. Android模仿iOS iMessages10照片选择器的实现

    不知不觉已经接近半年多没有写过博客了,这段时间,也是我刚好毕业走出校园的时间,由于学习工作的原因,一直没有真正静下心来写下些什么东西.这个星期刚入了小米笔记本pro的坑,本着新电脑新生活的理念嘻嘻-- ...

  2. css中的em用法

    px:是相对于浏览器分辨率的一个度量单位 em是一个相对于父元素的font-size的大小的一个度量单位 1.浏览器的默认字体大小是16px 2.如果元素自身没有设置字体大小,那么元素自身上的所有属性 ...

  3. CentOS6软raid配置与管理

    事先添加硬盘设备sdb.sdc.sdd.sde.无论是物理硬盘还是虚拟硬盘,最好使用同型号同大小的硬盘. 创建raid设备 支持raid0.1.4.5.6级别 # mdadm -C /dev/md0 ...

  4. Javascript 内核Bug

    Javascript 内核Bug: js 执行(9.9+19.8)加法运算 等于 29.700000000000003) <html> <head> <title> ...

  5. wkt转换geojson

    应用配置 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.o ...

  6. JavaScript 经典之一 闭包

    作为一个前端开发者,闭包是必须要攻克掉的障碍.据说好多面试者挂在闭包面试上.下面我就给大家讲一下我理解中的闭包.不说太多的废话,直接进入主题. 变量作用域 学习编程语言需要明白,变量的作用域.变量作用 ...

  7. 《Linux命令行与shell脚本编程大全》 第八章管理文件系统

    8.1 探索linux文件系统 8.1.1 基本的Linux文件系统 ext:最早的文件系统,叫扩展文件系统.使用虚拟目录操作硬件设备,在物理设备上按定长的块来存储数据. 用索引节点的系统来存放虚拟目 ...

  8. [转载] 解读ClassLoader

    转载自http://www.iteye.com/topic/83978 ClassLoader一个经常出现又让很多人望而却步的词,本文将试图以最浅显易懂的方式来讲解 ClassLoader,希望能对不 ...

  9. Redis 图形化监控方案 RedisLive 介绍

    作为一款开源的 Redis 图形化监控工具,RedisLive 提供对 Redis 实例的内存使用情况,接收的客户端命令,接收的请求数量以及键进行监控.RedisLive 的工作原理基于 Redis ...

  10. PHP编辑器PhpStrom运行缓慢问题

    最近在使用phpstorm开发项目的时候,在加载文件运行时,不管有多大,如果项目文件数据比较多的话,都能够让phpstorm卡到死机.其中调整过内存设置,关闭过动态提示,使用过phpstorm的安全模 ...