我们都知道,系统是不允许在子线程中访问UI的,但如果在主线程中进行耗时操作,又会极大地妨碍用户体验。
所以,我们可以在子线程中进行耗时操作,操作完毕后通知主线程更新UI。
为了方便在线程之间进行通信,官方提供了一种很好的解决方法——Handler。有效地解决了在子线程中无法访问UI的矛盾。
使用Handler,通常需要继承Handler类,并重写handleMessage()方法。
举一个简单的用法例子:
// 在主线程中
MyHandler mHandler = new MyHandler();
private void getDataFromNet() {
new Thread(new Runnable() {
@Override
public void run() {
//耗时操作,完成之后发送消息给Handler,完成UI更新;
mHandler.sendEmptyMessage(0);
// 如果想发送带参消息,则用sendMessage()方法
}
}).start();
}
class MyHandler extends Handler{
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
// 这个方法需要自己写内容
switch (msg.what) {
case 0:
//完成主界面更新,拿到数据
imageView.setImageResource(R.mipmap.ic_launcher);
break;
default:
break;
}
}
}
在以上的例子中,我们在主线程创建了一个MyHandler类型的对象mHandler,在子线程完成耗时操作(如网络请求获取图片)之后,用sendEmptyMessage()/sendMessage()方法发送消息,随后在主线程中会调用mhandler的handleMessage()方法来处理消息(如显示图片)。
怎么样,是不是很简单?
接下来我们就来看看它内部构造。
相关角色
- Handler :负责向消息队列发送消息,以及处理从消息队列中分发出来的消息。
- Looper:负责无限循环检查消息队列中的消息。如果有消息则把它取出交给handler处理,同时把该消息从消息队列中移除。
- MessageQueue(消息队列):负责存储消息。以单链表的结构对外提供插入和删除的工作。
角色关系
在Handler内部有mLooper和mQueue两个成员变量,其中mQueue是mLooper的成员变量。
由此我们可以知道,如果在一个线程中没有Looper,那么handler便无法向消息队列中发送消息,更不用说从中取出消息并处理了。
但是从开头的例子中我们也可以看到,在主线程中,并没有一个Looper被显式地创建,那么为什么在可以直接创建Handler并被使用呢?
这是因为,应用在启动的时候先执行了ActivityThreadMain,用Looper.prepareMainLooper()创建了一个在主线程进行循环的looper,并用Looper.loop()开启消息队列,从而handler可以正常使用。
public static void main(string[] args){ //在这里面创建了一个MainLooper,创建的过程如下:
//初始化
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if(sMainThreadHandler == null){
sMainThreadHandler = thread.getHandler();
}
AsyncTask.init();
//动起来
Looper.loop();
}
以上这段代码还可以说明一个问题,并不是只有主线程中才能创建Handler,在子线程中也同样可以。
只要在子线程调用Looper.prepare(),和Looper.loop(),无限循环读取消息队列的looper,就可以创建Handler了。
可是,Looper和Handler是怎么关联到一起的呢?当遇到多个继承了Handler的类时,Looper取出的消息又是怎样交给正确的Handler的呢?这就需要看一下他们的调用关系了。
调用关系
Handler在创建的时候,我们可以看到,它有两个构造方法。第一个是传入一个looper变量,为其内部的mLooper赋值。
// Handler类
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
第二个比较常用,不往里面传looper,而是自动获取该线程的looper为其赋值。
// Handler类
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;
}
值得注意的是获得该线程的looper的语句:mLooper = Looper.myLooper();
它是怎么获取的呢?我们跟进去看一下:
// Looper类
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
这里出现了一个很奇怪的变量——sThreadLocal。这个变量是ThreadLocal类型的,我们需要简单了解一下ThreadLocal类,才能对整个过程有一个更加清楚的认识。
ThreadLocal类解析
ThreadLocal是一个线程内部的数据存储类(只能存一个值),通过它可以在指定的线程中存储数据,数据存储以后,只有在指定线程中可以获取到存储的数据,对去其他线程来说则无法获取到该数据。
一般来说,当某些数据是以线程为作用域并且不同线程具有不同的数据副本的时候,就可以考虑采用ThreadLocal。
经过前面的讲解,我们可以想到Looper的作用域是线程,并且不同线程具有不同的Looper,这个时候通过ThreadLocal就可以轻松实现Looper在线程中的存取。
可能说到这里大家还是不太明白这个类的神奇之处,我举一个直观的例子,大家一看就知道啦。
package com.example.cgj.loopertest;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
private ThreadLocal<Boolean> threadLocal; //存布尔类型的值
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
threadLocal = new ThreadLocal<>();
threadLocal.set(true); // 在主线程把存的值设为true
Log.d("threadLocal的值 , 当前线程 :",threadLocal.get().toString()+" "+Thread.currentThread().toString());
TestAsyncTask testAsyncTask = new TestAsyncTask();
testAsyncTask.execute();
}
class TestAsyncTask extends AsyncTask<Void,Integer,Void>{
@Override
protected Void doInBackground(Void... voids) {
threadLocal.set(false); // 在子线程把存的值设为false
Log.d("threadLocal的值 , 当前线程 :",threadLocal.get().toString()+" "+Thread.currentThread().toString());
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
// 回到主线程,打印子线程运行过后的值
Log.d("threadLocal的值 , 当前线程 :",threadLocal.get().toString()+" "+Thread.currentThread().toString());
}
}
}
请大家先不要看程序运行结果,先推测一下打印的三个值分别会是什么。
推测完后我们再往下来验证结果是否正确:
09-05 22:01:35.704 21005-21005/com.example.cgj.loopertest D/threadLocal的值 , 当前线程 :: true Thread[main,5,main]
09-05 22:01:35.704 21005-21039/com.example.cgj.loopertest D/threadLocal的值 , 当前线程 :: false Thread[AsyncTask #1,5,main]
09-05 22:01:35.724 21005-21005/com.example.cgj.loopertest D/threadLocal的值 , 当前线程 :: true Thread[main,5,main]
是不是发生了一件奇怪的事情?在子线程中明明把threadLocal中存的值设为了false,之后在主线程打印的值还是true!怎么会是这样,难道是没有设置成功?
事实上,在一个线程对threadLocal进行的操作,完全不会对另一个线程造成任何影响。从threadLocal被创建的线程开始分支的每个子线程,都单独拥有threadLocal所存储的值,当这个值在线程内进行改变时,都不会影响其他线程的值。
所以,使用sThreadLocal.get()获取该线程的Looper是一个很方便并且正确的选择。
获取到该线程的Looper之后,再为Handler的mLooper变量赋值,就完成了该线程里Handler和Looper的关联。
接下来我们再来看,Handler是怎样向消息队列发送消息的。
Handler发送消息的流程
为方便阅读,我将部分内容进行了简化。
最后来到了mQueue.enqueueMessage()这个方法。说明它就是最终把消息加入到消息队列的关键方法。我们来看一下它的源码:
// MessageQueue类
boolean enqueueMessage(Message msg, long when) {
// 判断是否有接收此消息的Handler(用target值来标记),若没有则抛出异常
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
// 判断该消息是否已经加入到消息队列,若已加入则抛出异常
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
synchronized (this) {
// 判断该消息队列是否已经退出。如果退出了,则无法发送消息,会抛出异常,并回收该消息。
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w(TAG, e.getMessage(), e);
msg.recycle();
return false;
}
msg.markInUse(); // 把该消息标记为已加入消息队列
msg.when = when; // 设置该消息的传输时间
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
// 如果该消息队列目前为空,则将该message作为头节点
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// Inserted within the middle of the queue. Usually we don't have to wake
// up the event queue unless there is a barrier at the head of the queue
// and the message is the earliest asynchronous message in the queue.
needWake = mBlocked && p.target == null && msg.isAsynchronous();
// 将该消息插入到消息队列(实现形式为单链表)
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
// 中文注释为作者注,英文为源码注、
稍微有点长,但一点点看完之后是不是明白了许多呢?
其实,除了send系列方法,还可以用post系列方法来发送消息(代码如下)。但post系列方法最终也是通过send系列方法来实现的,所以这里只讲述了sendMessage()方法的过程。
// Handler类
public final boolean post(Runnable r) { returnsendMessageDelayed(getPostMessage(r), 0); }
当Handler向消息队列插入一条消息后,Looper便能够在消息队列中读取到该消息,并将它进行分发。这里涉及到两点问题:读取消息、分发消息。
Looper的工作机制
Looper是通过loop()方法来使消息循环系统起作用的,这个方法非常重要。我们简单地看一下它的内容:
// Looper类
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;
// 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.isTagEnabled(traceTag)) {
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();
}
}
从以上代码中可以看到,loop()方法里面有一个死循环,只有queue.next()返回null时才能退出循环。当调用Looper的quit()/quitSafely()方法时,Looper会调用MessageQueue的quit()方法来退出自己的消息队列,当消息队列被标记为退出后,它的next()方法就会返回null。
换句话说,就是如果looper不退出,它的loop()方法会一直循环下去。
Looper会调用MessageQueue的next方法来获取新的消息,但next()是一个阻塞的方法,如果没有新消息,next()方法会一直阻塞在那里,也导致loop()方法一直阻塞在那里。如果next()返回了新消息,Looper就会用msg.target.dispatchMessage(msg)方法分发消息。msg.target是一个Handler对象,用来识别这个消息应该交给哪个Handler处理。
当一个消息被Looper读取后,该消息会从消息队列中销毁。
这个过程可以用一个流程图来简单地概括:
有一点不能忘记,如果在子线程中创建了Looper,记得在使用完毕后一定要调用Looper的quit的方法退出Looper。
Looper提供了两种退出方法:
- quit() : 直接退出looper,但消息队列中可能还有消息没有处理。
- quitSafely() : 不直接退出looper,等消息队列中所有的消息都处理完毕后才安全地退出。
如果在该线程的任务都已经结束后没有调用quit方法来终止消息循环,这个子线程会一直处在运行状态,等待新消息的到来。而如果退出了Looper,这个子线程的代码才算全部执行完,才会终止自己。
所以,出于资源的考虑,一定要在不需要的时候终止Looper。
到现在,这个过程已经渐具雏形了。但还少了最后一个步骤分析:分发处理消息的过程。
Handler处理消息的过程
Handler的dispatchMessage()方法的源码如下:
// Handler类
public void dispatchMessage(Message msg) {
if (msg.callback != null) { // 在Message类中有成员变量:Runnable callback;
handleCallback(msg);
} else {
if (mCallback != null) { // 在Handler类中有成员变量:final Callback mCallback;
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
private static void handleCallback(Message message) {
message.callback.run();
}
public interface Callback {
public boolean handleMessage(Message msg);
}
首先,检查Message的callback是否为null。如果不是,则调用handleCallback()方法来处理消息。我们通过跟踪该变量可以知道,callback是一个Runnable对象,实际上就是在用Handler的post方法时所传递的Runnable参数。直接调用callback.run()即可处理。
如果是null,再检查mCallback是否为null。不为null就调用mCallback的handMessage()方法来处理消息。
如果mCallback也是null,就直接用handleMessage()方法来处理消息。
这里出现了一个接口:Callback。通过它可以直接用如下方式创建Handler对象:
Handler handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
return false;
}
});
看到这个用法,结合源码的注释:“Callback interface you can use when instantiating a Handler to avoid having to implement your own subclass of Handler”,可以用Callback接口来创建一个Handler实例,而不用派生Handler的子类。
在文章开头举例子的时候,我们说常见的使用Handler的方法,是继承Handler类,并重写handleMessage()方法来处理具体的消息。
当我们不想派生子类的时候,就可以通过Callback实现。
Handler处理消息的过程也可以归纳为一个流程图:
好了,以上就是安卓消息机制的全部内容了。经过之前的分析我们能够看出,其实Handler可以实现任何需要在两个线程间进行通信的功能,并不是只用来在子线程中通知主线程更新UI的,只是开发者比较常用它来更新UI而已。
而这种消息的传递也不只能用Handler实现,只要一个标志性变量在线程A中的改变能被线程B检测到,就能够起到通知线程B的作用,进而使线程B作出响应和改变。读者们如果有兴趣甚至也可以仿照这种机制自己动手写一个“Handler”出来,只要具备了一个可以发送和处理消息的类,一个存储消息的类,和一个不停循环检查读取消息并分发的类,让它们相互间协调配合默契,就可以完成啦。
最后,作者尚在学习,欢迎指摘~