结合源代码分析android的消息机制
描写叙述
開始看源代码
1.View的绘制都是从ViewRootImpl这个类開始,我们在这个类中找找。为什么异步线程不能更新UI。发现了这种方法
void checkThread() {
if (mThread != Thread.currentThread()) {
throw new CalledFromWrongThreadException(
"Only the original thread that created a view hierarchy can touch its views.");
}
}
当中mThread就是大名鼎鼎的UI线程,这段代码说明不是UI线程就直接抛异常,相当粗暴。
接着我们发现
@Override
public void requestFitSystemWindows() {
checkThread();
mApplyInsetsRequested = true;
scheduleTraversals();
} @Override
public void requestLayout() {
if (!mHandlingLayoutInLayoutRequest) {
checkThread();
mLayoutRequested = true;
scheduleTraversals();
}
}
2.接着看Handler,当我们new出一个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;
}
这个构造器最直接。
首先须要一个Looper,哪里来的?在子线程中,我们通常要运行Looper.prepare()
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对象,而且存在了threadLocal中。当Looper创建的时候,同一时候创建了消息队列
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
当handler构造时。调用Looper.myLooper()方法,从threadLocal中取出新建的Looper对象。假设你没用调用Looper.myLooper(),运行下边代码就遇到那个熟悉的异常了。
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
在主线程中没用调用。为什么没有报错?由于ActivityThread帮你调了
Looper.prepareMainLooper(); ActivityThread thread = new ActivityThread();
thread.attach(false); if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
} if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
} // End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();
看Looper.prepareMainLooper()和Looper.loop()都调了。
3.再看下Handler的post和send方法。Message怎么被Handler送进MessageQueue的。发现最后他们都进了这种方法
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
通过enqueueMessage方法将消息体也就是Message对象压入MessageQueue中。
4,然后调用Looper.loop(),開始处理消息
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
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 (;;) {
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); 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.recycleUnchecked();
}
}
一个死循环,然后不断通过queue.next()方法把Message从MessageQueue中取出来处理
5.将消息取出来后,通过调用msg.target.dispatchMessage(msg)来处理消息。msg.target指的是Handler对象,来详细看下:
/**
* 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);
}
}
这种方法说明当有Runnable对象(handler.post(new
Runnable())设置)时,消息交给handleCallback()处理
private static void handleCallback(Message message) {
message.callback.run();
}
直接调用了Runnable的run方法。这也解释了handler.post(new
Runnable())时没有新建线程的问题。当有mCallBack(new Handler(new CallBack())时设置),调用callBack的方法handlerMessage()。都没有,则调用Handler的handlerMessage方法。
6.自此消息基本从 产生->增加队列->处理 过程基本走通了。
总结
遗留问题
Log.e("---1---", String.valueOf(Thread.currentThread())
+ "\nThreadID:" + Thread.currentThread().getId());
new Thread(new Runnable() {
@Override
public void run() {
try {
Looper.prepare();
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Log.e("---3---", String.valueOf(Thread.currentThread())
+ "\nThreadID:" + Thread.currentThread().getId());
btn.setText("handlerMessage");
}
};
Log.e("---2---", String.valueOf(Thread.currentThread())
+ "\nThreadID:" + Thread.currentThread().getId());
handler.sendEmptyMessage(0);
handler.sendEmptyMessageDelayed(0, 2000);
handler.post(new Runnable() {
@Override
public void run() {
Log.e("---4---", String.valueOf(Thread.currentThread())
+ "\nThreadID:" + Thread.currentThread().getId());
btn.setBackgroundColor(Color.YELLOW);
}
});
Looper.loop();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
Only the original thread that created a view hierarchy can touch its views.
而延时的第二个3,不能成功更新UI,为什么?
结合源代码分析android的消息机制的更多相关文章
- 【原创】源码角度分析Android的消息机制系列(五)——Looper的工作原理
ι 版权声明:本文为博主原创文章,未经博主允许不得转载. Looper在Android的消息机制中就是用来进行消息循环的.它会不停地循环,去MessageQueue中查看是否有新消息,如果有消息就立刻 ...
- 【原创】源码角度分析Android的消息机制系列(一)——Android消息机制概述
ι 版权声明:本文为博主原创文章,未经博主允许不得转载. 1.为什么需要Android的消息机制 因为Android系统不允许在子线程中去访问UI,即Android系统不允许在子线程中更新UI. 为什 ...
- 【原创】源码角度分析Android的消息机制系列(二)——ThreadLocal的工作过程
ι 版权声明:本文为博主原创文章,未经博主允许不得转载. 在上一篇文章中,我们已经提到了ThreadLocal,它并非线程,而是在线程中存储数据用的.数据存储以后,只能在指定的线程中获取到数据,对于其 ...
- 【原创】源码角度分析Android的消息机制系列(三)——ThreadLocal的工作原理
ι 版权声明:本文为博主原创文章,未经博主允许不得转载. 先看Android源码(API24)中对ThreadLocal的定义: public class ThreadLocal<T> 即 ...
- 【原创】源码角度分析Android的消息机制系列(六)——Handler的工作原理
ι 版权声明:本文为博主原创文章,未经博主允许不得转载. 先看Handler的定义: /** * A Handler allows you to send and process {@link Mes ...
- 【原创】源码角度分析Android的消息机制系列(四)——MessageQueue的工作原理
ι 版权声明:本文为博主原创文章,未经博主允许不得转载. MessageQueue,主要包含2个操作:插入和读取.读取操作会伴随着删除操作,插入和读取对应的方法分别为enqueueMessage和ne ...
- 《Android开发艺术探索》读书笔记 (10) 第10章 Android的消息机制
第10章 Android的消息机制 10.1 Android消息机制概述 (1)Android的消息机制主要是指Handler的运行机制,其底层需要MessageQueue和Looper的支撑.Mes ...
- Android的消息机制
一.简介 ①.我们不能在子线程中去访问UI空控件,这是时候只能通过Handler将更新UI的操作放到主线程中去执行 ②.Handler的组成:messageQueue和Looper的支持 ③.Mess ...
- Android 基础 十一 Android的消息机制
Handler是Android消息机制的上层接口,这使得在开发应用过程中我们只需要和Handler交互即可.Handler的使用过程很简单,通过它可以轻松地将一个任务切换到Handler所在的线程中去 ...
随机推荐
- web前端学习路线和步骤
H5+全栈工程师 (学习下列技术可以加QQ: 1416 7596 61)第一阶段:初级入门阶段基本功 1.HTML入门 Windows概述.浏览器概述.HTML简介.HTML标签详解.前端开发工具概 ...
- Oracle-2 - :超级适合初学者的入门级笔记--定义更改约束,视图,序列,索引,同义词
接着我上一篇的写,在这感觉到哇 内容好多啊 上一篇,纯手打滴,希望给个赞! 添加约束的语法: 使用 alter table 添加或删除约束,但是不能修改约束 有效化或无效化约束 添加not nul ...
- CLR之委托的揭秘(一)
初识委托: 在之前的学习中我们已经可以把对象,值,数组当作参数传递给方法,但是有没有可能把方法也当作参数传递给方法呢?有了这个想法于是就有了委托.方法当作一种参数去传递,但是方法有的 ...
- Python源码分析
- 【转】Entity Framework 5.0系列之约定配置
Code First之所以能够让开发人员以一种更加高效.灵活的方式进行数据操作有一个重要的原因在于它的约定配置.现在软件开发越来复杂,大家也都试图将软件设计的越来越灵活,很多内容我们都希望是可配置的, ...
- [转]ORACLE分区表的使用和管理
转自:http://love-flying-snow.iteye.com/blog/573303 废话少说,直接讲分区语法. Oracle表分区分为四种:范围分区,散列分区,列表分区和复合分区. 一: ...
- select * from 的一些心得
如何简单运用好 select * from语句,在不同的函数下,有不同的先后顺序. 语法格式 (代表先后顺便) (2)select 字段名 查询什么东西 (1)from 表名,从哪个表查询 例如:查询 ...
- Web攻击技术
Web攻击技术 1.针对Web的攻击技术 1.1.在客户端即可篡改请求 在Web应用中,从浏览器那接收到的Http的全部内容,都可以在客户端自由地变更.篡改,所以Web应用可能会接收到与预期数据不相同 ...
- GraphicsMagick的命令行使用示例
GraphicsMagick是从 ImageMagick 5.5.2 分支出来的,但是现在他变得更稳定和优秀,GM更小更容易安装.GM更有效率.GM的手册非常丰富GraphicsMagick的命令与I ...
- Nginx 搭建图片服务器
Nginx 搭建图片服务器 本章内容通过Nginx 和 FTP 搭建图片服务器.在学习本章内容前,请确保您的Linux 系统已经安装了Nginx和Vsftpd. Nginx 安装:http://www ...