注意:本篇文章是本人閱讀相關(guān)文章所寫下的總結(jié)逐沙,方便以后查閱,所有內(nèi)容非原創(chuàng),侵權(quán)刪洼畅。
本篇文章內(nèi)容來自于:
- Android開發(fā)藝術(shù)探索 任玉剛
- 深入源碼解析Android中的Handler,Message,MessageQueue,Looper
目錄
- 什么是Android消息機制
- Android消息機制概述
- Android消息機制分析
--3.1 ThreadLocal的工作原理
--3.2 MessageQueue的工作原理
--3.3 Looper的工作原理
--3.4 Handler的工作原理
1. Android消息機制成員介紹
Android的消息機制主要是指Handler的運行機制吩案。
Handler的運行需要底層的MessageQueue和Looper的支撐。
(1) Handler:
Handler是Android消息機制的上層接口帝簇,開發(fā)時只需和Handler交互即可徘郭。
Handler使用很簡單,可以輕松將一個任務切換到Handler所在的線程中去執(zhí)行丧肴。
為什么Androd要提供這個功能:
因為Android規(guī)定必須在主線程中訪問UI残揉,又不建議在主線程中進行耗時操作,否則會導致程序無法響應ANR芋浮。如果沒有Handler無法將子線程中訪問UI的工作切換到主線程中去進行抱环。
為什么不允許在子線程中訪問UI?
因為Android的UI并不是線程安全的纸巷,如果在多線程并發(fā)訪問可能會導致UI控件處于不可預期的狀態(tài)镇草。如果加上鎖機制會讓UI訪問的邏輯變復雜影響效率。最簡單高效的方法是采用單線程模型來處理UI操作瘤旨,開發(fā)者只需要通過Handler切換線程梯啤。
(2) MessageQueue消息隊列:
MessageQueue內(nèi)部存儲了一組消息,以隊列的形式對外提供給插入和刪除的工作存哲。內(nèi)部存儲結(jié)構(gòu)并不是真正的隊列因宇,而是采用單鏈表的數(shù)據(jù)結(jié)構(gòu)來存儲消息列表。
(3) Looper消息循環(huán):
它的出現(xiàn)是因為MessageQueue只是一個消息的存儲單元祟偷,不能處理消息察滑。Looper填補了這個功能。
Looper會以無限循環(huán)的形式去查找是否有新消息修肠,如果有的話處理消息贺辰,否則就一直等待。
線程是默認沒有Looper的氛赐,如果需要使用Handler則必須為線程創(chuàng)建Looper魂爪。(主線程ActivityThread創(chuàng)建時會初始化Looper,所以在主線程中默認可以使用Handler)
ThreadLocal:
Looper中還有一個ThreadLocal艰管。ThreadLocal不是線程滓侍,它的作用是可以在每個線程中存儲數(shù)據(jù)。
Handler創(chuàng)建的時候會采用當前線程的Looper來構(gòu)造消息循環(huán)系統(tǒng)牲芋。
那么Handler內(nèi)部如何獲取當前線程的Looper呢撩笆?
這就要使用ThreadLocal捺球。Looper類中使用ThreadLocal來存儲Looper對象。
那么為什么需要ThreadLocal來存儲Looper呢夕冲?
因為Looper的構(gòu)造函數(shù)是私有的氮兵,無法創(chuàng)建Looper進行賦值。只能將Looper的引用存在變量中歹鱼,而且每個線程都有自己對應的Looper泣栈,則需要用到ThreadLocal來存儲。因為ThreadLocal可以在不同的線程中互不干擾的存儲并提供數(shù)據(jù)弥姻,通過ThreadLocal可以輕松獲取每個線程的Looper南片。
2. Android消息機制概述
Android的消息機制主要是指Handler的運行機制以及Handler所附帶的MessageQueue和Looper的工作過程。
Handler創(chuàng)建時會采用當前線程的Looper來構(gòu)建內(nèi)部的消息循環(huán)系統(tǒng)庭敦。
如果當前線程沒有Looper疼进,則會報錯。因為線程是默認沒有Looper的秧廉,而主線程ActivityThread創(chuàng)建時會初始化Looper伞广,所以在主線程中默認可以使用Handler。
那么如何解決疼电?只需要為當前線程創(chuàng)建Looper即可嚼锄,或者在一個有Looper的線程中。
Handler創(chuàng)建完畢后澜沟,這個時候其內(nèi)部的Looper以及MessageQueue就可以和Handler一起切同工作了灾票。
發(fā)送消息時峡谊,可通過Handler的post方法發(fā)送一個Runnable茫虽,或者通過Handler的send方法發(fā)送一個Message。兩個方法都是通過send方法來完成既们。
當Handler的send方法被調(diào)用時濒析,它會調(diào)用MessagQueue的enqueueMessage方法將這個消息放入消息隊列,然后Looper發(fā)現(xiàn)有新消息到來時啥纸,就會處理這個消息号杏。
最終消息中的Runnable或者Handler的HandlerMessage方法會被調(diào)用。
當使用Handler來post/send消息時斯棒,僅僅是向消息隊列中插入了一條消息盾致,MessageQueue的next方法就會返回這條消息給Looper,Looper接受到消息后就開始處理荣暮,最終消息由Looper交由給Handler處理庭惜,即Handler的dispatchMessage方法會被調(diào)用,而Handler的dispatchMessage方法會進行判斷穗酥,如果發(fā)送過來的是一個runnbale护赊,則運行這個runnable任務惠遏;如果mCallback不為null,則運行mCallback的handlerMessage方法骏啰;最后運行自身的handleMessage方法
3. Android消息機制分析
3.1 ThreadLocal的工作原理
ThreadLocal是一個線程內(nèi)部的數(shù)據(jù)存儲類节吮,通過它可以在指定的線程中存儲數(shù)據(jù),數(shù)據(jù)存儲后判耕,只能在指定線程中可以獲取到存儲的數(shù)據(jù)透绩,對于其他線程來說則無法獲取到數(shù)據(jù)。
應用的場景:當某些數(shù)據(jù)是以線程為作用域并且不同線程具有不通過的數(shù)據(jù)副本的時候壁熄,就可以采用ThreadLocal渺贤。
應用:AcivityThread、Looper请毛、AMS
由于不同的線程擁有不同的Looper志鞍,則可以通過ThreadLocal來輕松實現(xiàn)Looper在線程中的讀取。
ThreadLocal的使用
public class MainActivity extends BaseActivity {
private ThreadLocal<Boolean> threadLocal = new ThreadLocal<Boolean>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
threadLocal.set(true);
Log.d("xl", "mainthread=" + threadLocal.get());
new Thread("thread1") {
@Override
public void run() {
threadLocal.set(false);
Log.d("xl", "thread1=" + threadLocal.get());
}
}.start();
new Thread("thread2") {
@Override
public void run() {
Log.d("xl", "thread2=" + threadLocal.get());
}
}.start();
}
}
D/xl: mainthread=true
D/xl: thread1=false
D/xl: thread2=null
為什么ThreadLocal可以在不同的線程中維護一套數(shù)據(jù)的副本并且彼此不干擾方仿?
因為不同線程訪問同一個ThreadLocal的get方法固棚,ThreadLocal內(nèi)部會從各自的線程中取出一個數(shù)組,然后再從數(shù)組中根據(jù)當前ThreadLocal的索引去查找出對應的value值仙蚜。很顯然此洲,不同線程中的數(shù)組是不同的。
ThreadLocal的內(nèi)部實現(xiàn)
ThreadLocal是一個泛型類委粉,定義為public class ThreadLocal<T>呜师,只要弄清楚ThreadLocal的get和set方法就可以明白他的工作原理。
(1)ThreadLocal的set方法
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t); //首先獲得當前線程的ThreadLocalMap數(shù)據(jù)贾节。
//Thread中有ThreadLocal.ThreadLocalMap threadLocals = null;用于存儲ThreadLocal對象汁汗,以Entry的形式
if (map != null)
map.set(this, value); //有的話設(shè)置
else
createMap(t, value); //沒有的話創(chuàng)建
}
(2)ThreadLocal的get方法
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);//首先獲得當前線程的ThreadLocalMap數(shù)據(jù)。
if (map != null) { //有的話則取
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue(); //沒有的話創(chuàng)建
}
3.2 MessageQueue的工作原理
MessageQueue主要包含兩個操作:插入和讀取栗涂。讀取操作本身會伴隨著刪除操作知牌。
插入的操作對應enqueueMessage方法,往消息隊列中插入一條消息斤程。
讀取的操作對應next方法角寸,從消息隊列中取出一條消息并將其從消息隊列中移除。
雖然MessageQueue叫消息隊列忿墅,但是內(nèi)部實現(xiàn)是用了一個單鏈表的數(shù)據(jù)結(jié)構(gòu)來維護消息列表扁藕,因為單鏈表在插入和刪除上比較有優(yōu)勢。
MessageQueue的內(nèi)部實現(xiàn)
(1)enqueueMessage
主要是單鏈表的插入操作疚脐。
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;
}
(2)next
next方法是一個無限循環(huán)的方法亿柑,如果消息隊列中沒有消息,那么next方法就會阻塞亮曹,當有消息到來的時候橄杨,next方法會返回這條消息并將其從單鏈表中刪除秘症。
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;
}
}
3.3 Looper的工作原理
Looper在消息機制中扮演消息循環(huán)的角色。它會不停從MessageQueue中查看是否有新消息式矫,如果有新消息就會立刻處理乡摹,否則就一直阻塞在那里。
Looper的構(gòu)造方法(private)
構(gòu)造方法中會創(chuàng)建一個MessageQueue消息隊列采转,然后將當前線程的對象保存起來聪廉。
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
Handler的工作需要Looper,沒有Looper的線程就會報錯故慈。
那么如何為一個線程創(chuàng)建Looper板熊?
通過Looper.prepare()可為當前線程創(chuàng)建一個Looper,接著通過Looper.loop()來開啟消息循環(huán)察绷。
new Thread("thread1") {
@Override
public void run() {
Looper.prepare();
//Looper. prepareMainLooper()這個方法是給主線程創(chuàng)建Looper使用的干签。
Handler handler = new Handler();
Looper.loop();
}
}.start();
如何得到當前線程的Looper對象?
getMainLooper()方法拆撼,可以在任何地方獲取到主線程的Looper容劳。
Looper.myLooper()拿到當前線程的Looper的引用
如何退出Looper
Looper提供了quit和quitSafely來退出一個Looper。
quit會直接退出Looper闸度。
quitSafely只是設(shè)定一個退出標記竭贩,會把消息隊列中的已有消息處理完畢后才安全的退出。
Looper退出后莺禁,通過Handler發(fā)送的消息會失效留量,此時Handler的send方法會返回false。
在子線程中哟冬,如果手動創(chuàng)建了Looper楼熄,那么在所有的事情完成后應該調(diào)用quit方法來終止消息循環(huán),否則這個子線程會一直處于等待的狀態(tài)柒傻。
Looper的內(nèi)部實現(xiàn)
(1)Looper.prepare()方法
會創(chuàng)建一個Looper對象孝赫,且用ThreadLocal保存這個對象较木,ThreadLocal內(nèi)部是使用當前線程中的一個數(shù)組來保存這個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));
}
(2)Looper.loop()方法
loop方法是一個死循環(huán),
唯一跳出循環(huán)的方式是MessageQueue的next方法返回了null伐债。
當Looper的quit方法被調(diào)用時预侯,Looper就會調(diào)用MessageQueue的quit或者quitSafely方法來通知消息隊列退出,此時next方法會返回null峰锁。
所以萎馅,除非Looper退出,否則loop方法會無限循環(huán)下去虹蒋。
loop方法會調(diào)用MessageQueue的next方法獲取新消息糜芳,而next是一個阻塞操作飒货,當沒有消息時,next方法會一直阻塞在那里峭竣,這也導致loop方法一直阻塞在那里塘辅。
當MessageQueue的next方法返回了新消息后,Looper就會處理這條消息:msg.target.dispatchMessage(msg);
msg.target是發(fā)送這條消息的Handler對象皆撩,這樣Handler發(fā)送的消息最終又交給該Handler的dispatchMessage方法來處理了扣墩。
而Handler的dispatchMessage方法是在創(chuàng)建Handler時所使用的Looper中執(zhí)行的,則成功切換線程了扛吞。
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
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
final long end;
try {
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (slowDispatchThresholdMs > 0) {
final long time = end - start;
if (time > slowDispatchThresholdMs) {
Slog.w(TAG, "Dispatch took " + time + "ms on "
+ Thread.currentThread().getName() + ", h=" +
msg.target + " cb=" + msg.callback + " msg=" + msg.what);
}
}
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();
}
}
3.4 Handler的工作原理
Handler的工作主要包括消息的發(fā)送和接受過程呻惕。
消息的發(fā)送可以通過post的一系列方法以及send的一系列方法來實現(xiàn),其實post也就是用了send方法
public final boolean dsendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
Handler發(fā)送消息僅僅是向消息隊列中插入了一條消息滥比,MessageQueue的next方法就會返回這條消息給Looper亚脆,Looper接受到消息后就開始處理,最終消息由Looper交由給Handler處理盲泛,即Handler的dispatchMessage方法會被調(diào)用型酥,這是Handler進入處理消息的階段。
public void dispatchMessage(Message msg) {
//1. 首先檢查Message的callback是否為null查乒,不為null則調(diào)用handleCallback
//Message的callback是一個runnable對象弥喉,實際上就是Handler的post方法所傳遞的runnable對象,handleCallback就是message.callback.run(),運行runnable玛迄。
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
//2.檢查mCallback是否為null由境,不為null則調(diào)用mCallback的handleMessage方法。即new Handler(callback)
if (mCallback.handleMessage(msg)) {
return;
}
}
//3.最后調(diào)用Handler的handleMessage方法來處理消息
handleMessage(msg);
}
}
為什么在沒有Looper的子線程創(chuàng)建Handler會拋異常
因為public Handler()實際就是調(diào)用了Handler(Looper looper)