1.概述
Android的消息機(jī)制主要是指Handler的運(yùn)行機(jī)制,Handler的運(yùn)行需要底層的MessageQueue和Looper的支撐。MessageQueue是消息隊(duì)列。他的內(nèi)存存儲(chǔ)了一組消息,以隊(duì)列的形式對(duì)外提供插入和刪除的工作。他的內(nèi)部存儲(chǔ)結(jié)構(gòu)并不是真正的隊(duì)列,而是采用單鏈表的數(shù)據(jù)結(jié)構(gòu)來(lái)存儲(chǔ)消息列表。Looper為消息循環(huán),由于MessageQueue只是一個(gè)消息的存儲(chǔ)單元,它不能去處理消息,而Looper就填補(bǔ)了這個(gè)功能,Looper會(huì)以無(wú)限循環(huán)的形式去查找是否有新的消息,如果有的話就處理消息,否則就一直等待,Looper還有一個(gè)特殊的概念,那就是ThreadLocal,ThreadLocal并不是線程,它的作用可以在每個(gè)線程中存儲(chǔ)數(shù)據(jù)。我們知道,Handler創(chuàng)建的時(shí)候會(huì)采用當(dāng)前線程的Looper來(lái)構(gòu)造消息循環(huán)系統(tǒng),那么Handler內(nèi)部如何獲取到當(dāng)前線程的Looper呢?這就要使用ThreadLocal了,ThreadLocal可以在不同的線程中互不干擾地存儲(chǔ)并提供數(shù)據(jù),通過(guò)ThreadLocal可以輕松獲取每個(gè)線程的Looper。當(dāng)然需要注意的是,線程是默認(rèn)沒(méi)有Looper的,如果需要使用Handler就必須為線程創(chuàng)建Looper。我們經(jīng)常提到的主線程,也就是UI線程,它就是ActivityThread,ActivityThread被創(chuàng)建時(shí)會(huì)初始化Looper,這也是在主線程中默認(rèn)可以使用Handler的原因。
2.ThreadLocal-線程局部變量
ThreadLocal是一個(gè)現(xiàn)場(chǎng)內(nèi)部的數(shù)據(jù)存儲(chǔ)類,通過(guò)它可以在指定的線程中存儲(chǔ)數(shù)據(jù),數(shù)據(jù)存儲(chǔ)以后,只有在指定線程中可以獲取到存儲(chǔ)的數(shù)據(jù)。對(duì)于Handler來(lái)說(shuō),它需要獲取當(dāng)前線程的Looper,很顯然Looper的作用域就是線程并且不同線程具有不同的Looper,這個(gè)時(shí)候通過(guò)ThreadLocal就可以輕松實(shí)現(xiàn)Looper在線程中的存儲(chǔ)。ThreadLocal是一個(gè)泛型類。
2.1存儲(chǔ)機(jī)制
在localValues內(nèi)部有一個(gè)數(shù)組;private Object[]table,ThreadLocal的值就存在這個(gè)table數(shù)組中,ThreadLocal的值在table數(shù)組中的存儲(chǔ)位置總是為ThreadLocal的reference字段所標(biāo)識(shí)的對(duì)象的下一個(gè)位置,比如ThreadLocal的reference對(duì)象在table數(shù)組中的索引為index,那么ThreadLocal的值在table數(shù)組中的索引就是index+1.最終ThreadLocal的值將會(huì)被存儲(chǔ)在table數(shù)組中:table[index+1]=value
2.put
void put(ThreadLocal<?> key, Object value) {
cleanUp();
// Keep track of first tombstone. That's where we want to go back
// and add an entry if necessary.
int firstTombstone = -1;
for (int index = key.hash & mask;; index = next(index)) {
Object k = table[index];
if (k == key.reference) {
// Replace existing entry.
table[index + 1] = value;
return;
}
if (k == null) {
if (firstTombstone == -1) {
// Fill in null slot.
table[index] = key.reference;
table[index + 1] = value;
size++;
return;
}
// Go back and replace first tombstone.
table[firstTombstone] = key.reference;
table[firstTombstone + 1] = value;
tombstones--;
size++;
return;
}
// Remember first tombstone.
if (firstTombstone == -1 && k == TOMBSTONE) {
firstTombstone = index;
}
}
}
//獲取當(dāng)前線程的數(shù)據(jù)
Values values(Thread current) {
return current.localValues;//當(dāng)前線程存儲(chǔ)的數(shù)組
}
//初始化當(dāng)前線程的數(shù)據(jù)
Values initializeValues(Thread current) {
return current.localValues = new Values();
}```
2.3 set
public void set(T value) {
Thread currentThread = Thread.currentThread();//獲取當(dāng)前的線程
Values values = values(currentThread);//
if (values == null) {
values = initializeValues(currentThread);
}
values.put(this, value);
}
3)get
[java] view plain copy 在CODE上查看代碼片派生到我的代碼片
public T get() {
// Optimized for the fast path.
Thread currentThread = Thread.currentThread();
Values values = values(currentThread);
if (values != null) {
Object[] table = values.table;
int index = hash & values.mask;
if (this.reference == table[index]) {
return (T) table[index + 1];
}
} else {
values = initializeValues(currentThread);
}
return (T) values.getAfterMiss(this);
}```
從ThreadLocal的set和get方法可以看出,他們所操作的對(duì)象都是當(dāng)前線程localValues對(duì)象的table數(shù)組,因此在不同線程中訪問(wèn)同一個(gè)ThreadLocal的set和get方法,他們對(duì)ThreadLocal所做的讀寫操作僅限于各自線程的內(nèi)部。
3.MessageQueue-消息隊(duì)列
消息隊(duì)列在Android中指的是MessageQueue,MessageQueue主要包含兩個(gè)操作:插入和讀取。讀取操作本身會(huì)伴隨著刪除操作,插入和讀取對(duì)應(yīng)的方法分別為enqueueMessage和next,其中enqueueMessage的作用是往消息隊(duì)列中 插入一條消息,而next的作用是從消息隊(duì)列中取出一條消息并將其從消息隊(duì)列中移除。MessageQueue內(nèi)部是通過(guò)一個(gè)單鏈表的數(shù)據(jù)結(jié)構(gòu)來(lái)維護(hù)消息列表,當(dāng)鏈表在插入和刪除上比較有優(yōu)勢(shì)。
3.1enqueueMessage插入消息
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;
}```
**3.2 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;
}
}```
next方法是一個(gè)無(wú)限循環(huán)的方法,如果消息隊(duì)列中沒(méi)有消息,那么next方法會(huì)一直堵塞在這里。當(dāng)有新消息到來(lái)時(shí),next方法會(huì)返回這條消息并將其從鏈表中移除
4.Message- 消息實(shí)體
需要注意Message的一些成員變量Handler target; //對(duì)應(yīng)的HandlerRunnable callback; //對(duì)應(yīng)的回調(diào)Message next;//單鏈表引用
5.Looper-消息循環(huán)
Looper在Android的消息機(jī)制中扮演著消息循環(huán)的角色,具體來(lái)說(shuō)就是他會(huì)不停地從MessageQueue中查看是否有新消息,如果有新消息就會(huì)立刻處理,否則就一直阻塞在哪里。
Looper處理prepare方法外,還提供了prepareMainLooper方法,這個(gè)方法主要是給主線程也就是ActivityThread創(chuàng)建Looper使用的,其本質(zhì)也是通過(guò)prepare方法來(lái)實(shí)現(xiàn)。由于主線程的Looper比較特殊,所以Looper提供一個(gè)getMainLooper方法,通過(guò)它可以在任何地方獲取主線程的Looper。Looper也是可以退出的,Looper提供勒quit和quitSafely來(lái)退出一個(gè)Looper。quit會(huì)直接退出Looper,而quitSafely只是設(shè)定一個(gè)退出標(biāo)記,然后把消息隊(duì)列的已有消息處理完畢后才安全退出。Looper退出后,通過(guò)Handler發(fā)送的消息會(huì)失敗,這個(gè)時(shí)候Handler的send方法會(huì)返回false。在子線程,如果手動(dòng)為其創(chuàng)建了Looper,那么所有的事情完成以后應(yīng)該調(diào)用quit方法來(lái)終止消息循環(huán),否則這個(gè)子線程就會(huì)一直處理等待的狀態(tài)。
Looper最重要的一個(gè)方法是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();
}
}```
loop方法是一個(gè)死循環(huán),唯一跳出循環(huán)的方式是MessageQueue的next方法返回了null。當(dāng)Looper的quit方法被調(diào)用時(shí),Looper就會(huì)調(diào)用MessageQueue的quit或者quitSafely方法來(lái)通知消息隊(duì)列退出,當(dāng)消息隊(duì)列被標(biāo)記為退出狀態(tài)時(shí),他的next方法會(huì)返回null。loop方法會(huì)調(diào)用MessageQueue的next方法來(lái)獲取新消息,而next是一個(gè)阻塞操作,當(dāng)沒(méi)有消息時(shí),next方法會(huì)一直阻塞在哪里,這也導(dǎo)致loop方法一直阻塞在哪里。若有新消息,Looper會(huì)調(diào)用msg。target。dispatchMessage(msg),這里的msg.target是發(fā)送這條消息的Handler對(duì)象,這樣Handler發(fā)送的消息最終又交給它的dispatchMessage方法來(lái)處理了。但是這里不同的是,Handler的dispatchMessage方法是在創(chuàng)建Handler時(shí)所使用的Looper中執(zhí)行,這樣就成功將代碼邏輯切換到指定的線程中去執(zhí)行了。
**6.Handle-消息處理**
Handler的工作主要包含消息的發(fā)送和接收過(guò)程。消息的發(fā)送可以通過(guò)post的一系列方法以及send的一系列方法來(lái)實(shí)現(xiàn),post的一系列方法最終是通過(guò)send的一系列方法來(lái)實(shí)現(xiàn)的。

**6.1 創(chuàng)建**
使用Handler必須要有Looper,不然會(huì)報(bào)異常
public Handler(Callback callback) {
this(callback, false);
}
/**
- Use the provided {@link Looper} instead of the default one.
- @param looper The looper, must not be null.
*/
public Handler(Looper looper) {
this(looper, 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;
}```
6.2 發(fā)送
Handler發(fā)送消息的過(guò)程僅僅是向消息隊(duì)列中插入了一條消息
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);
}```
**6.3 接收**
當(dāng)消息隊(duì)列插入消息后,MessageQueue的next方法就會(huì)返回這條消息給Looper,Looper收到消息后就開(kāi)始處理了,最終消息由Looper交由Handler處理
public interface Callback {
public boolean handleMessage(Message msg);
}
/**
- Subclasses must implement this to receive messages.
*/
public void handleMessage(Message msg) {
}
/**
- Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}```
7.主線程的消息循環(huán)
Android的主線程就是ActivityThread,主線程的入口方法為main,在main方法中系統(tǒng)會(huì)通過(guò)Looper.prepareMainLooper()來(lái)創(chuàng)建主線程的Looper以及MessageQueue,并通過(guò)Looper。loop()來(lái)開(kāi)啟主線程的消息循環(huán)
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
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());
AndroidKeyStoreProvider.install();
// 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");
}```
主線程的消息循環(huán)開(kāi)始以后,ActivityThread還需要一個(gè)Handler來(lái)和消息隊(duì)列進(jìn)行交互,這個(gè)Handler就是ActivityThread.H,他的內(nèi)部定義了一組消息類型,主要管理Activity的生命周期及四大組件的啟動(dòng)和停止過(guò)程等
private class H extends Handler {
public static final int LAUNCH_ACTIVITY = 100;
public static final int PAUSE_ACTIVITY = 101;
public static final int PAUSE_ACTIVITY_FINISHING= 102;
public static final int STOP_ACTIVITY_SHOW = 103;
public static final int STOP_ACTIVITY_HIDE = 104;
public static final int SHOW_WINDOW = 105;
public static final int HIDE_WINDOW = 106;
public static final int RESUME_ACTIVITY = 107;
public static final int SEND_RESULT = 108;
public static final int DESTROY_ACTIVITY = 109;
public static final int BIND_APPLICATION = 110;
public static final int EXIT_APPLICATION = 111;
public static final int NEW_INTENT = 112;
public static final int RECEIVER = 113;
public static final int CREATE_SERVICE = 114;
public static final int SERVICE_ARGS = 115;
public static final int STOP_SERVICE = 116;
public static final int CONFIGURATION_CHANGED = 118;
public static final int CLEAN_UP_CONTEXT = 119;
public static final int GC_WHEN_IDLE = 120;
public static final int BIND_SERVICE = 121;
public static final int UNBIND_SERVICE = 122;
public static final int DUMP_SERVICE = 123;
public static final int LOW_MEMORY = 124;
public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
public static final int RELAUNCH_ACTIVITY = 126;
public static final int PROFILER_CONTROL = 127;
public static final int CREATE_BACKUP_AGENT = 128;
public static final int DESTROY_BACKUP_AGENT = 129;
public static final int SUICIDE = 130;
public static final int REMOVE_PROVIDER = 131;
public static final int ENABLE_JIT = 132;
public static final int DISPATCH_PACKAGE_BROADCAST = 133;
public static final int SCHEDULE_CRASH = 134;
public static final int DUMP_HEAP = 135;
public static final int DUMP_ACTIVITY = 136;
public static final int SLEEPING = 137;
public static final int SET_CORE_SETTINGS = 138;
public static final int UPDATE_PACKAGE_COMPATIBILITY_INFO = 139;
public static final int TRIM_MEMORY = 140;
public static final int DUMP_PROVIDER = 141;
public static final int UNSTABLE_PROVIDER_DIED = 142;
public static final int REQUEST_ASSIST_CONTEXT_EXTRAS = 143;
public static final int TRANSLUCENT_CONVERSION_COMPLETE = 144;
public static final int INSTALL_PROVIDER = 145;
public static final int ON_NEW_ACTIVITY_OPTIONS = 146;
public static final int CANCEL_VISIBLE_BEHIND = 147;
public static final int BACKGROUND_VISIBLE_BEHIND_CHANGED = 148;
public static final int ENTER_ANIMATION_COMPLETE = 149;
}```
另外經(jīng)常使用的runOnUIThread(Runable action),通過(guò)源碼分析也是使用了mHandler,而mHandler的Looper也是使用的UI線程的mainLooper。
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}```
出處:http://huangjunbin.com/page/3/