很久沒寫博客了,一直想寫下android關于源碼分析的文章,今天就來分析下android中的異步消息處理機制Handler的原理。Handler的用法我們都再熟悉不過了。其最經典的用法如下:
~~~
Looper.prepare();
~~~
~~~
private Handler handlerWenzhang = new Handler(){
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:break;
case 1:break;
default:break;
}
};
};
~~~
~~~
Looper.loop();
~~~
接下來在子線程中發送消息。
~~~
Message message = new Message();
Bundle bundle = new Bundle();
bundle.putString("message", "1");
message.setData(bundle);
handler.sendMessage(message);
~~~
以上handleMessage()方法中就是在主線程調用,一般用于進行UI操作,而sendMessage()方法是在子線程中調用,把結果傳到主線程,這就實現了異步通信。使用方法用簡單,但是只會用而不知道其原理往往會很不爽,所以讓我們來看看handler的源碼實現吧。
我們來細究handler的內部原理。在介紹handler之前我們要先了解下什么是Looper,Handler和MessageQueue。
Handler:用于在子線程發送消息,在主線程獲得和處理消息;
MessageQueue:是一個管理消息的隊列,消息是先入先出的。
Looper:負責讀取MessageQueue中的消息,讀取到后交給Handler處理。要注意的是每個線程都必須定義一個Looper,之所以平時我們在使用時很少定義Looper是因為android的主線程中已經默認給我們定義好了,所以不需要再次定義。
程序一開始就應該調用Looper.prepare()來定義Looper,首先看看Looper的代碼:
~~~
public static void prepare() {
prepare(true);
}
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并放入sThreadLocal中,這樣保證線程中只有一個Looper。既然創建了Looper,就先看看它的構造方法:
~~~
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
~~~
很簡單,創建了一個消息隊列。接著我們來看看定義了Handler,前面我們已經提過,Handler一般在子線程中發送消息,在主線程中從MessageQueue中取數據,那么具體怎么實現的呢,先看看Handler的構造方法:
~~~
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;
}
~~~
主要看看第10行代碼,通過Looper的myLooper獲取到線程中的Looper對象,代碼如下:
~~~
public static Looper myLooper() {
return sThreadLocal.get();
}
~~~
然后第15行代碼就是獲得Looper的MessageQuene對象,這樣Handler就和MessageQuene連接起來了。接著我們調用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.recycle();
}
}
~~~
以上代碼很長,首先是先獲取Looper對象,如果不存在拋異常。queue.next()就是消息出隊列的意思,如果有消息就將其出隊列,其中for循環其到一個不斷取數據的作用,如果沒數據,就阻塞。調用msg.target.dispatchMessage(msg)對獲得的消息進行處理,通過前文我們可以猜測target應該是Handler。那么就先把它當Handler,接下來當然就是看Handler的dispatchMessage()方法啦。
~~~
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
~~~
看看handleMessage()方法,有沒有很熟悉。而在Handler中handleMessage()是一個空方法。
~~~
public void handleMessage(Message msg) {
}
~~~
所以我們如果要對消息進行處理就只要重寫handleMessage()方法即可。到此是不是對Handler如何取數據和如何處理數據相當清楚啦。但我們還有些疑問,Handler是如何發送消息的,消息如何進入隊列的。還有就是為什么上面的target是Handler。要弄明白這些,就只能繼續看代碼。
我們來看看發送的代碼,一般調用sendMessage()、sendEmptyMessage()等方法來發送消息。追蹤源碼可知無論是sendMessage()還是sendEmptyMessage最終都調用的是sendMessageAtTime(Message msg, long uptimeMillis)方法。讓我們來看看它的源碼:
~~~
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);
}
~~~
方法很簡單,傳入兩個參數,msg是我們發送的消息,uptimMills指發送消息的時間。若像延時發送可設置此值。最后返回enqueueMessage方法。讓我們繼續看看enqueueMessage實現了什么功能。
~~~
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
~~~
看到第二行,我們是不是明白了什么。在這里把msg.target賦值Handler,這就回答了上面的問題。最后調用的是MessageQueue中的enqueueMessage方法。查看下enqueueMessage的方法:
~~~
boolean enqueueMessage(Message msg, long when) {
if (msg.isInUse()) {
throw new AndroidRuntimeException(msg + " This message is already in use.");
}
if (msg.target == null) {
throw new AndroidRuntimeException("Message must have a target.");
}
synchronized (this) {
if (mQuitting) {
RuntimeException e = new RuntimeException(
msg.target + " sending message to a Handler on a dead thread");
Log.w("MessageQueue", e.getMessage(), e);
return false;
}
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;
}
~~~
這個就是入隊的意思。將消息傳入MessageQueue中。看上面代碼才知道,原來MessageQueue并不是一個集合把消息都存起來。它是按傳入的時間參數來對消息進行排序。這就完成了消息的入隊。到此我們整個Handler的處理過程就講完了,接下來總結一下:
Handler在子線程中通過sendMessage()方法經enqueueMessage將消息傳入到MessageQueue隊列中。此時仍在子線程中。Handler再通過loop()方法獲得消息并在handleMessage方法中處理。Handler是建立在主線程中的,所以handlerMessage就是在主線程處理相關操作。
關于HandleMessage的講解就到這里,可能個人的分析有出錯的地方,希望指出。
- 前言
- Android底部tab與標題欄相結合
- Android免費獲取短信驗證碼
- android中Handler的源碼分析
- 詳解Fragment的傳值問題
- 詳談gson解析
- android新控件之toolbar,floatingActionButton,SnackBar,CollapsingToolbarLayout
- android自定義控件
- 淺談android的線程池
- Android的消息處理機制,AsyncTask源碼解析
- IPC——android進程間通信
- CoCos2d_android入門所需知道的一切
- Cocos2d_android你所需要知道的一切(下)
- Activity你需要知道的一切
- Activity啟動過程源碼分析
- Data Binding Guide——google官方文檔翻譯(上)
- Data Binding Guide——google官方文檔翻譯(下)
- android TextView實現跑馬燈效果
- android中生成excel
- Volley源碼解析
- LayoutInflater源碼解析
- android發送郵件
- android測試工具MonkeyRunner--google官網翻譯
- android View繪制源碼分析
- Android中Window添加View的底層原理
- 仿美團商品選購下拉菜單實現