handler源码分析
今天重新梳理了下,其实handler源码还算比较简单。
Hanlder关键类
Hanlder:发送和接收消息 Looper:用于轮询消息队列,一个线程只能有一个Looper Message: 消息实体 MessageQueue: 消息队列用于存储消息和管理消息
创建Looper
创建Looper的方法是调用Looper.prepare() 方法
在ActivityThread中的main方法中为我们prepare了
public static void main(String[] args) {
Environment.initForCurrentUser();
Looper.prepareMainLooper();//初始化looper
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
Looper.loop();//轮询
throw new RuntimeException("Main thread loop unexpectedly exited");
}
Looper.prepareMainLooper()
public static void prepareMainLooper() {
prepare(false);//主线程消息队列不可quit
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
消息机制的同步屏障
屏障的意思即为阻碍,顾名思义,同步屏障就是阻碍同步消息,只让异步消息通过。
HandlerThread是什么?为什么它会存在?
HandlerThread是Thread的子类,严格意义上来说就是一个线程,只是它在自己的线程里面帮我们创建了Looper HandlerThread 存在的意义如下:
1) 方便使用:a. 方便初始化,b,方便获取线程looper
2)保证了线程安全
我们一般在Thread里面 线程Looper进行初始化的代码里面,必须要对Looper.prepare(),同时要调用Loop。 loop();
@Override public void run() {
Looper.prepare();
Looper.loop();
}
这篇handler完整的源码分析 博客已经讲的比较清楚了,不清楚的部分我再稍微结合源码进行分析,基本上掌握的差不多了,因为核心难点是在native层,也就是epoll机制,可参考这篇博客你知道Handler里还藏着一个epoll机制吗?.这篇博客没有讲到,我自己暂时也没能力研究,如有兴趣可参考handler中looper.loop()为什么不会阻塞这篇文章里面链接有提到,我自己也有点分析不下去就暂时作罢,如若后续有能力再分析吧.下面提供的几篇博客,主要是从面试角度、实际场景出发、为了检验效果、加深印象.
答案
1.handler中looper.loop()为什么不会阻塞,native层分析
2.handler中looper.loop()为什么不会阻塞,native层另外一种分析
3.handler为什么有可能造成内存泄漏及怎么解决
4.内存泄露分析
5. Handler十大必问
6.Handler二十七问 很核心 很难
handlerThread使用场景
这可参考这篇博客.