Handler 使用
一、Handler和Looper关联
1、子线程内先调用Looper.prepare();
2、再创建Handler,
3、Looper.loop(); 让Looper开始工作
二、Looper
Looper创建
一个线程只能创建一个Looper,且把Looper 存到ThreadLocal中;
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));
}
Looper构造函数创建MassageQueue;
//Looper 关联主线程时为false
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
Handler构造函数会关联Looper
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 " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
其中mLooper = Looper.myLooper();获取本线程ThreadLocal中的Looper
/**
* 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();
}
Looper.loop是个死循环;
不断从消息队列中读取消息,取出消息进行分发;但阻塞是在queue.next();
退出条件-msg=null(MessageQueue 返回空);
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/