前言及簡介
前些天我們整個項(xiàng)目組趁著小假期摆寄,驅(qū)車去了江門市的臺山猛虎峽玩了兩個多鐘左右極限勇士全程漂流,感覺真得不錯,天氣熱就應(yīng)該多多玩水椭迎,多親近一下大自然锐帜,不要整天埋頭工作。寫文章主要是讓朋友們一起相互分享學(xué)習(xí)畜号,共同進(jìn)步。
好了允瞧,言歸正題简软,今天我們要講的主題是關(guān)于Android中的異步消息處理機(jī)制的內(nèi)容。有一點(diǎn)Android基礎(chǔ)的朋友們都知道述暂,在Android中痹升,主線程(也就是UI線程)是不安全的,當(dāng)在主線程處理消息過長時畦韭,非常容易發(fā)生ANR(Application Not Responding)現(xiàn)象疼蛾,這樣對于用戶體驗(yàn)是非常不好的;其次艺配,如果我們在子線程中嘗試進(jìn)行UI的操作察郁,程序就可能還會直接崩潰。我相信转唉,對于大多剛?cè)腴T的朋友皮钠,在日常工作當(dāng)中會經(jīng)常遇到這個問題,而解決的方法大多已經(jīng)通過google已了解清楚赠法,也就是在子線程中創(chuàng)建一個消息Message對象麦轰,然后利用在主線程中創(chuàng)建的Handler對象進(jìn)行發(fā)送,之后我們可以在這個Handler對象的handlerMessage()方法中獲取剛剛發(fā)送的Message對象砖织,取出里面所存儲的值款侵,就可以在這里進(jìn)行UI的操作。這種方法就稱為異步消息處理線程侧纯。
總的來說新锈,異步消息處理線程,說得比較通俗一點(diǎn)就是茂蚓,當(dāng)我們啟動此方法后壕鹉,會進(jìn)入到一個無限的循環(huán)當(dāng)中,每循環(huán)一次聋涨,我們就其對應(yīng)的內(nèi)部消息隊(duì)列(Message Queue)中取出一個消息(Message)晾浴,然后回調(diào)好相應(yīng)的消息處理函數(shù),當(dāng)執(zhí)行完一個消息后則繼續(xù)循環(huán)牍白,若當(dāng)消息隊(duì)列中消息為空脊凰,則線程會被阻塞等待,直到有消息進(jìn)入時再被喚醒。
好吧狸涌,說了那么多切省,現(xiàn)在,就讓我們來看一下這種處理機(jī)制的廬山真面目吧帕胆。
分析Handler
首先我們來分析分析一下Handler的用法朝捆,我們知道,要創(chuàng)建一個Handler對象非常的簡單明了懒豹,直接進(jìn)行new一個對象即可芙盘,但是你有沒有想過,這里會隱藏著什么注意點(diǎn)呢×郴啵現(xiàn)在可以試著寫一下下面的一小段代碼儒老,然后自己運(yùn)行看看:
public class MainActivity extends ActionBarActivity {
private Handler mHandler0;
private Handler mHandler1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler0 = new Handler();
new Thread(new Runnable() {
@Override
public void run() {
mHandler1 = new Handler();
}
}).start();
}
這一小段程序代碼主要創(chuàng)建了兩個Handler對象,其中记餐,一個在主線程中創(chuàng)建驮樊,而另外一個則在子線程中創(chuàng)建,現(xiàn)在運(yùn)行一下程序片酝,則你會發(fā)現(xiàn)囚衔,在子線程創(chuàng)建的Handler對象竟然會導(dǎo)致程序直接崩潰,提示的錯誤竟然是Can't create handler inside thread that has not called Looper.prepare()
于是我們按照logcat中所說钠怯,在子線程中加入Looper.prepare(),即代碼如下:
new Thread(new Runnable(){
@override
public void run(){
Looper.prepare();
mHandler1 = new Handler()l
}
}).start();
再次運(yùn)行一下程序佳魔,發(fā)現(xiàn)程序不會再崩潰了,可是晦炊,單單只加這句Looper.prepare()是否就能解決問題了鞠鲜。我們探討問題,就要知其然断国,才能了解得更多贤姆。我們還是先分析一下源碼吧,看看為什么在子線程中沒有加Looper.prepare()就會出現(xiàn)崩潰稳衬,而主線程中為什么不用加這句代碼霞捡?我們看下Handler()構(gòu)造函數(shù):
public Handler() {
this(null, false);
}
構(gòu)造函數(shù)直接調(diào)用this(null, false),于是接著看其調(diào)用的函數(shù)薄疚,
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;
}
不難看出碧信,源碼中調(diào)用了mLooper = Looper.myLooper()方法獲取一個Looper對象,若此時Looper對象為null街夭,則會直接拋出一個“Can't create handler inside thread that has not called Looper.prepare()”異常砰碴,那什么時候造成mLooper是為空呢?那就接著分析Looper.myLooper()板丽,
public static Looper myLooper() {
return sThreadLocal.get();
}
這個方法在sThreadLocal變量中直接取出Looper對象呈枉,若sThreadLocal變量中存在Looper對象,則直接返回,若不存在猖辫,則直接返回null酥泞,而sThreadLocal變量是什么呢?
static final ThreadLocat<Looper> sThreadLocal = new ThreadLocal<Looper>();
它是本地線程變量啃憎,存放在Looper對象芝囤,由這也可看出,每個線程只有存有一個Looper對象辛萍,可是凡人,是在哪里給sThreadLocal設(shè)置Looper的呢,通過前面的試驗(yàn)叹阔,我們不難猜到,應(yīng)該是在Looper.prepare()方法中传睹,現(xiàn)在來看看它的源碼:
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
由此看到耳幢,我們的判斷是正確的,在Looper.prepare()方法中給sThreadLocal變量設(shè)置Looper對象欧啤,這樣也就理解了為什么要先調(diào)用Looper.prepare()方法睛藻,才能創(chuàng)建Handler對象,才不會導(dǎo)致崩潰邢隧。但是店印,仔細(xì)想想,為什么主線程就不用調(diào)用呢倒慧?不要急按摘,我們接著分析一下主線程,我們查看一下ActivityThread中的main()方法纫谅,代碼如下:
public static void main(String[] args) {
SamplingProfilerIntegration.start();
// CloseGuard defaults to true and can be quite spammy. We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
// Set the reporter for event logging in libcore
EventLogger.setReporter(new EventLoggingReporter());
Security.addProvider(new AndroidKeyStoreProvider());
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
代碼中調(diào)用了Looper.prepareMainLooper()方法炫贤,而這個方法又會繼續(xù)調(diào)用了Looper.prepare()方法,代碼如下:
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
分析到這里已經(jīng)真相大白付秕,主線程中g(shù)oogle工程師已經(jīng)自動幫我們創(chuàng)建了一個Looper對象了兰珍,因而我們不再需要手動再調(diào)用Looper.prepare()再創(chuàng)建,而子線程中询吴,因?yàn)闆]有自動幫我們創(chuàng)建Looper對象掠河,因此需要我們手動添加,調(diào)用方法是Looper.prepare()猛计,這樣唠摹,我們才能正確地創(chuàng)建Handler對象。
發(fā)送消息
當(dāng)我們正確的創(chuàng)建Handler對象后有滑,接下來我們來了解一下怎么發(fā)送消息跃闹,有一點(diǎn)基礎(chǔ)的朋友肯定對這個方法已經(jīng)了如指掌了。具體是先創(chuàng)建出一個Message對象,然后可以利用一些方法望艺,如setData()或者使用arg參數(shù)等方式來存放數(shù)據(jù)于消息中苛秕,再借助Handler對象將消息發(fā)送出去就可以了。
new Thread(new Runnable() {
@Override
public void run() {
Message msg = Message.obtain();
msg.arg1 = 1;
msg.arg2 = 2;
Bundle bundle = new Bundle();
bundle.putChar("key", 'v');
bundle.putString("key","value");
msg.setData(bundle);
mHandler0.sendMessage(msg);
}
}).start();
通過Message對象進(jìn)行傳遞消息找默,在消息中添加各種數(shù)據(jù)艇劫,之后再消息通過mHandler0進(jìn)行傳遞,之后我們再利用Handler中的handleMessage()方法將此時傳遞的Message進(jìn)行捕獲出來惩激,再分析得到存儲在msg中的數(shù)據(jù)店煞。但是,這個流程到底是怎么樣的呢风钻?具體我們還是來分析一下源碼顷蟀。首先分析一下發(fā)送方法sendMessage():
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
通過調(diào)用sendMessageDelayed(msg, 0)方法
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
再能過調(diào)用sendMessageDelayed(Message msg, long delayMillis),方法中第一個參數(shù)是指發(fā)送的消息msg,第二個參數(shù)是指延遲多少毫秒發(fā)送,我們著重看一下此方法:
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);
}
由這里可以分析得出骡技,原來消息Message對象是建立一個消息隊(duì)列MessageQueue,這個對象MessageQueue由mQueue賦值鸣个,而由源碼分析得出mQueue = mLooper.mQueue,而mLooper則是Looper對象布朦,我們由上面已經(jīng)知道囤萤,每個線程只有一個Looper,因此是趴,一個Looper也就對應(yīng)了一個MessageQueue對象涛舍,之后調(diào)用enqueueMessage(queue, msg, uptimeMillis)直接入隊(duì)操作:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
方法通過調(diào)用MessageQueue對enqueueMessage(Message msg, long uptimeMills)方法:
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
synchronized (this) {
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w("MessageQueue", e.getMessage(), e);
msg.recycle();
return false;
}
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// Inserted within the middle of the queue. Usually we don't have to wake
// up the event queue unless there is a barrier at the head of the queue
// and the message is the earliest asynchronous message in the queue.
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
首先要知道,源碼中用mMessages代表當(dāng)前等待處理的消息唆途,MessageQueue也沒有使用一個集合保存所有的消息富雅。觀察中間的代碼部分,隊(duì)列中根據(jù)時間when來時間排序窘哈,這個時間也就是我們傳進(jìn)來延遲的時間uptimeMills參數(shù)吹榴,之后再根據(jù)時間的順序調(diào)用msg.next,從而指定下一個將要處理的消息是什么。如果只是通過sendMessageAtFrontOfQueue()方法來發(fā)送消息
public final boolean sendMessageAtFrontOfQueue(Message msg) {
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, 0);
}
它也是直接調(diào)用enqueueMessage()進(jìn)行入隊(duì)滚婉,但沒有延遲時間图筹,此時會將傳遞的此消息直接添加到隊(duì)頭處,現(xiàn)在入隊(duì)操作已經(jīng)了解得差不多了让腹,接下來應(yīng)該來了解一下出隊(duì)操作远剩,那么出隊(duì)在哪里進(jìn)行的呢,不要忘記MessageQueue對象是在Looper中賦值骇窍,因此我們可以在Looper類中找瓜晤,來看一看Looper.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.recycleUnchecked();
}
}
代碼比較多,我們只挑重要的分析一下腹纳,我們可以看到下面的代碼用for(;;)進(jìn)入了一個死循環(huán)痢掠,之后不斷的從MessageQueue對象queue中取出消息msg驱犹,而我們不難知道,此時的next()就是進(jìn)行隊(duì)列的出隊(duì)方法足画,next()方法代碼有點(diǎn)長雄驹,有興趣的話可以自行翻閱查看,主要邏輯是判斷當(dāng)前的MessageQueue是否存在待處理的mMessages消息淹辞,如果有医舆,則將這個消息出隊(duì),然后讓下一個消息成為mMessages象缀,否則就進(jìn)入一個阻塞狀態(tài)蔬将,一直等到有新的消息入隊(duì)喚醒⊙胄牵回看loop()方法霞怀,可以發(fā)現(xiàn)當(dāng)執(zhí)行next()方法后會執(zhí)行msg.target.dispatchMessage(msg)方法,而不難看出莉给,此時msg.target就是Handler對象里烦,繼續(xù)看一下dispatchMessage()方法:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
先進(jìn)行判斷mCallback是否為空,若不為空則調(diào)用mCallback的handleMessage()方法禁谦,否則直接調(diào)用handleMessage()方法,并將消息作為參數(shù)傳出去废封。這樣我們就完全一目了然州泊,為什么我們要使用handleMessage()來捕獲我們之前傳遞過去的信息。
現(xiàn)在我們根據(jù)上面的理解漂洋,不難寫出異步消息處理機(jī)制的線程了遥皂。
class myThread extends Thread{
public Handler myHandler;
@Override
public void run() {
Looper.prepare();
myHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
//處理消息
}
};
Looper.loop();
}
}
當(dāng)然除了發(fā)送消息外,還有以下幾個方法可以在子線程中進(jìn)行UI操作:
- View的post()方法
- Handler的post()方法
- Activity的runOnUiThread()方法
其實(shí)這幾個方法的本質(zhì)都是一樣的刽漂,只要我們勤于查看這幾個方法的源碼演训,不難看出最后調(diào)用的也是Handler機(jī)制,也是借用了異步消息處理機(jī)制來實(shí)現(xiàn)的贝咙。
總結(jié)
通過上面對異步消息處理線程的講解样悟,我們不難真正地理解到了Handler、Looper以及Message之間的關(guān)系庭猩,概括性來說窟她,Looper負(fù)責(zé)的是創(chuàng)建一個MessageQueue對象,然后進(jìn)入到一個無限循環(huán)體中不斷取出消息蔼水,而這些消息都是由一個或者多個Handler進(jìn)行創(chuàng)建處理震糖。
接下來朋友們想要了解哪方面的東西或者有什么好的想法,可以在下面留言交流趴腋,我會盡自己的能力選擇分享給朋友們吊说,當(dāng)然论咏,如果有什么分享錯誤或者不懂的地方,可以相互交流颁井,期待每個朋友在我的博文中都能學(xué)到東西厅贪,如果覺得好的話,麻煩各位兄弟關(guān)注一下蚤蔓,謝謝X砸纭!