Handler源碼分析
首先分析主線程調用Handler的流程
一般在Activity中,創建一個靜態內部類,Handler的子類
在Activity中使用的時候,直接調用構造函數創建實例
/**
* 默認構造函數,將handler與當前線程的Looper關聯
* 如果這個線程沒有一個looper,這個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());
}
}
mLooper = Looper.myLooper();
//前面說過,looper爲空的時候,handler收不到任何的消息,會拋出異常
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;
}
總結上面的構造函數,主要作用還是通過Looper.myLooper獲取到handler需要的looper,接下來我們看下這段代碼
/**
* 返回和當前線程關聯的Looper,如果當前線程沒有關聯Looper,就會返回null
*/
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
那麼handler的構造函數就分析到這裏,總結一下:
1.handler的構造函數有7個,其中最常用的就是無參構造函數
2.無參構造函數,調用包含callback(null),async(false)的兩個參數的構造函數
3.構造函數中,對內存泄露進行檢測
4.通過Looper的靜態方法myLooper獲取到當前線程的looper,當然其實主要針對的是主線程,子線程的looper需要開發者自行指定
5.將looper中的消息隊列賦值給成員變量mQueue
6.其他成員變量賦值