前言
文章是一篇學習筆記,主要記錄了閱讀Handler
、Message
、MessageQueue
、Looper
源碼(Android 8.1
)的一些心得體會,但并沒有涉及到更深層次源碼的分析,比如MessageQueue
的native
層的源碼。而AsyncTask
只是簡單介紹其API
。
概述
Android
的消息機制主要是指Handler
的運行機制,Handler
的運行需要底層的MessageQueue
和Looper
的支撐,常用于更新UI
。
MessageQueue
用于存儲消息(Message
),內部的存儲結構采用了鏈表,而不是隊列,它提供插入和刪除消息的功能,但不會處理消息。Looper
,MessageQueue
的管家,它的loop
方法會一直查看MessageQueue
是否存在消息(Message
)需要處理,如果有,就交給Handler
來處理。Handler
是消息(Message
)的發送者和處理者。
ThreadLocal
并不是線程,它的作用是可以在每個線程中存儲數據,這些數據對于其他線程是不可見的。每個線程中只會有一個Looper
,可以通過ThreadLocal
獲取到。
另外,線程默認是沒有Loope
r的,如果需要使用Handler
就必須為線程創建,比如在子線程。而主線程已經為我們創建好了,可以查閱ActivityThread
的main
方法,其中包括了MessageQueue
的初始化。
它們的數量級關系是:Handler(N):Looper(1):MessageQueue(1):Thread(1)
。
Handler
的主要作用是將一個任務切換到某個指定的線程中執行,這樣設計主要是為了解決Android
只能再主線程中更新UI
。
系統為什么不允許再子線程中訪問UI呢?這是因為Android
的UI
控件不是線程安全的,如果再多線程中并發訪問可能會導致UI
控件處于不可預期的狀態。
加鎖的缺點有兩個:首先加上鎖機制會讓UI
訪問的邏輯變得復雜;其次,鎖機制會降低UI
訪問的效率,因為鎖機制會阻塞某些線程的執行。
創建方式
在此只列出一種創建Handler
的方式,其他的創建方式可以自行百度,但是,一定要注意:如果在沒有Looper的線程里創建Handler會報錯的:
// 在主線程創建
public class MyHandler extends Handler {
@Override
public void handleMessage(Message msg) {
// 處理的代碼
}
}
MyHandler handler = new MyHandler();
// 子線程中執行
Message message = handler.obtainMessage();
message.what = 1;
message.obj = 123;
handler.sendMessage(message);
原理圖
源碼分析
先從ActivityThread
的main
方法看起,里面有兩句需要注意的:
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
// 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());
// 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"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
// 注意
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
大致就是說,主線程的Looper
已經準備好了。通常,我們創建Handler
會選擇繼承Handler
并重寫handleMessage
,因為父類的handleMessage
什么也不做。這里,我們關注其構造方法(無參的):
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;
}
假如我們再子線程中創建Handler
,但該線程并沒有Looper
,它會拋出異常:
Can't create handler inside thread that has not called Looper.prepare()
可見,Handler
的創建需要Looper
。那這個異常如何解決呢?舉例如下:
new Thread("new Thread") {
@Override
public void run() {
Looper.prepare();
Handler handler = new Handler();
Looper.loop();
}
}.start();
現在,我們回想一下,為什么在主線程可以直接創建Handler
?正如前面所講述的,當我們的App
啟動后,會調用ActivityThread
的main
的方法,而Looper
的prepareMainLooper
方法會被調用,也就是創建了Looper
,也就是滿足了Handler
的創建條件。其源碼如下:
/** Initialize the current thread as a looper.
* This gives you a chance to create handlers that then reference
* this looper, before actually starting the loop. Be sure to call
* {@link #loop()} after calling this method, and end it by calling
* {@link #quit()}.
*/
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
// 一個線程只能創建一個Looper
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
/**
* Initialize the current thread as a looper, marking it as an
* application's main looper. The main looper for your application
* is created by the Android environment, so you should never need
* to call this function yourself. See also: {@link #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();
}
}
不管是prepareMainLooper()
方法還是prepare()
方法,最后都是通過prepare(boolean quitAllowed)
來創建Looper
。我們先來看sThreadLocal
:
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
詳細的介紹可以參考這篇博客:Android的消息機制之ThreadLocal的工作原理。它的作用是保存當前線程的Looper
,且線程間互不干擾。
再看Looper
的構造方法,它完成了MessageQueue
的創建:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
總的來說,Android
的主線程就是ActivityThread
,主線程的入口方法為main
,再main
方法中系統會通過Looper.prepareMainLooper()
來創建主線程的Looper
以及MessageQueue
,并通過Looper.loop()
來開啟主線程的消息循環。
Message:消息載體
-
public int what
:標識 -
public int arg1
:保存int
數據 -
public int arg2
:保存int
數據 -
public Object obj
:保存任意數據 -
long when
:記錄應該被處理的時間值,換句話說就是延時時間 -
Handler target
:保存在主線程創建的Handler
對象引用 -
Runnable callback
:用來處理消息的回調器(一般不用,見原理圖二) -
Meaage next
:指向下一個Message
用來形成一個鏈表 -
private static Message sPool
:用來緩存處理過的Message
,以便復用 -
Message obtain()
:它利用了Message
中消息池(sPool
)
先從Message
的創建入手,官方更推薦使用obtain
來創建,而不是其構造方法。它的構造方法什么也不做,只是完成了Message
的創建,而obtain
可以復用Message
,且有很多多種重載。從內存、效率來看,obtain
更優。
/** Constructor (but the preferred way to get a Message is to call {@link #obtain() Message.obtain()}).
*/
public Message() {
}
/**
* Return a new Message instance from the global pool. Allows us to
* avoid allocating new objects in many cases.
*/
public static Message obtain() { // 最常見
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
可見,消息池采用了鏈表結構,確實是復用了Message
。
private static final Object sPoolSync = new Object();
private static Message sPool;
private static int sPoolSize = 0;
private static final int MAX_POOL_SIZE = 50;
下面是Message
的回收處理:
/**
* Return a Message instance to the global pool.
* <p>
* You MUST NOT touch the Message after calling this function because it has
* effectively been freed. It is an error to recycle a message that is currently
* enqueued or that is in the process of being delivered to a Handler.
* </p>
*/
public void recycle() {
if (isInUse()) {
if (gCheckRecycle) {
throw new IllegalStateException("This message cannot be recycled because it "
+ "is still in use.");
}
return;
}
recycleUnchecked();
}
/**
* Recycles a Message that may be in-use.
* Used internally by the MessageQueue and Looper when disposing of queued Messages.
*/
void recycleUnchecked() {
// Mark the message as in use while it remains in the recycled object pool.
// Clear out all other details.
flags = FLAG_IN_USE;
what = 0;
arg1 = 0;
arg2 = 0;
obj = null;
replyTo = null;
sendingUid = -1;
when = 0;
target = null;
callback = null;
data = null;
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
前面也提到,Message
可以自行處理,處理的邏輯交給一個Runnable
,也就是callback
,讀者可以自行查閱obtain
的其他重載,看看callback
賦值的情況,這里就不帖代碼了。
Handler:發送、處理、移除消息
前面已經分析過Message
的相關代碼,該小節將從發送Message
開始分析。其實,也可以通過Handler
來創建Message
,其內部也是調用Message.obtain
來創建Message
對象。
public final Message obtainMessage() {
return Message.obtain(this);
}
Handler
發送消息的方式有多種方式,這里選了一種最常見的,它的調用流程:
源碼如下:
public final boolean sendMessage(Message msg) {
return sendMessageDelayed(msg, 0); // 延時發送時間為0
}
// 延時發送
public final boolean sendMessageDelayed(Message msg, long delayMillis) {
// 容錯
if (delayMillis < 0) {
delayMillis = 0;
}
// 當前時間加上延時時間就是真正發送Message的時間
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
// Looper創建時,MessageQueue也創建了
// mQueue在Handler創建是就初始化了,代碼在前面已經貼過了
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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
// Message的成員變量,用來存儲Handler的對象引用
// 也就是記錄了由哪個Handler來處理這個Message
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
// 將Message插入到MessageQueue中,完成發送
return queue.enqueueMessage(msg, uptimeMillis);
}
另外,Handler
的post
方法也可以發送Message
,且該Message
將交給它自身來處理,當讀者看過dispatchMessage
方法后就明白了。
public final boolean post(Runnable r) {
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r; // 可以回憶下講述Message的那一節
return m;
}
下面是dispatchMessage
的源碼,它在Looper.loop
方法中被調用:
public void dispatchMessage(Message msg) {
// 如果Message.callback不為null,就交給它自身處理
if (msg.callback != null) {
handleCallback(msg);
} else {
// 如果mCallback不為null,交給該Handler處理
// mCallback是Handler內部的一個接口
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
// 最后是我們最常見的,重寫handleMessage
handleMessage(msg);
}
}
接著來看看Callback
,這個接口長啥樣:
public interface Callback {
/**
* @param msg A {@link android.os.Message Message} object
* @return True if no further handling is desired
*/
public boolean handleMessage(Message msg);
}
它也是在Handler
創建的時候初始化的,但調用的構造方法不一樣,導致最后的初始化不一樣。無參的構造方法會導致mCallback
為null
。
public Handler(Callback callback) {
this(callback, false);
}
最后來看看Handler
移除Message
的實現,但真正的實現交給了MessageQueue
。
public final void removeMessages(int what) {
mQueue.removeMessages(this, what, null);
}
public final void removeMessages(int what, Object object) {
mQueue.removeMessages(this, what, object);
}
MessageQueue:存儲消息的,以message的when排序優先級
Message
經Handler
發送后到達MessageQueue
,它采用鏈表的數據結構來存儲Message
。下面是其構造方法:
MessageQueue(boolean quitAllowed) {
mQuitAllowed = quitAllowed;
// 如果需要理解為什么loop方法不會卡住主線程,可以從這個本地方法開始入手
mPtr = nativeInit();
}
MessageQueue
中最主要的兩個方法是next
和enqueueMessage
。
next
方法也會阻塞(當消息隊列為空時或當前時間還沒到達Message
要處理的時間點時)但不會卡住主線程,它的工作就是根據需求從消息隊列中取一個Message
。注意,next
方法是一個無限循環的方法。
enqueueMessage
方法的工作就是將一個Message
插入到消息隊列且位置是合適的,因為它會根據Message
要處理的時間點進行排序,從它的插入操作也可以了解到MessageQueue
采用了鏈表。
由于next
方法和enqueueMessage
方法的源碼過長,下面只貼出enqueueMessage排序Message
的源碼:
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;
}
關于阻塞但不會卡住主線程的問題在下一小節會提到。
Looper:從MessageQueue中獲取當前需要處理的消息,并提交給Handler處理
關于Looper
在前面也講述了一部分,現在只剩下loop
方法了,很重要。在它的內部也開啟了一個無限循環。
在for
無限循環中,有一句表明了會阻塞:
Message msg = queue.next(); // might block
導致它阻塞的原因在MessageQueue.next
方法。當消息隊列退出或正在退出時,loop
方法會結束,也就是跳出無限循環。
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
在這個循環里還有一句需要注意的:
msg.target.dispatchMessage(msg);
意思時交給Handler
處理這個Message
。至此,整個流程就分析完了。
面試的時候可能會遇到:為什么loop
方法會阻塞主線程但不會卡住呢?以下的文章也許可以解答你心中的疑問:
異步任務
- 邏輯上:以多線程的方式完成的功能需求
- API上:指
AsyncTask
類
AsyncTask
- 在沒有
AsyncTask
之前,我們用Handler+Thread
就可以實現異步任務的功能需求 -
AsyncTask
是針對Handler
和Thread
的封裝,使用它編碼更加簡潔,更加高效 -
AsyncTask
封裝了ThreadPool
,比直接使用Thread
效率要高
相關API
-
AsyncTack<Params,Progress,Ressult>
-
Params
啟動任務執行的輸入參數,比如HTTP請求的URL -
Progress
后臺任務執行的百分比 -
Result
后臺執行任務最終返回的結果,比如String
-
-
execute(Params... params)
:啟動任務,開始任務的執行流程 -
onPreExcute()
:在分線程工作開始之前在UIThread中執行,一般用來顯示提示視圖5 -
doInBackground(Params... params)
:在workerThread
中執行,完成任務的主要工作,通常需要較長的時間 -
onPostExecute(Result result)
:在doInBackground
執行完后再UIThread
中執行,一般用來更新界面 -
publishProgress(Progress... values)
:在分線程中發布當前進度 -
onProgressUpdate(Progress... values)
:在主線程中更新進度
AsyncTask
在具體的使用過程中也是有一些條件限制的,主要有以下幾種(摘自《Android開發藝術探索》):
- 1、
AsyncTask
的類必須在主線程中加載,這就意味著第一次訪問AsyncTask
必須發生在主線程,當然這個過程在Android 4.1
及以上版本中已經被系統自動完成。在Android 5.0
的源碼中,可以查看ActivityThread
的main
方法,它會調用AsyncTask
的init
方法,這就滿足了AsyncTask
的類必須在主線程中進行加載這個條件了。 - 2、
AsyncTask
的對象必須在主線程中創建。 - 3、
execute
方法必須在UI線程調用。 - 4、不要再程序中直接調用
onPreExecute
、onPostExecute
、doInBackground
和onProgressUpdate
方法 - 5、一個
AsyncTask
對象只能執行一次,即只能調用一次execute
方法,否則會報運行時異常 - 6、在
Android 1.6
之前,AsyncTask
是串行執行任務的,Android 1.6
的時候AsyncTask
開始采用線程池里處理并行任務,但是從Android 3.0
開始,為了避免AsyncTask
所帶來的并發錯誤,AsyncTask又采用一個線程來串行執行任務。盡管如此,在Android 3.0
以及后續的版本中,我們仍然可以通過AsyncTask
的executeOnExecutor
方法來并行地執行任務。
總結
文章以Handler
的創建過程為參照,簡單介紹了Handler的原理和源碼。文章末尾對AsyncTask
進行了簡單的介紹。讀者有空可以讀一讀《Android開發藝術探索》的第10章和第11章。