一、前言
大家对Handler一定不陌生,它主要用于多线程间的通信,常见的就是在UI线程中创建了Handler对象,在异步线程中做数据请求等耗时的操作,耗时操作后再通过Handler.sendMessage(message)等接口通知UI线程刷新界面等。
二、概念了解
说到Handler的内部实现,一定要知道MessageQueue和Looper两个概念。
- MessageQueue:字面理解就是消息队列,用来存放消息,Handler就是将message发送到该队列中。
- Looper:字面理解就是循环处理机,内部会循环去MessageQueue获取消息message,如果没有消息就锁住;有则通知Handler处理该消息,最终便会调用Handler.handleMessage(message)(如果通过Handler.post(runnable),则最终执行runnable里面的内容)。
三、源码分析
首先看看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;
}
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
后者会传入Looper对象,前者则用当前线程的Looper,如果没有(mLooper == null)则会抛出异常 "Can't create handler inside thread that has not called Looper.prepare()",是不是有的印象哈?曾经我也犯过该错误,也许这时有人会说,“我每次都是直接new Handler创建,都没有执行Looper.prepare(),从来都没遇到过该报错”,这是因为当前线程是主线程(即所谓的UI线程)。主线程就是 ActivityThread,和普通的java类一样,入口是一个main方法,见如下源码:
public static void main(String[] args) {
SamplingProfilerIntegration.start();
// CloseGuard defaults to true and can be quite spammy. We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
// Set the reporter for event logging in libcore
EventLogger.setReporter(new EventLoggingReporter());
Security.addProvider(new AndroidKeyStoreProvider());
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
AsyncTask.init();
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
根据源码,主线程启动就会调用了Looper.prepareMainLooper(),这时便创建了主线程的Looper。因此,当我们创建Handler对象又没传入特定Looper时,需要确保当前线程已创建了Looper,即已调用了Looper.prepare()。接下来,我们来看看Looper的相关方法及成员。
/** Initialize the current thread as a looper.
* This gives you a chance to create handlers that then reference
* this looper, before actually starting the loop. Be sure to call
* {@link #loop()} after calling this method, and end it by calling
* {@link #quit()}.
*/
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));
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
/**
* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
*/
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
// sThreadLocal.get() will return null unless you've called prepare().
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
/**
* Initialize the current thread as a looper, marking it as an
* application's main looper. The main looper for your application
* is created by the Android environment, so you should never need
* to call this function yourself. See also: {@link #prepare()}
*/
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
/**
* Returns the application's main looper, which lives in the main thread of the application.
*/
public static Looper getMainLooper() {
synchronized (Looper.class) {
return sMainLooper;
}
}
根据源码知道,Looper有个静态成员sThreadLocal,通过它保存每个线程的Looper(可以把它当做一个Map,其中key就是线程,value就是Looper,它的内部实现就不再深入解析了)。执行Looper.prepare(),最终便会为当前线程创建Looper对象,其中会创建MessageQueue(所以,一个Looper就对应有一个MessageQueue),需要注意,已创建了Looper则不能再执行该方法,否则会抛出异常"Only one Looper may be created per thread"。在方法Looper.prepare()的注释中,我们知道,当创建完Looper对象需要执行Looper.loop()。继续看源码,看Looper.loop()做了什么。
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
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
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
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();
}
}
终于看到Looper最核心的代码了,其实就是一个死循环。现在,我们对Handler、Looper、MessageQueue有了初步的了解,接下来通过时序图看看他们三者是如何工作的。
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);
}
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) {
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) {
//等下Looper就是通过该target回调通知处理消息
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
上面展示的是通过sendMessage(message)的方式发送消息,我们有时也会通过post(runnable)发送消息,源码如下:
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
其实就是进一步封装成带有callback的Message,后面的流程还是一样。消息发送完后,接下来就是Looper去获取消息,见上面的源码Looper.loop(),通过queue.next()获得有效消息后,执行msg.target.dispatchMessage(msg),其中target就是Handler了,看看dispatchMessage()方法做了什么。
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
private static void handleCallback(Message message) {
message.callback.run();
}
说到这里,是不是有种峰回路转的感觉哈!Handler机制表面上理解还是比较简单的,能力不足就只能解析到这里了。
四、总结
1、每个线程只有一个Looper,可通过Looper.prepare()创建,其中主线程启动就通过Looper.prepareMainLooper()创建了,创建完Looper记得执行Looper.loop()。
2、创建Handler对象时,需要保证当前线程已创建Looper,如果确定是主线程的Handler,可通过Looper.getMainLooper()传入Looper对象构造。
3、一般我们会在类通过new Handler()并重写handleMessage(messgae)方法来构造,其实这时我们就是创建了一个匿名内部类,而内部类默认是持有外部类的对象,所以这时需要注意是否存在内存泄露的问题。一般我们在退出activity时会通过handler.removeCallbacksAndMessages(null)来移除所有待处理的消息。