先总结一下Handler,MessageQueue,Looper之间消息传递的工作原理和相关异常信息,后面进行源码分析。
1 主线程中创建唯一的一个Looper,在Looper对象中,创建MessageQueue对象
首先Android程序启动时会开启主线程Main Thread(主线程通常被叫做UI线程);
在Main Thread中会创建Looper对象;
为了保证每个线程中只能有一个Looper,所以在Looper.prepare()方法中,会判断当前线程是否已经存在Looper对象,如果存在,则会抛出"Only one Looper may be created per thread",否则就创建Looper,这样就保证了每个线程中只能有一个Looper;
在Looper对象中,又会创建MessageQueue;
这样,和Main Thread相关联的Looper和MessageQueue就创建好了。
2 Handler 和 Looper与MessageQueue相关联(都是在主线程中)
当我们在Main Thread中创建Handler时,会去拿到已经创建好的Looper,当然也拿到looper的MessageQueue;
如果为Null,则证明是在非UI线程中,会抛出java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()异常;
这样Handler,Message,Looper三者就相关联了。
3 Handler,MessageQueue,Looper三者功能区分
Handler发送的消息会发送到MessageQueue中;
Looper.loop方法不断读取MessageQueue中的消息,并将消息分发给对应的Handler,handler再处理消息;
MessageQueue为消息队,由Looper管理;
4 子线程中创建Handler
如果在子线程中创建Handler的时候,在构造Handler的时候,会拿到和当前线程相关联的Looper对象,但是当前的子线程中并没有Looper对象,所以会抛出“java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()”异常。
5 在非UI线程更新UI
在非UI线程更新UI时,会调用checkThread方法,判断当前线程是否是UI线程,如果不是,则会抛出“Only the original thread that created a view hierarchy can touch its views.”即非UI线程不能更新UI。
下面从源码的角度分析:
6.1 UI线程创建相互关联的Looper和MessageQueue,并且保证每个线程中只存在一个Looper对象。
ActivityThread的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对象。在prepareMainLooper()中,又会调用 prepare()方法:
public static void prepare() {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper());
}
sThreadLocal即为主线程,初始化的时候 sThreadLocal.get()为空,创建一个Looper()对象。
private Looper() {
mQueue = new MessageQueue();
mRun = true;
mThread = Thread.currentThread();
}
可以看到,在初始化Looper对象的时候,创建了一个与之关联的MessageQueue()。
这时候,UI线程已经创建了相互关联的Looper和MessageQueue,并且保证每个线程中只存在一个Looper对象。
6.2 Handler 和 Looper与MessageQueue相关联
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;
}
当在主线程中创建Handler时,Handler构造函数中会调用Looper.myLooper():
public static Looper myLooper() {
return sThreadLocal.get();
}
sThreadLocal即为当前的主线程,通过sThreadLocal.get()拿到当前线程创建的Looper对象。这时候Handler就和Looper相关联了。
6.3 Handler , Looper,MessageQueue之间的整个消息传递机制
当Handler.sendMessage()时, msg.target = this将消息发送的对象指定为当前的Handler。
如果是在子线程中创建Handler,那么sThreadLocal.get()为空,则会抛出"Can't create handler inside thread that has not called Looper.prepare()"这条刚开始接触Handler时常见的异常了。
所以:如果要在子线程中创建并使用Handler,则在创建Handler之前,必须调用Looper. prepare()创建一个Looper对象,再调用Looper. loop(),使用死循环不断取出MessageQueue中的消息。
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.recycle();
}
}
可以看到, msg.target.dispatchMessage(msg)将取出的消息分发出去, target即为Handler本身。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
在dispatchMessage()中,则回调了我们熟悉的 handleMessage(msg)方法。
这样,就完成了从Handler发送消息到Looper的MessageQueue中,通过Looper.loop()不断循环,把消息取出来再分发给Handler自己,通过 回调handleMessage(msg),处理不同消息的整个消息传递机制。
6.4 为什么不能在非UI线程更新UI
void checkThread() {
if (mThread != Thread.currentThread()) {
throw new CalledFromWrongThreadException(
"Only the original thread that created a view hierarchy can touch its views.");
}
}
6.5 移除消息队列里面的消息
public final void removeCallbacksAndMessages( Object token)
使用场景: 销毁Activity时,移除队列中的消息,防止Activity对象不能释放。