學(xué)習(xí)android的一大樂趣是可以通過源碼學(xué)習(xí)google大牛們的設(shè)計(jì)思想鬼悠。android源碼中包含了大量的設(shè)計(jì)模式爵嗅,除此以外,android sdk還精心為我們設(shè)計(jì)了各種helper類掸宛,對于和我一樣渴望水平得到進(jìn)階的人來說考传,都太值得一讀了肴焊。
android的消息處理有三個(gè)核心類:Looper,Handler和Message前联。其實(shí)還有一個(gè)Message Queue(消息隊(duì)列,以下均稱為MQ)娶眷,但是MQ被封裝到Looper里面了似嗤,開發(fā)中不會(huì)直接與MQ打交道,因此不作為核心類届宠。
1. 線程的魔法師 Looper
Looper的字面意思是“循環(huán)者”双谆,它被設(shè)計(jì)用來使一個(gè)普通線程變成Looper線程(我的英文名就是取自這里,2333)席揽。所謂Looper線程就是循環(huán)工作的線程顽馋。在程序開發(fā)中(尤其是GUI開發(fā)中),我們經(jīng)常會(huì)需要一個(gè)線程不斷循環(huán)幌羞,一旦有新任務(wù)則執(zhí)行寸谜,執(zhí)行完繼續(xù)等待下一個(gè)任務(wù),這就是Looper線程属桦。使用Looper類創(chuàng)建Looper線程很簡單:
public class LooperThread extends Thread {
@Override
public void run() {
// 將當(dāng)前線程初始化為Looper線程
Looper.prepare();
// ...其他處理熊痴,如實(shí)例化handler
// 開始循環(huán)處理消息隊(duì)列
Looper.loop();
}
}
通過上面兩行核心代碼,你的線程就升級為Looper線程了D舯觥9啤!夠很神奇吧系谐?咱們來看看這兩行代碼各自做了什么巾陕。
Looper.prepare()
通過上圖可以看到,現(xiàn)在你的線程中有一個(gè)Looper對象纪他,它的內(nèi)部維護(hù)了一個(gè)消息隊(duì)列MQ鄙煤。注意,一個(gè)Thread只能有一個(gè)Looper對象茶袒,為什么呢梯刚?咱們來看源碼。
public class Looper {
// 每個(gè)線程中的Looper對象其實(shí)是一個(gè)ThreadLocal薪寓,即線程本地存儲(chǔ)(TLS)對象
private static final ThreadLocal sThreadLocal = new ThreadLocal();
// Looper內(nèi)的消息隊(duì)列
final MessageQueue mQueue;
// 當(dāng)前線程
Thread mThread;
// 亡资。。向叉。其他屬性
// 每個(gè)Looper對象中有它的消息隊(duì)列锥腻,和它所屬的線程
private Looper() {
mQueue = new MessageQueue();
mRun = true;
mThread = Thread.currentThread();
}
// 我們調(diào)用該方法會(huì)在調(diào)用線程的TLS中創(chuàng)建Looper對象
public static final void prepare() {
if (sThreadLocal.get() != null) {
// 試圖在有Looper的線程中再次創(chuàng)建Looper將拋出異常
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper());
}
// 其他方法
}
通過源碼,prepare()背后的工作方式一目了然植康,其核心就是將looper對象定義為ThreadLocal旷太。如果你還不清楚什么是ThreadLocal,請參考 徹底理解ThreadLocal
Looper.loop()
調(diào)用loop方法后,Looper線程就開始真正工作了销睁,它不斷從自己的MQ中取出隊(duì)頭的消息(也叫任務(wù))執(zhí)行供璧。其源碼分析如下:
public static void loop() {
final Looper me = myLooper();//取得當(dāng)前線程looper
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;//取得當(dāng)前線程looper中的MQ
//沒看懂,但不影響理解 冻记,請自行體會(huì)官方注釋
// Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
for (;;) {
Message msg = queue.next(); //取出消息
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
//沒看懂睡毒,請自行體會(huì)官方注釋
// This must be in a local variable, in case a UI event sets the logger
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
// 非常重要!將真正的處理工作交給message的target冗栗,即后面要講的handler
msg.target.dispatchMessage(msg);
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
//沒看懂演顾,不影響理解
// Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "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);
}
//回收消息資源
msg.recycleUnchecked();
}
}
除了prepare()和loop()方法,Looper類還提供了一些有用的方法隅居,比如
Looper.myLooper()得到當(dāng)前線程looper對象:
public static final Looper myLooper() {
// 在任意線程調(diào)用 Looper.myLooper()返回的都是那個(gè)線程的looper
return (Looper)sThreadLocal.get();
}
getThread()得到looper對象所屬線程:
public Thread getThread() {
return mThread;
}
除了prepare()和loop()方法钠至,Looper類還提供了一些有用的方法,比如
Looper.myLooper()得到當(dāng)前線程looper對象:
public static final Looper myLooper() {
// 在任意線程調(diào)用 Looper.myLooper()返回的都是那個(gè)線程的looper
return (Looper)sThreadLocal.get();
}
getThread()得到looper對象所屬線程:
public Thread getThread() {
return mThread;
}
quit()方法結(jié)束looper循環(huán):
public void quit() {
// 創(chuàng)建一個(gè)空的message胎源,它的target為NULL棉钧,表示結(jié)束循環(huán)消息
Message msg = Message.obtain();// 發(fā)出消息
mQueue.enqueueMessage(msg, 0);
}
到此為止,你應(yīng)該對Looper有了基本的了解涕蚤,總結(jié)幾點(diǎn):
- 每個(gè)線程有且最多只能有一個(gè)Looper對象宪卿,它是一個(gè)ThreadLocal
- Looper內(nèi)部有一個(gè)消息隊(duì)列,loop()方法調(diào)用后線程開始不斷從消息隊(duì)列中取出消息執(zhí)行
- Looper可以使一個(gè)線程變成Looper線程万栅。
2. 異步處理大師 Handler
什么是handler佑钾?handler扮演了往MQ上添加消息和處理消息的角色(只處理由自己發(fā)出的消息),即通知MQ它要執(zhí)行一個(gè)任務(wù)(sendMessage)烦粒,并在loop到自己的時(shí)候執(zhí)行該任務(wù)(handleMessage)休溶,整個(gè)過程是異步的。handler創(chuàng)建時(shí)會(huì)關(guān)聯(lián)一個(gè)looper扰她,默認(rèn)的構(gòu)造方法將關(guān)聯(lián)當(dāng)前線程的looper邮偎,不過這也是可以set的。默認(rèn)的構(gòu)造方法:
public class handler {
final MessageQueue mQueue; // 關(guān)聯(lián)的MQ
final Looper mLooper; // 關(guān)聯(lián)的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());
}
}
// 默認(rèn)將關(guān)聯(lián)當(dāng)前線程的looper
mLooper = Looper.myLooper();
// looper不能為空泻云,即該默認(rèn)的構(gòu)造方法只能在looper線程中使用
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
// 重要!直接把關(guān)聯(lián)looper的MQ作為自己的MQ狐蜕,因此它的消息將發(fā)送到關(guān)聯(lián)looper的MQ上
mQueue = mLooper.mQueue;
mCallback = null;
}
// 其他方法
}
下面咱們就可以為之前的LooperThread類加入Handler:
public class LooperThread extends Thread {
private Handler handler1;
private Handler handler2;
@Override
public void run() {
// 將當(dāng)前線程初始化為Looper線程
Looper.prepare();
// 實(shí)例化兩個(gè)handler
handler1 = new Handler();
handler2 = new Handler();
// 開始循環(huán)處理消息隊(duì)列
Looper.loop();
}
}
Handler發(fā)送消息
有了handler之后宠纯,我們就可以使用以下這些方法向MQ上發(fā)送消息了。
- post(Runnable)
- postAtTime(Runnable, long)
- postDelayed(Runnable, long)
- sendEmptyMessage(int)
- sendMessage(Message)
- sendMessageAtTime(Message, long)
- sendMessageDelayed(Message, long)
光看這些API可能會(huì)覺得handler能發(fā)兩種消息层释,一種是Runnable對象婆瓜,一種是message對象,這是直觀的理解,但其實(shí)post發(fā)出的Runnable對象最后都被封裝成message對象了廉白,見源碼:
// 此方法用于向關(guān)聯(lián)的MQ上發(fā)送Runnable對象个初,它的run方法將在handler關(guān)聯(lián)的looper線程中執(zhí)行
public final boolean post(Runnable r)
{
// 注意getPostMessage(r)將runnable封裝成message
return sendMessageDelayed(getPostMessage(r), 0);
}
private final Message getPostMessage(Runnable r) {
Message m = Message.obtain(); //得到空的message
m.callback = r; //將runnable設(shè)為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必須設(shè)為該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發(fā)出的message有如下特點(diǎn):
- message.target為該handler對象,這確保了looper執(zhí)行到該message時(shí)能找到處理它的handler磅轻,即loop()方法中的關(guān)鍵代碼
msg.target.dispatchMessage(msg);
- post發(fā)出的message珍逸,其callback為Runnable對象
Handler處理消息
說完了消息的發(fā)送,再來看下handler如何處理消息聋溜。消息的處理是通過核心方法dispatchMessage(Message msg)與鉤子方法handleMessage(Message msg)完成的谆膳,見源碼
// 處理消息,該方法由looper調(diào)用
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
// 如果message設(shè)置了callback撮躁,即runnable消息漱病,處理callback!
handleCallback(msg);
} else {
// 如果handler本身設(shè)置了callback馒胆,則執(zhí)行callback
if (mCallback != null) {
/* 這種方法允許讓activity等來實(shí)現(xiàn)Handler.Callback接口缨称,避免了自己編寫handler重寫handleMessage方法。見http://alex-yang-xiansoftware-com.iteye.com/blog/850865 */
if (mCallback.handleMessage(msg)) {
return;
}
}
// 如果message沒有callback祝迂,則調(diào)用handler的鉤子方法handleMessage
handleMessage(msg);
}
}
// 處理runnable消息
private final void handleCallback(Message message) {
message.callback.run(); //直接調(diào)用run方法睦尽!
}
// 由子類實(shí)現(xiàn)的鉤子方法
public void handleMessage(Message msg) {
}
可以看到,除了handleMessage(Message msg)和Runnable對象的run方法由開發(fā)者實(shí)現(xiàn)外(實(shí)現(xiàn)具體邏輯)型雳,handler的內(nèi)部工作機(jī)制對開發(fā)者是透明的当凡。這正是handler API設(shè)計(jì)的精妙之處!
Handler的用處
- handler可以在任意線程發(fā)送消息纠俭,這些消息會(huì)被添加到當(dāng)前線程looper關(guān)聯(lián)的MQ上沿量。
- handler是在與它關(guān)聯(lián)的looper線程中處理消息的
這就解決了android最經(jīng)典的不能在其他非主線程中更新UI的問題。android的主線程也是一個(gè)looper線程(looper在android中運(yùn)用很廣)冤荆,我們在其中創(chuàng)建的handler默認(rèn)將關(guān)聯(lián)主線程MQ朴则。因此,利用handler的一個(gè)solution就是在activity中創(chuàng)建handler并將其引用傳遞給worker thread钓简,worker thread執(zhí)行完任務(wù)后使用handler發(fā)送消息通知activity更新UI乌妒。(過程如圖)
下面給出sample代碼,僅供參考:
public class TestDriverActivity extends Activity {
private TextView textview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textview = (TextView) findViewById(R.id.textview);
// 創(chuàng)建并啟動(dòng)工作線程
Thread workerThread = new Thread(new SampleTask(new MyHandler()));
workerThread.start();
}
public void appendText(String msg) {
textview.setText(textview.getText() + "\n" + msg);
}
class MyHandler extends Handler {
@Override
public void handleMessage(Message msg) {
String result = msg.getData().getString("message");
// 更新UI
appendText(result);
}
}
}
public class SampleTask implements Runnable {
private static final String TAG = SampleTask.class.getSimpleName();
Handler handler;
public SampleTask(Handler handler) {
super();
this.handler = handler;
}
@Override
public void run() {
try { // 模擬執(zhí)行某項(xiàng)任務(wù)外邓,下載等
Thread.sleep(5000);
// 任務(wù)完成后通知activity更新UI
Message msg = prepareMessage("task completed!");
// message將被添加到主線程的MQ中
handler.sendMessage(msg);
} catch (InterruptedException e) {
Log.d(TAG, "interrupted!");
}
}
private Message prepareMessage(String str) {
Message result = handler.obtainMessage();
Bundle data = new Bundle();
data.putString("message", str);
result.setData(data);
return result;
}
}
封裝任務(wù) Message
在整個(gè)消息處理機(jī)制中撤蚊,message又叫task,封裝了任務(wù)攜帶的信息和處理該任務(wù)的handler损话。message的用法比較簡單侦啸,這里不做總結(jié)了槽唾。但是有這么幾點(diǎn)需要注意:
1.盡管Message有public的默認(rèn)構(gòu)造方法,但是你應(yīng)該通過Message.obtain()來從消息池中獲得空消息對象光涂,以節(jié)省資源庞萍。具體Message源碼分析請參考 管理與分配內(nèi)存
2.如果你的message只需要攜帶簡單的int信息,請優(yōu)先使用Message.arg1和Message.arg2來傳遞信息顶捷,這比用Bundle更省內(nèi)存
3.擅用message.what來標(biāo)識(shí)信息挂绰,以便用不同方式處理message屎篱。
到此為止了服赎,Android消息處理機(jī)制差不多就講完了,好累交播,有木有打賞的重虑?