前言
Android中的消息機制一直都是新手頭疼的問題,對於Handler機制的理解是Android重中之重,經常在面試和日常開發中遇到,所以,這篇文章目的是通過解析源碼來幫助梳理Handler的工作機制和運行流程。再此之前先解決一下新手疑惑的問題,還有爲文章後面解析做鋪墊。
Handler機制到底幹嘛用的?
在實際開發中,最常用到Handler就是切換到UI線程中更新UI,其實Handler不止是更新UI纔會用到,對於任何切換線程執行任務都是可以做的。
爲什麼Android中只能在主線程(UI線程)中更新UI?
Android和通常的GUI程序一樣,都是單線程模型的,因爲要UI更新效率直接影響到用戶體驗,所以UI的處理一定要放在第一位。子線程可能造成UI更新發錯亂,原因是多個子線程同時對一個UI控件進行操作,結果造成界面更新不符合預期,如果用到上鎖機制,你就想想你的代碼會有多複雜吧。。而且加鎖會影響UI更新效率,所以綜上原因,Android只允許你在主線程中更新UI。
Android程序的入口在哪裏?
剛學習Java的同學都是從在main方法中寫一句System.out.println(“Hello World!”)開始的,而學了Android之後,就有疑問了:Android程序沒有main方法嗎??答案肯定是有的,在Android中入口類是ActivityThread,其中main方法就是程序啓動時入口方法。
Handler的基本用法
public class MainActivity extends AppCompatActivity {
private TextView mTextView;
private Button mButton;
//點擊按鈕之後新建一個子線程,發送一個消息到Looper的消息隊列中輪循
private Runnable mTask = new Runnable() {
@Override
public void run() {
Message message = Message.obtain();
message.obj = "Hello World";
mHandler.sendMessage(message);
}
};
//Handler對象,handleMessage方法會在Looper處理到消息時候回調
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
mTextView.setText((CharSequence) msg.obj);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
mTextView = (TextView) findViewById(R.id.tv_hello);
mButton = (Button) findViewById(R.id.btn_set_text);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(mTask).start();
}
});
}
}
大家對以上的操作應該是很熟悉了吧,不熟悉你就要去看看handler怎麼使用的文檔,再接着看下面的解析。。這就是一個簡單的從子線程切換到主線程去更新UI的做法。同時Handler的應用還有HandlerThread,這裏就不展開講了,有興趣可以自行查看文檔。
Handler機制原理
下面就開始通過源碼來解析Handler機制的原理了,其實Handler機制由三個類構成,分別是Handler,Looper,MessageQueue。在此就不貼出流程圖了,個人覺得流程圖並不能完全呈現出其運作原理,而且容易誤導你對源碼的理解。
Looper的源碼淺析
Looper中主要需要關注的兩個方法是prepare和loop。這個類的主要作用是用來輪詢Handler發送的消息,能夠使得消息的處理在指定線程中執行,得益於ThreadLocal類。ThreadLocal是一個線程內部數據存儲類,有了它就可以在指定的線程中存儲數據。
首先來看下Looper的構造方法:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
Looper的構造方法是private修飾的,意味着Looper只能在Looper類中構造,而查看源碼發現,Looper的構造只有在prepare方法出現。並且在構造的時候,Looper對象會持有一個MessageQueue的引用,並且記錄了當前的線程。下面來看下prepare方法的邏輯:
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));
}
prepare()方法很簡單,就是創建一個Looper對象,保存在sThreadLocal中,這樣Looper對象就和當前的線程關聯起來了。
總結來說Looper的創建其實很簡單,可以理解爲將一個Looper對象存儲到當前線程中,不同線程中創建的Looper,通過Looper.myLooper()返回的Looper是不同實例。下面是Looper中的核心方法,loop方法。
//省略的代碼大部分是非邏輯的日誌記錄相關代碼
public static void loop() {
//省略若干代碼
for (;;) {
Message msg = queue.next(); // queue是當前的消息隊列對象,這裏可能堵塞線程
if (msg == null) {
return;
}
//省略若干代碼
try {
msg.target.dispatchMessage(msg);
} finally {
//省略若干代碼
}
//省略若干代碼
}
}
這裏的代碼也很簡單,就是一個死循環,不停從Looper持有的MessageQueue對象中排隊出message。然後調用msg.target.despatchMessage(msg),注意:這裏都是在Looper所在線程中調用的。msg.target就是發送了這條消息的主人,也就是handler對象,調用dispatchMessage方法就會按照一定的邏輯順序回調處理信息的方法,具體邏輯下面再講,這樣就講完了Looper的核心工作原理了,並沒有多複雜,當然源碼還是看着有點繞的,感興趣的同學可以去看下源碼。
Handler的源碼淺析
Handler的主要作用是發送message和處理message,handler是怎麼和looper關聯起來的呢,其實就是通過handler的構造方法,其中Handler總共有7個構造方法,最終調用的就是以下兩個中的一個:
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
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;
}
其實仔細觀察可以發現,區別就是有沒有傳入Looper,沒有傳入的話,當前Handler中的mLooper默認就是當前線程中的Looper,如果當前線程沒有Looper對象就會拋出異常。因此,handler必須是要有looper關聯着的,缺少了Looper的Handler是不能工作的。
我們剛學習handler用法的時候都是從sendMessage(msg)開始的,其實handler發送message的方式有很多,比如post,postDelay,sendMessageAtTime等等···其實不論是以什麼樣的形式發送的消息,最後都是調用了enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis)方法,這個方法再調用了消息隊列的中的enqueueMessage(Message msg, long when)方法,這樣就將該消息放入消息隊列中排隊了。
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
上面講過了,在Looper的loop方法中,如果輪詢當一條消息時會調用發送該消息的dispatchMessage方法,這樣就分發了該消息交給handler來處理,dispatchMessage有一定的分發邏輯,我們來看代碼分析:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
首先判斷msg是否存在callback,如果存在就是調用該callback(Runnable對象)的run方法;否則先判斷該handler的mCallback是否爲空,如果不爲空,則調用它的handleMessage方法,如果它的handleMessage返回false,則還會調用handler中的handleMessage方法;如果其返回了true,則不會調用handler中的handleMessage方法;如果mCallback爲空,那也只會調用handler中的handleMessage方法。感覺很繞是吧···最好還是自己畫一個流程圖,這樣就能清楚知道這個邏輯了。爲毛弄這麼複雜的邏輯呢?其實這樣就滿足你的多種體位,啊,呸··滿足你的多種實現方式,比如能message多次分發,比如這種寫法:
private Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
Log.d(TAG, "首先回調此方法 " + msg.obj);
return false;
}
}) {
@Override
public void handleMessage(Message msg) {
Log.d(TAG, "然後後回調此方法 " + msg.obj);
}
};
這樣的寫法既給handler傳入了一個callback又重載了其handleMessage方法,只要callback中的handleMessage返回爲false,表示不攔截信息,就會繼續分發消息,最終調用handler的handleMessage方法。handler主要要關注的核心原理就在此,其他細節部分就省略不講了,自己可以嘗試看源碼學習。
MessageQueue的源碼淺析
MessageQueue顧名思義,消息隊列,這是一個用單鏈表實現的隊列結構,作用就是存儲排隊進來的消息,主要的操作就是插入和移除,分別對應了enqueueMessage(Message msg, long when)和next()方法。下面貼出代碼:
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(TAG, 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;
}
實質上enqueueMessage就是一個單鏈表插入的操作。
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
// Next message is not ready. Set a timeout to wake up when it is ready.
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// Got a message.
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}
// If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
// Run the idle handlers.
// We only ever reach this code block during the first iteration.
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
// Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0;
// While calling an idle handler, a new message could have been delivered
// so go back and look again for a pending message without waiting.
nextPollTimeoutMillis = 0;
}
}
next方法是一個死循環,所以在調用next方法的時候,如果消息隊列中沒有消息的話就會堵塞,如果有消息進入就會移除該消息。
以上就是handler機制的整個流程解析,其實把核心內容拿出來其實還是很容易理解的。
UI線程中的Looper創建過程
大家在使用handler時,大多會直接在UI線程中直接new Handler(),並沒有傳入looper對象,爲什麼可以依然運行呢?其實上面就講到了,沒有傳入looper給handler的時候,構造方法會默認傳入當前線程中的looper對象給handler,那說明UI線程中默認給我們提供了一個looper對象,那這個looper對象是在哪裏創建的呢?其實就是在程序入口ActivityThread的main方法中,代碼如下:
public static void main(String[] args) {
//.....
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"));
// }
// End of event ActivityThreadMain.
//.....
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
可以看出來,在UI線程中,首先調用了Looper的prepareMainLooper方法,其實就是給UI線程關聯一個looper對象,並且記錄到Looper中的sMainLooper中了,然後調用了Looper.loop()方法,開始輪詢消息,這裏loop方法會堵塞線程,如果looper意外停止工作則會拋出異常。
在此Android消息機制淺析結束,希望能幫助到一些初學者,如果文中有誤請大家指出,謝謝~~