概述:
通信的同步(Synchronous):指向用戶端發送請求後,必須要在服務端有回應後用戶端才繼續發送其它的請求,是以這時所有請求将會在服務端得到同步,直到服務端傳回請求。
通信的異步(Asynchronous):指用戶端在發送請求後,不必等待服務端的回應就可以發送下一個請求。
所謂同步調用,就是在一個函數或方法調用時,沒有得到結果之前,該調用就不傳回,直到傳回結果。異步調用和同步是相對的,在一個異步調用發起後,被調用者立即傳回給調用者,但是調用者不能立刻得到結果,被調用都在實際處理這個調用的請求完成後,通過狀态、通知或回調等方式來通知調用者請求處理的結果。
android的消息處理有三個核心類:Looper,Handler和Message。其實還有一Message Queue(消息隊列),但是MQ被封裝到Looper裡面了,我們不會直接與MQ打交道,是以它不算是個核心類。
1. 消息類:Message類
android.os.Message的主要功能是進行消息的封裝,同時可以指定消息的操作形式,Message類定義的變量和常用方法如下:
(1)public int what:變量,用于定義此Message屬于何種操作
(2)public Object obj:變量,用于定義此Message傳遞的資訊資料,通過它傳遞資訊
(3)public int arg1:變量,傳遞一些整型資料時使用
(4)public int arg2:變量,傳遞一些整型資料時使用
(5)public Handler getTarget():普通方法,取得操作此消息的Handler對象。
在整個消息處理機制中,message又叫task,封裝了任務攜帶的資訊和處理該任務的handler。message的用法比較簡單,但是有這麼幾點需要注意:
(1)盡管Message有public的預設構造方法,但是你應該通過Message.obtain()來從消息池中獲得空消息對象,以節省資源。
(2)如果你的message隻需要攜帶簡單的int資訊,請優先使用Message.arg1和Message.arg2來傳遞資訊,這比用Bundle更省記憶體
(3)擅用message.what來辨別資訊,以便用不同方式處理message。
2. 消息通道:Looper
在使用Handler處理Message時,需要Looper(通道)來完成。在一個Activity中,系統會自動幫使用者啟動Looper對象,而在一個使用者自定義的類中,則需要使用者手工調用Looper類中的方法,然後才可以正常啟動Looper對象。Looper的字面意思是“循環者”,它被設計用來使一個普通線程變成Looper線程。所謂Looper線程就是循環工作的線程。在程式開發中(尤其是GUI開發中),我們經常會需要一個線程不斷循環,一旦有新任務則執行,執行完繼續等待下一個任務,這就是Looper線程。使用Looper類建立Looper線程很簡單:
public class LooperThread extends Thread {
@Override
public void run() {
// 将目前線程初始化為Looper線程
Looper.prepare();
// ...其他處理,如執行個體化handler
// 開始循環處理消息隊列
Looper.loop();
}
}
通過上面兩行核心代碼,你的線程就更新為Looper線程了!那麼這兩行代碼都做了些什麼呢?
1)Looper.prepare()
通過上圖可以看到,現在你的線程中有一個Looper對象,它的内部維護了一個消息隊列MQ。注意,一個Thread隻能有一個Looper對象,為什麼呢?來看一下源碼
public class Looper {
// 每個線程中的Looper對象其實是一個ThreadLocal,即線程本地存儲(TLS)對象
private static final ThreadLocal sThreadLocal = new ThreadLocal();
// Looper内的消息隊列
final MessageQueue mQueue;
// 目前線程
Thread mThread;
//其他屬性
// 每個Looper對象中有它的消息隊列,和它所屬的線程
private Looper() {
mQueue = new MessageQueue();
mRun = true;
mThread = Thread.currentThread();
}
// 我們調用該方法會在調用線程的TLS中建立Looper對象
public static final void prepare() {
if (sThreadLocal.get() != null) {
// 試圖在有Looper的線程中再次建立Looper将抛出異常
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper());
}
// 其他方法
}
prepare()背後的工作方式一目了然,其核心就是将looper對象定義為ThreadLocal。
2)Looper.loop()
調用loop方法後,Looper線程就開始真正工作了,它不斷從自己的MQ中取出隊頭的消息(也叫任務)執行。其源碼分析如下:
public static final void loop() {
Looper me = myLooper(); //得到目前線程Looper
MessageQueue queue = me.mQueue; //得到目前looper的MQ
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
// 開始循環
while (true) {
Message msg = queue.next(); // 取出message
if (msg != null) {
if (msg.target == null) {
// message沒有target為結束信号,退出循環
return;
}
// 日志
if (me.mLogging!= null) me.mLogging.println(
">>>>> Dispatching to " + msg.target + " "
+ msg.callback + ": " + msg.what
);
// 非常重要!将真正的處理工作交給message的target,即後面要講的handler
msg.target.dispatchMessage(msg);
// 日志
if (me.mLogging!= null) me.mLogging.println(
"<<<<< Finished to " + msg.target + " "
+ msg.callback);
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf("Looper", "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);
}
// 回收message資源
msg.recycle();
}
}
}
除了prepare()和loop()方法,Looper類還提供了一些有用的方法,比如Looper.myLooper()得到目前線程looper對象:
public static final Looper myLooper() {
// 在任意線程調用Looper.myLooper()傳回的都是那個線程的looper
return (Looper)sThreadLocal.get();
}
getThread()得到looper對象所屬線程:
public Thread getThread() {
return mThread;
}
quit()方法結束looper循環:
public void quit() {
// 建立一個空的message,它的target為NULL,表示結束循環消息
Message msg = Message.obtain();
// 發出消息
mQueue.enqueueMessage(msg, );
}
綜上,Looper有以下幾個要點:
1)每個線程有且隻能有一個Looper對象,它是一個ThreadLocal
2)Looper内部有一個消息隊列,loop()方法調用後線程開始不斷從隊列中取出消息執行
3)Looper使一個線程變成Looper線程。
那麼,我們如何操作Message Queue上的消息呢?這就是Handler的用處了
3. 消息操作類:Handler類
Message對象封裝了所有的消息,而這些消息的操作需要android.os.Handler類完成。什麼是handler?handler起到了處理MQ上的消息的作用(隻處理由自己發出的消息),即通知MQ它要執行一個任務(sendMessage),并在loop到自己的時候執行該任務(handleMessage),整個過程是異步的。handler建立時會關聯一個looper,預設的構造方法将關聯目前線程的looper,不過這也是可以set的。預設的構造方法:
public class handler {
final MessageQueue mQueue; // 關聯的MQ
final Looper mLooper; // 關聯的looper
final Callback mCallback;
// 其他屬性
public Handler() {
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());
}
}
// 預設将關聯目前線程的looper
mLooper = Looper.myLooper();
// looper不能為空,即該預設的構造方法隻能在looper線程中使用
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
// 重要!!!直接把關聯looper的MQ作為自己的MQ,是以它的消息将發送到關聯looper的MQ上
mQueue = mLooper.mQueue;
mCallback = null;
}
// 其他方法
}
下面我們就可以為之前的LooperThread類加入Handler:
public class LooperThread extends Thread {
private Handler handler1;
private Handler handler2;
@Override
public void run() {
// 将目前線程初始化為Looper線程
Looper.prepare();
// 執行個體化兩個handler
handler1 = new Handler();
handler2 = new Handler();
// 開始循環處理消息隊列
Looper.loop();
}
}
加入handler後的效果如下圖:
可以看到,一個線程可以有多個Handler,但是隻能有一個Looper!
Handler發送消息
有了handler之後,我們就可以使用
post(Runnable)
postAtTime(Runnable, long)
postDelayed(Runnable, long)
sendEmptyMessage(int)
sendMessage(Message)
sendMessageAtTime(Message, long)
sendMessageDelayed(Message, long)
這些方法向MQ上發送消息了。光看這些API你可能會覺得handler能發兩種消息,一種是Runnable對象,一種是message對象,這是直覺的了解,但其實post發出的Runnable對象最後都被封裝成message對象了,見源碼:
// 此方法用于向關聯的MQ上發送Runnable對象,它的run方法将在handler關聯的looper線程中執行
public final boolean post(Runnable r)
{
// 注意getPostMessage(r)将runnable封裝成message
return sendMessageDelayed(getPostMessage(r), );
}
private final Message getPostMessage(Runnable r) {
Message m = Message.obtain(); //得到空的message
m.callback = r; //将runnable設為message的callback,
return m;
}
public boolean sendMessageAtTime(Message msg, long uptimeMillis)
{
boolean sent = false;
MessageQueue queue = mQueue;
if (queue != null) {
msg.target = this; // message的target必須設為該handler!
sent = queue.enqueueMessage(msg, uptimeMillis);
}
else {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
}
return sent;
}
通過handler發出的message有如下特點:
1.message.target為該handler對象,這確定了looper執行到該message時能找到處理它的handler,即loop()方法中的關鍵代碼
msg.target.dispatchMessage(msg);
2.post發出的message,其callback為Runnable對象
Handler處理消息
說完了消息的發送,再來看下handler如何處理消息。消息的處理是通過核心方法dispatchMessage(Message msg)與鈎子方法handleMessage(Message msg)
完成的,見源碼
dispatchMessage(Message msg) {
(msg.callback != ) {
handleCallback(msg);
} {
(mCallback != ) {
(mCallback.handleMessage(msg)) {
;
}
}
handleMessage(msg);
}
}
handleCallback(Message message) {
message.callback.run(); }
handleMessage(Message msg) {
}
可以看到,除了handleMessage(Message msg)和Runnable對象的run方法由開發者實作外(實作具體邏輯),handler的内部工作機制對開發者是透明的。Handler擁有下面兩個重要的特點:
1)handler可以在任意線程發送消息,這些消息會被添加到關聯的MQ上
2)消息的處理是通過核心方法dispatchMessage(Message msg)與鈎子方法handleMessage(Message msg)完成的,handler是在它關聯的looper線程中處理消息的。
這就解決了android最經典的不能在其他非主線程中更新UI的問題。android的主線程也是一個looper線程(looper在android中運用很廣),我們在其中建立的handler預設将關聯主線程MQ。是以,利用handler的一個solution就是在activity中建立handler并将其引用傳遞給worker thread,worker thread執行完任務後使用handler發送消息通知activity更新UI。(過程如圖)