android 结合源码深入剖析Handler机制原理
Handler机制原理已经被许多大佬写透的东西了,这里我们为什么还要说呢?因为对于许多初学者来说,也只是会使用Handler而已,对于其机制,也只是大概知道,今天我们来利用源码深入剖析其原理。
首先我们模拟一下工厂中的情景:
Handler:消息的处理者,工厂中流水线的工人。
Message:系统传递的消息,工厂中流水线上的产品。
MessageQueue:消息队列,工厂中流水线上的传送带。
Looper:发动机,工厂中使流水线的传送带运动的发动机。
来看源码分析,Handler主程序入口其实是在ActivityThread的main方法中进行的:
ActivityThread.java:
/在android应用程序的入口其实在ActivityThread的main方法
//在这里,主线程会创建一个Looper对象。
Looper.prepareMainLooper();
//执行消息循环
Looper.loop();
在main函数中,Looper调用了prepareMainLooper(), (准备主要消息泵) 我们再进去Looper看看。
public static void prepareMainLooper() {
//在主线程中,其默认初始化一个Looper对象,因此我们在主线程的操作中是不需要自己去调prepare()。
prepare(false);
synchronized (Looper.class) {
//这里先进行判断,在主线程是否已经存在Looper了,
// 避免我们手动去调用prepareMainLooper(),因为这个是给程序入口初始化的时候系统会自动调用的
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
//设置全局变量,主线程的looper
sMainLooper = myLooper();
}
}
注意这个函数的注释,大概意思是:在主线程创建一个looper,是这个主线程的主looper,当这个app在初始化的时候就会自行创建,因此这个函数不是给你们调用的,是给系统自身在程序创建的时候调用的。
继续往下看,有个prepare(boolean)函数,我们去看看这个到底是用来干什么的。
Looper.java:
private static void prepare(boolean quitAllowed) {
//先判断当前线程是否已经存在Looper了,如果存在,不允许设置新的Looper对象,一个线程只允许存在一个Looper
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
//在当前线程中,创建新的Looper对象,并绑定当前线程
sThreadLocal.set(new Looper(quitAllowed));
}
我们看到了sThreadLocal,我们先看看这个sThreadLocal在Looper是干什么用的。
//sThreadLocal在Looper中作为全局变量,用于保存每个线程中的数据,可以看做是容器
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
Looper中,sThreadLocal作为一个全局变量,sThreadLocal其实是保存Looper的一个容器,我们继续往ThreadLocal的get、set进行分析。
public T get() {
//获取当前线程保存的对象--通过get函数来获取Looper对象
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null)
return (T) e.value;
}
return setInitialValue();
}
public void set(T value) {
//把当前的looper保存到当前线程中
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
关键的代码:
Thread t=Thread.currentThread();
也就是说,我们的Looper对象分别保存在相对应的线程中。我们看回来我们的prepare(boolean)函数:
looper.java:
private static void prepare(boolean quitAllowed) {
//先判断当前线程是否已经存在Looper了,如果存在,不允许设置新的Looper对象,一个线程只允许存在一个Looper
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
//在当前线程中,创建新的Looper对象,并绑定当前线程
sThreadLocal.set(new Looper(quitAllowed));
}
Looper.prepare(boolean)的作用就是创建一个Looper对象,并与当前线程绑定在一起。在代码中,首先判断当前线程是否已经存在looper,如果不存在则创建新的looper并且绑定到当前的线程上。
再看回之前的代码:
looper.java:
public static void prepareMainLooper() {
//在主线程中,其默认初始化一个Looper对象,因此我们在主线程的操作中是不需要自己去调prepare()。
prepare(false);
synchronized (Looper.class) {
//这里先进行判断,在主线程是否已经存在Looper了,
// 避免我们手动去调用prepareMainLooper(),因为这个是给程序入口初始化的时候系统会自动调用的
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
//设置全局变量,主线程的looper
sMainLooper = myLooper();
}
}
分别看一下sMainLooper是什么,myLooper()又是什么?
Looper.java:
//保存一个主线程的looper
private static Looper sMainLooper; // guarded by Looper.class
public static Looper myLooper() {
//使用当前线程的looper
return sThreadLocal.get();
}
sMainLooper在Looper做为一个全局变量,保存主线程绑定的looper,myLooper()则是获取当前线程绑定的Looper。在prepareMainLooper()中,在主线程中创建一个新的Looper,并且绑定主线程中,同时把这个主线程的looper赋值给sMainLooer这个全局变量。
ActivityThread.java:
public static void main(String[] args) {
......
//在android应用程序的入口其实在ActivityThread的main方法
//在这里,主线程会创建一个Looper对象。
Looper.prepareMainLooper();
......
......
......
//执行消息循环
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
}
在应用程序ActivityThread.main入口中,系统除了调用Looper.prepareMainLooper,而且在最后还调用了Looper.loop(),这个函数有什么?大家脑补一下,工厂里的流水线上,除了有传送带外,如果你不让它动起来,那传送带也没什么作用,那么Looper.loop的作用就是让这个传送带动起来,也就是我们的让我们的消息队列动起来。
Looper.java:
/**
* 调用此函数用于启动消息队列循环起来,作用相当于工厂流水线中的传送带的开关,
* 只有把开关打开,传送带才跑起来
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static void loop() {
//先进行判断当前线程是否有绑定looper
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
//获取这个looper的消息队列
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
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
final long traceTag = me.mTraceTag;
if (traceTag != 0) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
//关键点,这里的msg.target也就是hanlder.看回代码hanlder.enqueueMessage()
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
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);
}
//最后回收这个message
msg.recycleUnchecked();
}
}
这一段代码比较长,我们挑有中文注释的来看,先判断当前的线程是否存在looper,如果存在获取保存在Looper的消息队列messagequeue,然后无限循环这个消息队列来获取message,注意我们留到了一段代码:
//关键点,这里的msg.target也就是hanlder.看回代码hanlder.enqueueMessage()
msg.target.dispatchMessage(msg);
msg.target其实就是我们的handler,无论是handler通过post或者sendEmptyMessage,最终都会调用到调到这个enqueueMessage(),在这里会将handler赋值到msg.target中.
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
//在message中放一个标记
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
//在这里把消息放到队列里面去
return queue.enqueueMessage(msg, uptimeMillis);
}
既然Looper中的loop()调用了msg.target.dispatchMessage,我们就看看Handler的dispatchMessage是如何进行处理这个msg的。
Handler.java:
public void dispatchMessage(Message msg) {
//这里先判断callback是否为空
// callback就是我们使用handler.post(Runnable r)的入参runnable
if (msg.callback != null) {
handleCallback(msg);
} else {
//如果hanlder的入参callback不为空,优先处理
if (mCallback != null) {
//如果回调返回true.则拦截了handler.handleMessage的方法
if (mCallback.handleMessage(msg)) {
return;
}
}
//这就是为什么我们使用hanlder的时候,需要重写handleMessage的方法
handleMessage(msg);
}
}
在dispatchMessage函数中,意思就是分发这个消息,在代码中先判断msg.callback是否为空,msg.callback是什么?其实就是handler.post中的runnable对象,通俗的来说就是handler如果有post操作的,就处理post的操作,我们在看看handlerCallback这个函数。
Handler.java:
private static void handleCallback(Message message) {
message.callback.run();
}
很简单,就一行代码,我们看到了熟悉的run方法,这个不就是我们使用post的时候传进去的Runnbale对象的run方法吗?;;
/**
* 模拟开始
*/
private void doSth() {
//开启个线程,处理复杂的业务业务
new Thread(new Runnable() {
@Override
public void run() {
//模拟很复杂的业务,需要1000ms进行操作的业务
......
handler.post(new Runnable() {
@Override
public void run() {
//在这里可以更新ui
mTv.setText("在这个点我更新了:" + System.currentTimeMillis());
}
});
}
}).start();
}
我们回到handler.dispatchMessage(Message)中,如果不是通过post那么callback就为空,我们看到了一个mCallback变量,我们看看这个Callback的定义:
public interface Callback {
public boolean handleMessage(Message msg);
}
public Handler(Callback callback) {
this(callback, false);
}
我们可以通过实现这个接口,并作为一个参数传进去Handler来达到处理这个消息的效果。
Handler.java:
public void dispatchMessage(Message msg) {
//这里先判断callback是否为空
// callback就是我们使用handler.post(Runnable r)的入参runnable
if (msg.callback != null) {
handleCallback(msg);
} else {
//如果hanlder的入参callback不为空,优先处理
if (mCallback != null) {
//如果回调返回true.则拦截了handler.handleMessage的方法
if (mCallback.handleMessage(msg)) {
return;
}
}
//这就是为什么我们使用hanlder的时候,需要重写handleMessage的方法
handleMessage(msg);
}
}
最后一行代码中,我们看到了熟悉的handleMessage,这不就是我们经常handler.handlerMessage的方法吗?
但注意之前我们所看到的,如果我们mCallback.handlerMessage(msg)返回为true的话,这样就不交给handler.handleMessage处理了。
我们继续看回来我们的Looper.loop()
Looper.java:
/**
* 调用此函数用于启动消息队列循环起来,作用相当于工厂流水线中的传送带的开关,
* 只有把开关打开,传送带才跑起来
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static void loop() {
.....
.....
//循环通过消息队列来获取消息
for (; ; ) {
......
//最后回收这个message
msg.recycleUnchecked();
}
}
在无限循环每个消息的时候,除了调用handler.dispatchMessage,最后还会调用msg.recycleUnchecked()进行回收这个消息
总结:
1.为什么在主线程中创建Handler不需要我们调用Looper.prepare().因为在程序的入口中系统会调用Looper.prepareMainLooper()来创建,并且让其主线程的Looper启动起来。如果我们在子线程创建handler,需要手动创建looper并且启动。
2.每一个线程只能存在一个Looper, Looper有一个全局变量sThreadLocal用来保存每一个线程的looper,通过get、set进行存取looper。
3.Handler可以通过通过post或者sendMessage进行发送消息,因为其最终会调用sendMessageDelayed,我们可以通过runnable方式或者重写handleMessage进行消息的处理,当然如果通过handler.sendMessage(msg)的方式的话,我们可以实现Callback接口达到消息的处理。
4.为什么不能在子线程更新UI?其实更准确的来说应该是UI只能在创建UI的线程中进行更新,也就是主线程,如果子线程创建UI,其可以在子线程进行更新。