全面總結(jié)Android中線程的異步處理方式
一、概述
Handler 、 Looper 、Message 這三者都與Android異步消息處理線程相關(guān)的概念。那么什么叫異步消息處理線程呢?
異步消息處理線程啟動后會進入一個無限的循環(huán)體之中,每循環(huán)一次,從其內(nèi)部的消息隊列中取出一個消息,然后回調(diào)相應的消息處理函數(shù),執(zhí)行完成一個消息后則繼續(xù)循環(huán)。若消息隊列為空,線程則會阻塞等待。
說了這一堆,那么和Handler 、 Looper 、Message有啥關(guān)系?其實Looper負責的就是創(chuàng)建一個MessageQueue,然后進入一個無限循環(huán)體不斷從該MessageQueue中讀取消息,而消息的創(chuàng)建者就是一個或多個Handler 。
二、源碼解析
1、Looper
對于Looper主要是prepare()和loop()兩個方法。
首先看prepare()方法
public static final void prepare() {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(true));
}
sThreadLocal是一個ThreadLocal對象,可以在一個線程中存儲變量??梢钥吹剑诘?行,將一個Looper的實例放入了ThreadLocal,并且2-4行判斷了sThreadLocal是否為null,否則拋出異常。這也就說明了Looper.prepare()方法不能被調(diào)用兩次,同時也保證了一個線程中只有一個Looper實例~相信有些哥們一定遇到這個錯誤。
下面看Looper的構(gòu)造方法:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mRun = true;
mThread = Thread.currentThread();
}
在構(gòu)造方法中,創(chuàng)建了一個MessageQueue(消息隊列)。
然后我們看loop()方法:
public static void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;
// 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(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
// 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);
}
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.recycle();
}
}
第2行:
public static Looper myLooper() {
return sThreadLocal.get();
}
方法直接返回了sThreadLocal存儲的Looper實例,如果me為null則拋出異常,也就是說looper方法必須在prepare方法之后運行。
第6行:拿到該looper實例中的mQueue(消息隊列)
13到45行:就進入了我們所說的無限循環(huán)。
14行:取出一條消息,如果沒有消息則阻塞。
27行:使用調(diào)用 msg.target.dispatchMessage(msg);把消息交給msg的target的dispatchMessage方法去處理。Msg的target是什么呢?其實就是handler對象,下面會進行分析。
44行:釋放消息占據(jù)的資源。
Looper主要作用:
(1)與當前線程綁定,保證一個線程只會有一個Looper實例,同時一個Looper實例也只有一個MessageQueue。
(2)loop()方法,不斷從MessageQueue中去取消息,交給消息的target屬性的dispatchMessage去處理。
好了,我們的異步消息處理線程已經(jīng)有了消息隊列(MessageQueue),也有了在無限循環(huán)體中取出消息的哥們,現(xiàn)在缺的就是發(fā)送消息的對象了,于是乎:Handler登場了。
2、Handler
使用Handler之前,我們都是初始化一個實例,比如用于更新UI線程,我們會在聲明的時候直接初始化,或者在onCreate中初始化Handler實例。所以我們首先看Handler的構(gòu)造方法,看其如何與MessageQueue聯(lián)系上的,它在子線程中發(fā)送的消息(一般發(fā)送消息都在非UI線程)怎么發(fā)送到MessageQueue中的。
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();
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;
}
14行:通過Looper.myLooper()獲取了當前線程保存的Looper實例,然后在19行又獲取了這個Looper實例中保存的MessageQueue(消息隊列),這樣就保證了handler的實例與我們Looper實例中MessageQueue關(guān)聯(lián)上了。
Handler 常用方法:
(1)post(Runnable)
(2)postAtTime(Runnable,long)
(3)postDelayed(Runnable long)
(4)sendEmptyMessage(int)
(5)sendMessage(Message)
(6)sendMessageAtTime(Message,long)
(7)sendMessageDelayed(Message,long)
以上post類方法允許你排列一個Runnable對象到主線程隊列中, sendMessage類方法, 允許你安排一個帶數(shù)據(jù)的Message對象到隊列中,等待更新.
一般運行邏輯:
點擊button --- > 啟動一條新線程,用來處理數(shù)據(jù) ---- >數(shù)據(jù)處理完畢,通過handler返回 ----- > handler里面接收返回的數(shù)據(jù),進行UI更新等處理。
然后看我們最常用的sendMessage方法
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageDelayed(msg, delayMillis);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
MessageQueue queue = mQueue;
if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
return false;
}
return enqueueMessage(queue, msg, uptimeMillis);
}
輾轉(zhuǎn)反則最后調(diào)用了sendMessageAtTime,在此方法內(nèi)部有直接獲取MessageQueue然后調(diào)用了enqueueMessage方法,我們再來看看此方法:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
enqueueMessage中首先為meg.target賦值為this,【如果大家還記得Looper的loop方法會取出每個msg然后交給msg,target.dispatchMessage(msg)去處理消息】,也就是把當前的handler作為msg的target屬性。最終會調(diào)用queue的enqueueMessage的方法,也就是說handler發(fā)出的消息,最終會保存到消息隊列中去。
現(xiàn)在已經(jīng)很清楚了Looper會調(diào)用prepare()和loop()方法,在當前執(zhí)行的線程中保存一個Looper實例,這個實例會保存一個MessageQueue對象,然后當前線程進入一個無限循環(huán)中去,不斷從MessageQueue中讀取Handler發(fā)來的消息。然后再回調(diào)創(chuàng)建這個消息的handler中的dispathMessage方法,下面我們趕快去看一看這個方法:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
可以看到,第10行,調(diào)用了handleMessage方法,下面我們?nèi)タ催@個方法:
/**
* Subclasses must implement this to receive messages.
*/
public void handleMessage(Message msg) {
}
可以看到這是一個空方法,為什么呢,因為消息的最終回調(diào)是由我們控制的,我們在創(chuàng)建handler的時候都是復寫handleMessage方法,然后根據(jù)msg.what進行消息處理。
例如:
private Handler mHandler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
switch (msg.what)
{
case value:
break;
default:
break;
}
};
};
到此,這個流程已經(jīng)解釋完畢,讓我們首先總結(jié)一下
(1)首先Looper.prepare()在本線程中保存一個Looper實例,然后該實例中保存一個MessageQueue對象;因為Looper.prepare()在一個線程中只能調(diào)用一次,所以MessageQueue在一個線程中只會存在一個。
(2)Looper.loop()會讓當前線程進入一個無限循環(huán),不端從MessageQueue的實例中讀取消息,然后回調(diào)msg.target.dispatchMessage(msg)方法。
(3)Handler的構(gòu)造方法,會首先得到當前線程中保存的Looper實例,進而與Looper實例中的MessageQueue想關(guān)聯(lián)。
(4)Handler的sendMessage方法,會給msg的target賦值為handler自身,然后加入MessageQueue中。
(5)在構(gòu)造Handler實例時,我們會重寫handleMessage方法,也就是msg.target.dispatchMessage(msg)最終調(diào)用的方法。
好了,總結(jié)完成,大家可能還會問,那么在Activity中,我們并沒有顯示的調(diào)用Looper.prepare()和Looper.loop()方法,為啥Handler可以成功創(chuàng)建呢,這是因為在Activity的啟動代碼中,已經(jīng)在當前UI線程調(diào)用了Looper.prepare()和Looper.loop()方法。
3、Handler post
今天有人問我,你說Handler的post方法創(chuàng)建的線程和UI線程有什么關(guān)系?
其實這個問題也是出現(xiàn)這篇博客的原因之一;這里需要說明,有時候為了方便,我們會直接寫如下代碼:
mHandler.post(new Runnable()
{
@Override
public void run()
{
Log.e("TAG", Thread.currentThread().getName());
mTxt.setText("yoxi");
}
});
然后run方法中可以寫更新UI的代碼,其實這個Runnable并沒有創(chuàng)建什么線程,而是發(fā)送了一條消息,下面看源碼:
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
可以看到,在getPostMessage中,得到了一個Message對象,然后將我們創(chuàng)建的Runable對象作為callback屬性,賦值給了此message.
注:產(chǎn)生一個Message對象,可以new ,也可以使用Message.obtain()方法;兩者都可以,但是更建議使用obtain方法,因為Message內(nèi)部維護了一個Message池用于Message的復用,避免使用new 重新分配內(nèi)存。
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
MessageQueue queue = mQueue;
if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
return false;
}
return enqueueMessage(queue, msg, uptimeMillis);
}
最終和handler.sendMessage一樣,調(diào)用了sendMessageAtTime,然后調(diào)用了enqueueMessage方法,給msg.target賦值為handler,最終加入MessagQueue.
可以看到,這里msg的callback和target都有值,那么會執(zhí)行哪個呢?
其實上面已經(jīng)貼過代碼,就是dispatchMessage方法:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
第2行,如果不為null,則執(zhí)行callback回調(diào),也就是我們的Runnable對象。
好了,關(guān)于Looper , Handler , Message 這三者關(guān)系上面已經(jīng)敘述的非常清楚了。
最后來張圖解:

希望圖片可以更好的幫助大家的記憶~~
三、補充
其實Handler不僅可以更新UI,你完全可以在一個子線程中去創(chuàng)建一個Handler,然后使用這個handler實例在任何其他線程中發(fā)送消息,最終處理消息的代碼都會在你創(chuàng)建Handler實例的線程中運行。
eg:
new Thread()
{
private Handler handler;
public void run()
{
Looper.prepare();
handler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
Log.e("TAG",Thread.currentThread().getName());
};
}
}
Android不僅給我們提供了異步消息處理機制讓我們更好的完成UI的更新,其實也為我們提供了異步消息處理機制代碼的參考~~不僅能夠知道原理,最好還可以將此設(shè)計用到其他的非Android項目中去~~
- Android異步消息機制詳解
- android開發(fā)教程之handle實現(xiàn)多線程和異步處理
- Android中BroadcastReceiver(異步接收廣播Intent)的使用
- android異步請求服務器數(shù)據(jù)示例
- Android多線程及異步處理問題詳細探討
- Android加載對話框同時異步執(zhí)行實現(xiàn)方法
- android開發(fā)教程之handler異步更新ui
- Android App中實現(xiàn)圖片異步加載的實例分享
- 詳解Android的OkHttp包編寫異步HTTP請求調(diào)用的方法
- Android最基本的異步網(wǎng)絡(luò)請求框架
- Android編程實現(xiàn)異步消息處理機制的幾種方法總結(jié)
相關(guān)文章
Android批量插入數(shù)據(jù)到SQLite數(shù)據(jù)庫的方法
這篇文章主要為大家詳細介紹了Android批量插入數(shù)據(jù)到SQLite數(shù)據(jù)庫的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-03-03
Android Studio創(chuàng)建AIDL文件并實現(xiàn)進程間通訊實例
本篇文章主要介紹了Android Studio創(chuàng)建AIDL文件并實現(xiàn)進程間通訊實例,具有一定的參考價值,有興趣可以了解一下。2017-04-04
Android開發(fā)實現(xiàn)ImageView加載攝像頭拍攝的大圖功能
這篇文章主要介紹了Android開發(fā)實現(xiàn)ImageView加載攝像頭拍攝的大圖功能,涉及Android基于ImageView的攝像頭拍攝圖片加載、保存及權(quán)限控制等相關(guān)操作技巧,需要的朋友可以參考下2017-11-11
Android 兩個ViewPager的聯(lián)動效果的實現(xiàn)
這篇文章主要介紹了Android 兩個ViewPager的聯(lián)動效果的實現(xiàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08
Flutter TV Android端開發(fā)技巧詳細教程
這篇文章主要為大家介紹了Flutter TV Android端開發(fā)技巧詳細教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12

