只需要解释一点:为什么handler可以用于子线程更新UI
(1)当UI线程创建的时候会执行ActivityThread的main方法:
Looper.prepareMainLooper()
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
//每个线程只允许有一个Looper,所以当该线程的Looper存在时,报异常
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
我们看看prepare()方法做了什么
private static void prepare(boolean quitAllowed) {
//sThreadLocal 是一个ThreadLocal类型的实例,这个类的作用简单说就是为每个线程提供某个变量的副本来保证线程安全,以后会详细说
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
以上两步做一个总结,UI线程在初始化的时候会实例化一个Looper对象和一个MessageQueue对象,注意:一个线程只有一个looper实例,只有一个MessageQueue实例.
(2)ActivityThread中的另外一个方法:loop()
//不需要每行都看
public static void loop() {
//myLooper()返回的就是当前线程的looper对象
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
//获取当前线程的MessageQueue对象
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 (;;) {
//这里可能发生阻塞,为什么会阻塞?因为queue有可能取不出消息,因此就会等待消息
Message msg = queue.next();
//当取出的消息为空,退出循环.什么时候为空,需要看next源码,到这里我们看看next()方法做了什么
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 {
//这里是关键点,取出消息来以后,把消息交给它的target对象去处理,target是谁,一会揭晓答案
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();
...
msg.recycleUnchecked();
}
}
我们看看MessageQueue的next()方法做了什么
//只需要看中文注释的地方
Message next() {
//这个mPtr决定了是否返回null,返回null的话则looper的loop()方法就会退出,也就是不会再处理消息
//used by native code 这个是这个字段的解释,也就是说这个字段由native方法控制
//当我们调用looper的quit()或者quitSafely()方法的时候,这个字段的值就会被赋值为0
//quit()指的是立即退出消息循环,不管MessageQueue里面还有没有待处理的消息
//quitSafely()是等MessageQueue里面的消息处理完成后再退出
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
//开启无限循环去取消息,不用深究
for (;;) {
...
}
(3)通过looper的loop()方法,我们知道最终处理消息的是msg的target对象,下面我们来看看这个target是什么
我们在使用handler的时候,会使用这个方法:
handler.sendMessage(msg);
我们看看这个方法做了什么:
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
接着看:
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) {
//这个消息队列,就是当前线程的唯一消息队列,就是在创建looper的时候创建的那个唯一的MessageQueue,handler在哪个线程创建,这个MessageQueue就是哪个线程的
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);
}
接着看:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
//这个就是关键点!target对象就是handler本身,也就是说这个msg是谁发出的,最终由谁的dispatchMessage()方法处理!!!
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
//这个方法就是把消息加入到MessageQueue的消息队列里面,本着先进先出的原则,先加入到队列的消息优先处理
return queue.enqueueMessage(msg, uptimeMillis);
}
(4)从上面看出方法的最终执行者是我们创建的handler的dispatchMessage()方法:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
//当使用handler.post(Runnable r)这个方法的时候会执行这个方法,这个方法说到底就是执行r中的run()方法
handleCallback(msg);
} else {
//看到handleMessage()方法可能会更加熟悉,因为我们在创建handler的时候会重写这个方法,也就是最终调用的是我们重写的方法
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
(5)handler不仅可以用来更新ui,我们还可以在子线程创建handler,然后在其他线程使用这个handl实例发送消息,在子线程处理相应的逻辑,注意我们需要手动Looper.prepare().
new Thread(){
@Override
public void run() {
Looper.prepare();
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
super.run();
}
}.start();