Handler
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()); //非静态内部的handle可能引起内存泄漏。应该使用static 的handler
}
}
mLooper = Looper.myLooper();// 拿到looper
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;
}
Looper.myLooper()
:
/**
* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
* 返回当前线程关联的looper, 可能返回null
*/
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
handleMessage
/**
* Subclasses must implement this to receive messages.
* 需要子类来实现处理消息的方法
*/
public void handleMessage(Message msg) {
}
/**
* Handle system messages here.
* 分发消息回调方法:
* msg.callback
* mCallback
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ ( T | o ) ( Y | o | u | t | h | , | T | o ) ( S | i | m | p | l | e | ! ) \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/