我们都知道Android的主线程不能处理耗时的任务,否者会导致ANR的出现,但是界面的更新又必须在主线程中进行,这样我们就必须在子线程中处理耗时的任务,在主线程中进行UI更新。
Android的消息处理有三个核心类:
Looper,Handler和Message
MessageQueue(消息队列)封装到Looper里面了,我们不会直接与MessageQueue打交道。
1、Looper
Looper 在 Android 的消息机制中扮演着消息循环的角色,它会不停地从 MessageQueue 通过 next() 获取是否有新消息,如果有新消息就处理,否则就 MessageQueue 阻塞在那里。
Looper主要是prepare()、loop()这个两个方法
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
//sThreadLocal是否为null,否则抛出异常,Looper.prepare()方法只能被调用1次
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
//将一个Looper的实例放入了ThreadLocal
sThreadLocal.set(new Looper(quitAllowed));
private Looper(boolean quitAllowed) {
//构造方法中创建MessageQueue(消息队列)
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
接着看下loop()做了什么?
public static void loop() {
//获取sThreadLocal存储的Looper实例,me为null则抛出异常,也就是说looper方法在prepare方法之后调用
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
//拿到当前线程Looper的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 (;;) {
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
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
//msg.target是Handler类型对象
//把消息交给msg的target的dispatchMessage方法去处理
msg.target.dispatchMessage(msg);
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();
}
}
public static Looper myLooper() {
return sThreadLocal.get();
}
Looper用于封装了android线程中的消息循环,默认情况下一个线程是没有消息循环的,需要调用Looper.prepare()来给线程创建一个消息循环,调用Looper.loop()来使消息循环,从消息队列里取消息,处理消息。
Looper作用:
1、Looper使一个线程变成Looper线程
2、 每个线程只会有一个Looper实例,保证Looper实例也只有一个MessageQueue。
3、 Looper内部有一个消息队列,loop()方法调用后线程开始不断从MessageQueue中去取消息,交给消息的target属性的dispatchMessage去处理。
那么,我们如何往MessageQueue上添加消息呢?
那么该Handler登场了~
public Handler() {
this(null, false);
}
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());
}
}
//Looper.myLooper()获取了当前线程保存的Looper对象
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
//获取了Looper实例中保存的MessageQueue(消息队列),这样就保证了handler的实例与我们Looper实例中MessageQueue关联上了
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
有了handler之后,我们就可以使用 post(Runnable), postAtTime(Runnable, long), postDelayed(Runnable, long), sendEmptyMessage(int), sendMessage(Message), sendMessageAtTime(Message, long)和 sendMessageDelayed(Message, long)这些方法向MessageQueue上发送消息了。光看这些API你可能会觉得handler能发两种消息,一种是Runnable对象,一种是message对象,其实post发出的Runnable对象最后都被封装成message对象:
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
//最终调用了sendMessageAtTime方法发送消息
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
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) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
看完了消息的发送,再来看下handler如何处理消息。消息的处理的核心方法dispatchMessage(Message msg)
最后调用了handleMessage方法
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
public void handleMessage(Message msg) {
}
为什么是一个空方法呢
消息最终回调是由我们控制的,在创建handler的时候都是重写handleMessage方法,然后根据msg.what进行消息处理!