一. 概述
在Android开发中, 我们经常需要从网络或者本地资源中拉取数据,然后在界面上显示出来。而为了保证app使用的流畅性,我们不要再主线程做耗时的操作,以免阻塞主线程,导致应用程序无响应。
具体来说就是点击之后Activity中无响应超过5秒或者BroadcastReciver的OnRecive方法处理超过10秒就会抛出ANR。而且在Android4.0之后Google强制要求不能再主线程中访问网络。
所以当我们执行耗时的操作的时候都会在子线程中执行,但是Android中要求一般情况下只有在主线程中才能跟新UI界面,以免出现多个线程同时跟新界面导致程序异常发生。(不是一定只能在主线程才能跟新ui界面,但是绝大多数情况下是这样的。)
所以当我们在子线程中异步获取到数据之后,就需要给主线程通知,我这边已经获取到数据了,你把界面更新一下吧。这就涉及到了线程的切换,在Android中为我们提供了Handler来解决这个问题。 那么Handler是如何解决这个问题的呢?
二. 具体
1.Handler分析
首先, 我们来看一段简单的Handler使用代码,我们一步一步来分析这段代码
public class TestActivity extends AppCompatActivity {
private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new Thread(new Runnable() {
@Override
public void run() {
Message msg = Message.obtain();
mHandler.sendMessage(msg);
}
}).start();
}
}
1. 首先,我们先来看看如何创建一个Handler对象
可以看到,我们是使用关键字new来通过Handler的构造函数来创建了Handler对象,并且重写了handleMessage()方法,那么我们去Handler 的源码中看看是Handler的构造函数
public Handler() {
this(null, false);
}
public Handler(boolean async) {
this(null, async);
public Handler(Callback callback) {
this(callback, false);
}
public Handler(Looper looper) {
this(looper, null, false);
}
public Handler(Looper looper, Callback callback) {
this(looper, callback, false);
}
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
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;
}
虽然说Handler有七个构造函数,但是我们可以看到不管你通过哪个方法来创建Handler,最后都会通过this关键字调用来使用下面两个构造函数中的的一个来创建Handler
public Handler(Looper looper, Callback callback, boolean async){}
public Handler(Callback callback, boolean async) {}
先来看第一个方法,
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
其中我们在构造的时候传入了一个Looper对象,looper是什么呢?简单来说它是一个消息的轮询器,在它的内部有一个无限for循环不断地处理消息从别的线程发来的消息,而且每个不同线程中最多只能有一个Looper对象。
然后我们在Handler中保存了传入的这个looper对象的引用。如果没有传入looper对象,Handler会默认使用当前线程中的looper对象,如果当前线程没有looper对象,那么就会直接抛出运行时异常。
第二个参数看名字就知道是一个回调接口。我们具体的看看这个回调接口
public interface Callback {
public boolean handleMessage(Message msg);
}
这是定义在Handler内部的一个回调接口, 可以看到它只有一个方法就是handleMessage(Message msg);
这个接口是Google为了方便我们创建Handler而提供的,我们可以在这个方法中处理具体的消息,和我们创建Handler对象时重写Handler中的handleMessage方法效果是一样的,只不过这个方法会返回一个boolean类型的数据,这个数据有什么用呢?后面会讲到。
如果没有传入这个接口的子类实例对象,那么,默认mCallback就为null;
第三个参数是一个标记位,用来设置你发送的消息是否为异步的消息,当你传入true时,你通过这个Handler发送消息时,会调用msg.setAsynchronous(true)将消息设置为异步消息,默认为false。如下代码所示。
if (mAsynchronous) {
msg.setAsynchronous(true);
}
而第二个构造函数
public Handler(Callback callback, boolean async) {}
比起第一个构造函数来说,少了一个参数就是looper。 那么真的是创建Handler对象时不需要looper对象么? 当然不是的,我们开看看它代码块中的这一段
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
它调用了Looper中的一个静态方法,获得的一个looper对象。这个looper对象就是当前代码所在线程的looper对象。
比如我们在主线程创建Handler对象,这个Looper对象就是主线程的Looper对象。而主线程的Looper对象是在Activity创建时系统自动帮我们创建好了的。如果我们在子线程创建Handler对象,如果我们没有自己来创建Looper对象的话, 在子线程是没有的looper对象的,那么mLooper就是null,会直接抛出一个运行时异常。
具体如何获得当前线程的looper对象,如何在子线程创建looper对象我会在后面的Looper中具体进行讲解。
而其他的参数意义和第一个是一样的。
那么到这里,我们的Handler对象就创建完成了。可以看到,创建Handler时,Handler内部肯定会有一个looper类型的成员变量。
2. 接下来我们看看如何在子线程发送消息。
通过查看源码我们可以看到Handler下有非常多非常丰富的发送消息的方法,总的来说有这么三大系列:
Post系列下有:
post, postAtFrontOfQueue, postAtTime, postDelayed。
sendMessage系列下有:
sendMessage,sendMessageAtFrontOfQueue,sendMessageAtTime,sendMessageDelayed。
sendEmptyMessage系列下有:
sendEmptyMessage,sendEmptyMessageAtTime,sendEmptyMessageDelayed。
虽然看似有这么多的方法,但是最主要的也就这 三个方法,分别是
1. 通过post来发送一个Runable对象。
2. 通过sendMessage来发送一个message对象。
3. 通过sendEmptyMessage来发送一个没有内容的message对象。
接下来我们具体查看post方法,
post方法先调getPostMessage方法将Runable对象封装成一个message对象
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
然后调用sendMessageDelayed方法将封装的message对象发送出去。
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
post系列的其他方法都是同样的流程,先将Runable对象封装,然后调用了sendMessage系列中的方法。
我们来看看sendEmptyMessage系列方法
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);
}
可以看到实际上就是在调用Message.obtain()获得一个新的消息,然后调用sendMessageDelayed将它发送出去。
post系列和sendEmptyMessage系列中其他的方法,最后都是经过一串调用后调用到了sendMessage中对应的方法。那么看来,sendMessage 中的方法是关键喽。
那么接下来我们来看看关键执行的sendMessage系列中的方法。
sendMessage系列中虽然有很多方法, 但是最后都是调用了同一个方法enqueueMessage();
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
其中第一个参数:
queue是一个MessageQueue 类型的对象,它是在创建Handler对象时通过Looper对象获得的
mQueue = mLooper.mQueue;
MessageQueue 是Looper中的一个内部类,因为我们的looper在一个线程中只有一个,所以MessageQueue 也只有一个。MessageQueue 内部维持着一个单链表的数据结构,我们从别的线程中发出的message最终都会放到这个链表中维护起来。
第二个参数 msg就是我们传入的message或者Runable封装的message。
第三个参数uptimeMillis 是long类型的,它是用来表示消息执行的具体时间的,在message放入消息队列时都会按着这个时间来将消息插入到合适的位置。
这个方法最终调用了queue.enqueueMessage(msg, uptimeMillis)方法,将message根据uptimeMillis参数插入到了queue的链表结构中。
在此时我们就完成了消息在线程中的切换,我们在别的线程中创建的message,MessageQueue 对象中的链表中了,此时已经放入了创建Handler 时所使用的Looper对象中的MessageQueue 对象中的链表中了(是有点绕口… (¬_¬))。 那接下来我们就来看看Looper是什么。
2.Looper分析
前面我们说过,在一个线程中最多只能有一个Looper对象存在,那么,Android是如何保证一个线程中只有一个Looper的呢?
先来看看Looper的构造函数
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
可以看到,当Looper被实例化之后,它会直接实例化一个MessageQueue对象作为成员变量。然而我们可以看到,Looper的构造函数被private 修饰,意味着我们在其他类中不能使用new关键字来实例化looper对象
那么我们如何创建Looper的实例对象呢?
Android给我们提供了另外一个方法来创建Looper对象,那就是Looper.prepare()方法,我们来看看它的代码
public static void prepare() {
prepare(true);
}
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));
}
prepare方法调用了参数不同的一个重载方法prepare(boolean quitAllowed),在这里面我们看到了sThreadLocal.set(new Looper(quitAllowed)); 当我们调用了Looper.prepare后系统帮我们new了一个Looper对象。
那么我们如何保证一个线程只有一个Looper对象呢?
在prepare方法中有一个sThreadLocal,它是ThreadLocal类的一个实例。
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
可以看到ThreadLocal是一个静态对象,只要Looper的class一被加载进内存,就会先在内存中将ThreadLocal对象创建出来。
prepare方法中我们可以看到Looper的创建和ThreadLocal的get和set方法都有关系,
那么ThreadLocal是什么呢?
ThreadLocal有一个内部类ThreadLocal.ThreadLocalMap, 这是一个map集合。而每一个线程中都维护着这样一个Map集合。在Thread中有这么一行代码,可以看到,ThreadLocal.ThreadLocalMap是Thread中的一个成员变量
ThreadLocal.ThreadLocalMap threadLocals = null;
我们来分别看看ThreadLocal中的get,set两个方法
首先是ThreadLocal中的set方法
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
可以看到,set方法很简单,就是获取当前线程的ThreadLocalMap 对象,然后将ThreadLocal对象作为key,传入的泛型对象作为value,存入map中,如果当前线程还没有实例化创建ThreadLocalMap对象,那么通过调用ThreadLocal的createMap方法创建一个map对象,并且把键值对存入进去,其中t就是当前线程
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
接下来看看ThreadLocal中的get方法
public T get() {
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();
}
这个方法也很简单,首先获取当前的线程,然后获取当前线程的中的ThreadLocalMap对象。接着,以调用get方法的ThreadLocal对象作为key,获取到它对应的value值,返回即可。
我们在回过头来看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));
}
这下就很明了了,首先获取当前线程的ThreadLocalMap这个map集合中以sThreadLocal对象作为key保存的Looper对象,如果获取到了,说明当前线程已经 存在一个Looper对象了,那么就抛出运行时异常,”Only one Looper may be created per thread” 。
否则就通过new来创建一个looper对象,然后通过sThreadLocal的set方法以sThreadLocal为key将looper保存到当前线程的ThreadLocalMap这个map集合中。
而每个不同的线程都有一个独立的ThreadLocalMap对象,那么在不同的线程调用prepare方法就保存了不同的looper对象,而且也只会有一个looper对象。 因为我们在其他类通过new来创建looper, 通过prepare来创建,会判断只有当前线程中没有looper时,才会初始化一个looper对象。
而looper初始化时,构造函数中也会初始化一个MessageQueue对象。同样的,一个线程中也只有一个MessageQueue对象。
接下来我们看看Looper中几个重要的方法
1. 首先是Looper.prepareMainLooper()方法
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
Activity会在初始化创建的时候通过系统自动来调用这个方法来创建一个主线程的looper。我们不要调用这个方法,会导致程序直接抛出异常。
它的流程很简单,调用了prepare方法来创建一个looper对象,然后让sMainLooper这个成员变量指向他。 所以我们才能在主线程直接创建Handler对象,而不用传入looper 对象。
2. getMainLooper()方法和myLooper()方法
public static Looper getMainLooper() {
synchronized (Looper.class) {
return sMainLooper;
}
}
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
一个是返回主线程的looper,一个是返回方法调用时所在线程的looper。
3. 接下来是Looper中最重要的方法loop()
我们前面说过,在Looper中有一个无限死循环,不断地从MessageQueue中取出消息然后处理,就是在这个方法中执行的。
一般来说Activity被创建后,系统会调用Looper.prepareMainLooper()方法来创建主线程looper, 然后会调用loop()方法来开启循环。我们来看看这个方法
public static void loop() {
final Looper me = myLooper();
//Lopper对象为null,抛出异常
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
//如果Message为空,就退出循环。
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.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);
}
msg.recycleUnchecked();
}
}
大致来说
1. 首先判断当前线程中looper不为null,否则就抛出异常。然后获取了looper中的MessageQueue对象queue。
2. 接下来开启了一个无限for循环,然后调用了MessageQueue中的next方法,从queue中获取一个message对象。
3. 当message对象为null时,才能退出循环。message为null表示MessageQueue队列已经退出循环了
4. 调用了获得的message中的target的dispatchMessage方法。
其中的关键就是第二步和第三步
MessageQueue中的next方法也是一个无限循环,它会从MessageQueue的链表中不断地获取message然后返回给调用者,如果没有获取到message,那么它就会阻塞,知道获取到message,才会把message返回,并且从链表中移除这个message。只有当调用了MessageQueue的quit方法或者quitSalefy方法才会使得next方法返回null值,才会导致Loop退出循环。
final Message next() {
int pendingIdleHandlerCount = -1; // -1 only during first iteration
//要等待的时间
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
//查看当前消息队列中有没有消息,这是一个native方法
nativePollOnce(mPtr, nextPollTimeoutMillis);
synchronized (this) {
final long now = SystemClock.uptimeMillis();
final Message msg = mMessages;
if (msg != null) {
final long when = msg.when;
if (now >= when) {
mBlocked = false;
mMessages = msg.next;
msg.next = null;
if (false) Log.v("MessageQueue", "Returning message: " + msg);
msg.markInUse();
return msg;
} else {
nextPollTimeoutMillis = (int) Math.min(when - now, Integer.MAX_VALUE);
}
} else {
nextPollTimeoutMillis = -1;
}
if (pendingIdleHandlerCount < 0) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount == 0) {
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf("MessageQueue", "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
pendingIdleHandlerCount = 0;
nextPollTimeoutMillis = 0;
}
}
第二步获取到了MessageQueue中一个待处理的message,然后在第三步通过调用msg.target.dispatchMessage(msg)来处理了这个message。
而第三步中的target是什么呢? 实际上target是一个Handler对象,它指向的是我们发送这个message时使用的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);
}
}
首先,判断msg.callback不为null的话调用了handleCallback(msg)方法,消息处理结束**
如果msg.callback为null的话,就判断mCallback是否为null,如果不为null,执行mCallback.handleMessage(msg)并判断这个方法的返回值,返回值为true的话,消息处理结束,返回值为false再调用Handler对象中的handleMessage,消息处理结束。
如果msg.callback为null,则直接调用Handler对象中的handleMessage,然后消息处理结束。
这个callback和mCalback分别指的是什么呢?
还记得我们发送消息时调用的post系列方法么?我们将一个Runable对象封装到了message对象中,callback指的就是我们发送消息时post的runable对象。而handleCallback(msg)是这样的
private static void handleCallback(Message message) {
message.callback.run();
}
直接调用Runable的run方法执行runable中的代码即可。
而mCallback是我们创建Handler实例时传入的接口对象,还记得我们创建Handler可以接受一个Callback类型的参数么。
当我们创建对象时传入了Callback的实例对象,,在这里就会调用callback中的handleMessage方法中的代码,然后判断返回值, 如果为TRUE,则这条消息处理结束,直接返回,否则再调用Handler中的handleMessage方法,然后这条消息处理结束
至此,一条消息从创建到发送到执行完毕的流程结束,完成了线程间消息处理的切换。
三. 总结
总结来说一下, 虽然在Handler的消息机制中我们涉及到了不少的对象。但主要就是三个对象Handler,Looper,MessageQueue。
通过Handler来在任意线程将一个message加入到Handler被创建时所在线程的MessageQueue对象的内部链表中。
MessageQueue作为一个容器把传来的消息进行排序, 然后根据发送消息时传入的时间要求在next中返回message对象
Looper作为一个轮询器,不断地从MessageQueue中获取一个一个的message对象,然后交给Handler来进行处理。
通过Handler在其他线程发送消息, 通过Handler在它创建时使用的looper所在线程处理消息。
四. 一点扩展
看完整片文章,可以发现,我们不但可以在主线程中创建Handler来处理其他线程发来的消息。
当我们在某个子线程中需要避免耗时操作时,我们也可以做到了
例如:我们在子线程 A 中中来处理消息。
只需要在 A 线程中调用Looper.prepare()方法来创建一个looper对象,然后调用looper.loop()方法让这个looper循环起来, 我们就可以在 A 线程创建Handler对象,然后从别的线程通过这个Handler来发送消息给
A线程来进行处理了。
甚至Android已经提供好了这样的类,那就是HandlerThread;
HandlerThread
HandlerThread本质上就是一个Thread,它集成自Thread,只不过在它的Run方法中系统帮我们创建好了looper轮询器。
HandlerThread中的run方法。
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
这个Thread中存在着一个looper对象。 我们可以通过HandlerThread实例的getLooper()方法获取到HandlerThread中的looper对象。
我们还可以重写onLooperPrepared()这个方法,在looper开始轮询之前,做一些准备性的工作
这样我们就可以在别的方也能创建基于A线程中Looper的Handler对象了,通过这个Handler我们就能在别的线程中发送消息,然后在HandlerThread线程中处理消息了。
需要注意的一点就是,当我们这个线程使用完之后,记得要调用HandlerThread中的quit()方法,或者quitSafely()方法来停止循环。
才疏学浅,错漏之处欢迎多多批评指点。