關(guān)于這幾個(gè)技術(shù)術(shù)語(yǔ)弊攘,讓我們從Android的實(shí)際使用中來(lái)漸漸理清它們。
1. Looper的初始化
Application被創(chuàng)建時(shí),ActivityThread的main函數(shù)會(huì)被調(diào)用,其中初始化了一個(gè)Looper
Looper.prepareMainLooper();
其實(shí)現(xiàn)在Looper.java中:
/**
* 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); //進(jìn)行初始化
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper(); //賦值
}
}
prepare(false)是對(duì)Looper進(jìn)行初始化, 初始化之后調(diào)用將Looper對(duì)象賦值給sMainLooper. 所以我們只需要看prepare函數(shù):
......
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal();
......
private static void prepare(boolean quitAllowed) {
if(sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
} else {
sThreadLocal.set(new Looper(quitAllowed)); //創(chuàng)建一個(gè)Looper對(duì)象,放入ThreadLocal中
}
}
從之前的描述可以看出,Looper是一個(gè)單例,所以其構(gòu)造函數(shù)是private的:
private Looper(boolean quitAllowed) {
this.mQueue = new MessageQueue(quitAllowed);
this.mRun = true;
this.mThread = Thread.currentThread();
}
2. 初始化MessageQueue
上面的Looper的構(gòu)造函數(shù)中又初始化了一個(gè)MessageQueue姑曙,這里又引出了一個(gè)重要的對(duì)象MessageQueue . 每個(gè)Looper都保持一個(gè)MessageQueue用來(lái)存放Message. 這里只需要記住Looper和MessageQueue的關(guān)系即可.下面是MessageQueue 的構(gòu)造函數(shù):
/**
* Low-level class holding the list of messages to be dispatched by a
* Looper. Messages are not added directly to a MessageQueue,
* but rather through Handler objects associated with the Looper.
*
* You can retrieve the MessageQueue for the current thread with
* Looper.myQueue().
*/
MessageQueue(boolean quitAllowed) {
mQuitAllowed = quitAllowed;
mPtr = nativeInit();
}
從構(gòu)造函數(shù)上面的描述可以看到,Message是不能直接加入到MessageQueue中的, 必須通過(guò)Handler來(lái)添加. 這里你可能會(huì)有疑問(wèn)襟交,為什么Message不能直接加入到MessageQueue里面呢?帶著這個(gè)問(wèn)題我們繼續(xù)向下看伤靠。
3. 創(chuàng)建ActivityThread對(duì)象
Looper初始化完成后, 回到ActivityThread的main函數(shù), 這里還創(chuàng)建了一個(gè)ActivityThread對(duì)象,對(duì)App來(lái)說(shuō),ActivityThread是一個(gè)非常重要的類(lèi),
//初始化ActivityThread
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
ActivityThread的構(gòu)造函數(shù)中初始化了ResourcesManager,保存在mResourcesManager中. thread.attach(false)這個(gè)比較重要,是進(jìn)行一些狀態(tài)的設(shè)置和初始化. 隨后會(huì)初始化這個(gè)應(yīng)用程序UI線(xiàn)程的Handle .下面是getHandler()
final Handler getHandler() {
return mH;
}
其中mH的定義如下:
private class H extends Handler {
public void handleMessage(Message msg) {
if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
switch (msg.what) {
case LAUNCH_ACTIVITY: {
final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
r.packageInfo = getPackageInfoNoCheck(
r.activityInfo.applicationInfo, r.compatInfo);
handleLaunchActivity(r, null);
} break;
case RELAUNCH_ACTIVITY: {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityRestart");
ActivityClientRecord r = (ActivityClientRecord)msg.obj;
handleRelaunchActivity(r);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
}
}
其handleMessage這個(gè)函數(shù)很長(zhǎng),仔細(xì)看就可以發(fā)現(xiàn),這里調(diào)度了應(yīng)用開(kāi)發(fā)中各個(gè)組件的生命周期.包括activityRestart/activityPause/activityStop/activityDestroy/activityNewIntent等等.
4. 執(zhí)行消息循環(huán)
隨后main函數(shù)會(huì)調(diào)用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();
......
final MessageQueue queue = me.mQueue;
......
for (;;) {
Message msg = queue.next(); // might block
.......
msg.target.dispatchMessage(msg);
......
msg.recycleUnchecked();
}
}
可以看到其中調(diào)用了一個(gè)死循環(huán)for (;;),在循環(huán)開(kāi)始調(diào)用
Message msg = queue.next(); // might block
來(lái)從MessageQueue中獲取Message來(lái)進(jìn)行處理.注意到MessageQueue的next函數(shù)會(huì)調(diào)用this.nativePollOnce(this.mPtr, nextPollTimeoutMillis); 這是一個(gè)阻塞方法. 會(huì)調(diào)用到Native層的Looper的一些方法. 當(dāng)有消息的時(shí)候,就會(huì)返回一個(gè)Message.
這時(shí)候一個(gè)Activity的Handle/ Looper / MessageQueue都已經(jīng)跑起來(lái)了.他們直接的關(guān)系也清楚了.
5. 自己創(chuàng)建的Handler與Looper和MessageQueue之間的關(guān)系
在Android開(kāi)發(fā)中,我們一般會(huì)自己創(chuàng)建一個(gè)Handler,然后發(fā)送Message進(jìn)行通信 (典型場(chǎng)景就是創(chuàng)建一個(gè)子線(xiàn)程, 在其中執(zhí)行耗時(shí)較多的操作,然后發(fā)一個(gè)Message通知UI更新)
第一種寫(xiě)法:無(wú)參數(shù)的Handler
Handler defaultHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_HELLO:
Log.w(TAG, "defaultHandler ThreadName = "
+ defaultHandler.getLooper().getThread().getName());
}
}
};
......
//使用
new Thread(){
@Override
public void run() {
defaultHandler.sendEmptyMessage(MSG_HELLO);
}
}.start();
其打印結(jié)果如下:
這種寫(xiě)法創(chuàng)建的Handler,將自動(dòng)與當(dāng)前運(yùn)行的線(xiàn)程相關(guān)聯(lián),也就是說(shuō)這個(gè)自定義的Handler將與當(dāng)前運(yùn)行的線(xiàn)程使用同一個(gè)消息隊(duì)列,并且可以處理該隊(duì)列中的消息.如果不太理解這個(gè)可以查看Handler的構(gòu)造函數(shù):
public Handler(Callback callback, boolean async) {
......
mLooper = Looper.myLooper();
......
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
可以看到, Handler中的mLooper和mQueue就是之前ActivityThread中初始化好的.由于Looper是單例,也就是說(shuō)mLooper和mQueue都只有一個(gè), 而Handler的sendMessage最終會(huì)調(diào)用sendMessageAtTime:
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
MessageQueue queue = mQueue;
......
return enqueueMessage(queue, msg, uptimeMillis);
}
看到這里,應(yīng)該對(duì)自己創(chuàng)建的Handler和MessageQueue以及Looper直接的關(guān)系更清楚了.
第二種寫(xiě)法:參數(shù)包含Looper的Handler
Handler有好幾個(gè)構(gòu)造函數(shù),其中如果參數(shù)中不包含Looper,則最終會(huì)進(jìn)入第一種寫(xiě)法中的那個(gè)構(gòu)造函數(shù),如果參數(shù)中包含Looper,則會(huì)進(jìn)入到三個(gè)參數(shù)的構(gòu)造函數(shù)中:
/**
* Use the provided Looper instead of the default one and take a callback
* interface in which to handle messages. Also set whether the handler
* should be asynchronous.
*
* Handlers are synchronous by default unless this constructor is used to make
* one that is strictly asynchronous.
*
* Asynchronous messages represent interrupts or events that do not require global ordering
* with represent to synchronous messages. Asynchronous messages are not subject to
* the synchronization barriers introduced by MessageQueue#enqueueSyncBarrier(long).
*
* @param looper The looper, must not be null.
* @param callback The callback interface in which to handle messages, or null.
* @param async If true, the handler calls Message#setAsynchronous(boolean) for
* each Message that is sent to it or Runnable that is posted to it.
*
* @hide
*/
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
這種Handler初始化的時(shí)候必須創(chuàng)建一個(gè)Looper對(duì)象
Handler mHandler;
class CustomThread extends Thread {
@Override
public void run() {
Looper.prepare();
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_HELLO:
Log.w(TAG, "defaultHandler ThreadName = "
+ defaultHandler.getLooper().getThread().getName());
break;
default:
break;
}
}
};
Looper.loop();
}
}
//使用
CustomThread mCustomThread = new CustomThread();
mCustomThread.start();
我給TextView加了一個(gè)點(diǎn)擊事件捣域,點(diǎn)擊會(huì)打印對(duì)應(yīng)的線(xiàn)程名:
appNameText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mHandler.sendEmptyMessage(MSG_HELLO);
Log.w(TAG, "MainThreadName =" + getMainLooper().getThread().getName());
}
});
其結(jié)果如下:
通過(guò)上面兩個(gè)例子,你應(yīng)該對(duì)Thread/Looper/MessageQueue/Handler有更深入的了解了.