每一个Android应用都是由事件驱动的,每个事件都会转化为一个系统消息,即Message。应用在运行过程中会源源不断的产生、处理、销毁Message。负责存储消息的是每个进程默认的消息队列MessageQueue,这个消息队列维护了一个待处理的消息列表,由一个消息循环Loop不断的将消息取出交给处理人Handler进行处理
关键类
Message: 应用驱动事件
MessageQueue:Message存储数据结构 维护一个待处理的消息列表,遵循FIFO原则
Looper:负责MessageQueue与Handler之间的通信,不断的从MessageQueue中取出Message发送的Handler处理
Handler:将Message发送到MessageQueue的消息队列中,接收Looper传递的Message进行分发处理
Handler常用构造
//无参构造 默认取当前线程Looper
public Handler() {
this(null, false);
}
//指定Looper
public Handler(Looper looper) {
this(looper, null, false);
}
示例
Handler handler;
private void mainHandler() {
handler = new Handler(); //1
new Thread(new Runnable() {
@Override
public void run() {
handler.sendEmptyMessage(0);
}
}).start();
}
private void childHandler() {
new Thread(new Runnable() {
@Override
public void run() {
handler = new Handler(); //2
// handler = new Handler(getMainLooper()); //3
handler.sendEmptyMessage(0);
}
}).start();
}
private void childHandler2() {
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
handler = new Handler(); //4
handler.sendEmptyMessage(0);
Looper.loop();
}
}).start();
}
在上述代码中1 3 4对于handler的初始化皆可用, 2中会直接报错,原因在于handler在初始化时会校验Looper 是否为空
public Handler() {
this(null, false);
}
public Handler(Callback callback, boolean async) {
......
//对mLooper 进行赋值
mLooper = Looper.myLooper();
//mLooper 判空处理
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
进入Looper.myLooper()方法看一下
//Looper存储的数据结构
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
public static @Nullable Looper myLooper() {
//获取Looper
return sThreadLocal.get();
}
ThreadLocal是一个线程的内部存储类常用方法为set存入 get获取
我们去搜索一下set方法在哪里将Looper对象 set存入
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
//校验Looper 每个线程只能绑定一个Looper
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
//每次set存入皆是new一个新的Looper对象
sThreadLocal.set(new Looper(quitAllowed));
}
//Looper的构造
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
通过查看Looper的构造方法 发现其只在prepare方法中进行了对象的创建,在Handler初始化时并没有实例化Looper,因此在子线程中创建hanldler需要指定Looper或者先调用Looper 的prepare方法进行looper实例化
而在主线程中则不需要 原因如下
public static void main(String[] args) {
......
Looper.prepareMainLooper();
......
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
}
public static void prepareMainLooper() {
//调用prepare方法实例化
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
//将当前线程的Looper赋值给sMainLooper
sMainLooper = myLooper();
}
}
在应用创建时已经调用了prepareMainLooper方法进行了Looper的实例化
API
handler.post()
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
在post方法中通过调用getPostMessage方法将传入的Runnable参数包装到一个Message对象中,然后在传给sendMessageDelayed
函数。
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
//获取当前handler所在的消息队列
MessageQueue queue = mQueue;
//判断队列是否为空
if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
//消息队列为空 直接返回
return false;
}
return enqueueMessage(queue, msg, uptimeMillis);
}
sendMessageDelayed函数再调用了sendMessageAtTime函数,在sendMessageAtTime函数中完成了对队列的获取与判空,并将封装好的message对象加入到改handler所在的消息队列在。由于handler在创建时就已经关联了Looper
//无参构造最终调用
public Handler(Callback callback, boolean async) {
......
//获取Looper并赋值给即将创建的Handler 与持有该Looper的线程进行绑定
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
//带有Looper 的有参构造最终调用
public Handler(Looper looper, Callback callback, boolean async) {
//将传入的Looper赋值给即将创建的Handler 与持有该Looper的线程进行绑定
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
因此,在sendMessageAtTime函数中handler实现了消息的线程切换,无论在哪个线程中调用handler发送消息,最终执行到sendMessageAtTime函数时都会讲封装好的message对象加入到改handler在创建时所持有的线程的Looper的消息队列中进行循环处理
同理在 handler.postDelayed() handler.sendMessage() handler.sendEmptyMessage()等其他负责进行消息传递的api中最终也是调用到了sendMessageAtTime函数进行处理
public final boolean postDelayed(Runnable r, Object token, long delayMillis)
{
return sendMessageDelayed(getPostMessage(r, token), delayMillis);
}
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public final boolean sendEmptyMessage(int what)
{
return sendEmptyMessageDelayed(what, 0);
}
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageDelayed(msg, delayMillis);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
上面就是handler进行线程切换的实现了,下面我们看一下Looper是如何将Message从messageQueue中循环取出交由Handler进行处理的
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;
......
for (;;) {
//获取消息
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
......
try {
//处理消息
msg.target.dispatchMessage(msg);
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
......
//消息回收
msg.recycleUnchecked();
}
}
我们追入Message 中发现target类型为Handler,最终消息处理会调用到Handler的dispatchMessage函数
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
dispatchMessage函数依然只是负责分发的函数。如果msg中Runnable 类型的mCallback参数不为空,则执行handleCallback函数,最终调用到mCallback的run函数
private static void handleCallback(Message message) {
message.callback.run();
}
否则再进行 Callback 类型的mCallback 变量判空处理。mCallback 的赋值在handler的构造函数中
public Handler(Callback callback) {
this(callback, false);
}
一般不会用到,因此我们可以默认mCallback 为空执行handleMessage函数进行消息处理
关于Message.obtain
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
关于该函数我要说的是使用了享元模式,避免了Message对象的大量创建,大家有兴趣的可以去查阅一下源码。知识量有点大,涉及到Message的数据结构、创建、回收,此处就不说了
总结
handler在创建时会持有一个自己的Looper(通过自己传入或Looper.preper创建)该Looper属于当前线程或指定线程,Looper中有一个消息队列,handler无论在哪个线程发送消息时都会将封装好的Message对象传入该消息队列,实现了消息的线程切换,然后通过Looper.loop 进行不断地消息循环取出处理