简介
Android应用程序通过消息驱动,在线程间的通信中,通过Handler、Looper、MessageQueue来实现消息的传递和处理。
在使用时,一般我们会用Handler handler = new Handler();
在当前线程(一般是UI线程)创建一个Handler对象;
然后,通过在其他线程里使用handler.sendMessage(message)
来发送消息给当前线程;
通过当前线程的handler里面的handleMessage
来处理来自其他线程的消息
以上是最简单的消息机制的运用,然而,其中到底发生了什么呢?接下来我们简单解析下源码到底做了什么
Handler、Looper、MessageQueue的创建过程
1、创建Handler,持有Looper和MessageQueue的实例
public Handler(Callback callback, boolean async) {
/*****/
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;
}
在使用new Handler()时
,会先拿到当前线程的Looper对象,如果拿不到会报异常导致handler创建失败。
一般我们在UI线程中,是不需要手动去创建Looper对象的,因为系统会在Activity创建的时候,通过ActivityThread的main方法里,调用Looper.prepareMainLooper();
来创建与UI线程绑定的Looper
public static void main(String[] args) {
//省略
//通过prepareMainLooper创建Looper,并绑定到当前UI线程
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"));
}