源碼基于安卓8.0分析結(jié)果
關(guān)鍵類ActivityThread、Handler、Looper、Message、MessageQueue
- ActivityThread中的流程:應(yīng)用程序入口是在ActivityThread的main方法中,程序啟動(dòng),底層去調(diào)用C/C++去調(diào)用main方法
- ActivityThread中的main的方法
/*
將當(dāng)前線程初始化為一個(gè)活套,將其標(biāo)記為
*應(yīng)用程序的主要活套。應(yīng)用程序的主要套接字
*是由Android環(huán)境創(chuàng)建的,所以您永遠(yuǎn)不需要
*自己調(diào)用這個(gè)函數(shù)
*/
public static void main(String[] args) {
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) { sMainThreadHandler = thread.getHandler(); }
//if(false){}之類的語句,這種寫法是方便調(diào)試的,通過一個(gè)標(biāo)志就可以控制某些代碼是否執(zhí)行,比如說是否輸出一些系統(tǒng)的Log
if (false) { myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread")); }
Looper.loop();
}
- Looper.prepareMainLooper();方法
////Looper的prepare方法,并且關(guān)聯(lián)到主線程
public static void prepareMainLooper() {
//Only one Looper may be created per thread"
// false意思不允許我們程序員退出(面向我們開發(fā)者),因?yàn)檫@是在主線程里面
// TODO: 2018/5/17
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
//把Looper設(shè)置為主線程的Looper
sMainLooper = myLooper();
}
}
- 關(guān)于prepare(false)方法: Only one Looper may be created per thread 也就是說,一個(gè)線程只有一個(gè)Looper對象,要不然會(huì)拋出異常
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));
}
- 關(guān)于ThreadLocal的set方法,可以找到ThreadLocal的構(gòu)造函數(shù),底層的實(shí)現(xiàn)是一個(gè)Entry的數(shù)組.
ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
//1、ThreadLocal的set方法
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
//2、ThreadLocal的createMap方法
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
ThreadLocalMap的構(gòu)造函數(shù)里面有一個(gè)長度為16的Entry的數(shù)組,當(dāng)然這個(gè)機(jī)制和HashMap差不多,也有擴(kuò)容機(jī)制,就是當(dāng)容器裝不下了,在此的基礎(chǔ)上增加一倍的長度,同時(shí)把原來的數(shù)據(jù)copy到新的Entry數(shù)組中
//3、ThreadLocal的構(gòu)造函數(shù)
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
table = new Entry[INITIAL_CAPACITY];
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
table[i] = new Entry(firstKey, firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}
ThreadLocalMap的(擴(kuò)容機(jī)制)Double the capacity of the table.
/**
* Double the capacity of the table.
*/
private void resize() {
Entry[] oldTab = table;
int oldLen = oldTab.length;
int newLen = oldLen * 2;
Entry[] newTab = new Entry[newLen];
int count = 0;
for (int j = 0; j < oldLen; ++j) {
Entry e = oldTab[j];
if (e != null) {
ThreadLocal<?> k = e.get();
if (k == null) {
e.value = null; // Help the GC
} else {
int h = k.threadLocalHashCode & (newLen - 1);
while (newTab[h] != null)
h = nextIndex(h, newLen);
newTab[h] = e;
count++;
}
}
}
setThreshold(newLen);
size = count;
table = newTab;
}
- 同時(shí)關(guān)注Entry的類,可以發(fā)現(xiàn)這是WeakReference的子類,關(guān)系到了弱引用:弱引用是比軟引用更弱的一種的引用的類型,只有弱引用指向的對象的生命周期更短,當(dāng)垃圾回收器掃描到只有具有弱引用的對象的時(shí)候,不敢當(dāng)前空間是否不足,都會(huì)對弱引用對象進(jìn)行回收,不太明白的可以看我另外一篇文章 安卓代碼、圖片、布局、網(wǎng)絡(luò)和電量優(yōu)化
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
為什么我要提起它???可能我理解的不太準(zhǔn)確,肯定不太準(zhǔn)確,在我現(xiàn)在工作中,維護(hù)和開發(fā)一個(gè)硬件的應(yīng)用早餐機(jī)(用戶通過App預(yù)定早餐,第二天早上去機(jī)器上取早餐),就像蜂巢的快遞柜一樣,取早餐的機(jī)器,在深圳工作的大佬,可能也許看見過我們的機(jī)器,PLC、安卓、物聯(lián)網(wǎng)這篇文章有詳細(xì)的介紹。在測試過程中,由于App常駐在前臺(tái),有幾率導(dǎo)致App直接掛掉,通過日志發(fā)現(xiàn)是內(nèi)存不足,直接kill了這個(gè)App,我想這里可能就是這個(gè)原因,這個(gè)一個(gè)弱應(yīng)用,只要虛擬機(jī)掃描導(dǎo)致這里了,我不管你了,我直接把你回收掉。僅僅是個(gè)人的理解,同時(shí)我們安卓的開發(fā)板也不太穩(wěn)定,如果在這一點(diǎn)有見解的大佬,歡迎討論,謝謝了
- Looper.loop();根據(jù)我們的常識(shí)知道,如果程序沒有死循環(huán)的話,執(zhí)行完main函數(shù)(比如構(gòu)建視圖等等代碼)以后就會(huì)立馬退出了。之所以我們的APP能夠一直運(yùn)行著,就是因?yàn)長ooper.loop()里面是一個(gè)死循環(huán)
- 1、 首先拿到Looper對象(me),如果當(dāng)前的線程沒有Looper,那么就會(huì)拋出異常, // TODO: 2018/5/17 在子線程中創(chuàng)建handler的話,需要looper也要準(zhǔn)備好 ,要不然會(huì)報(bào)錯(cuò)。這就是為什么在子線程里面創(chuàng)建Handler如果不手動(dòng)創(chuàng)建和啟動(dòng)Looper會(huì)報(bào)錯(cuò)的原因
- 這個(gè)Looper對象就是通過sThreadLocal.get();細(xì)心的話可以發(fā)現(xiàn)前面已經(jīng)sThreadLocal.set()
- 1、 首先拿到Looper對象(me),如果當(dāng)前的線程沒有Looper,那么就會(huì)拋出異常, // TODO: 2018/5/17 在子線程中創(chuàng)建handler的話,需要looper也要準(zhǔn)備好 ,要不然會(huì)報(bào)錯(cuò)。這就是為什么在子線程里面創(chuàng)建Handler如果不手動(dòng)創(chuàng)建和啟動(dòng)Looper會(huì)報(bào)錯(cuò)的原因
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
- 2、然后拿到Looper的成員變量MessageQueue,在MessageQueue里面不斷地去取消息,關(guān)于MessageQueue的next方法如下:如果這個(gè)msg為null的,這個(gè)結(jié)束掉這個(gè)
- 3、msg.target.dispatchMessage(msg)就是處理消息,緊接著在loop方法的最后調(diào)用了msg.recycleUnchecked()這就是回收了Message。
- 4、我們平時(shí)寫Handler的時(shí)候不需要我們手動(dòng)回收,因?yàn)楣雀璧墓こ處熞呀?jīng)有考慮到這方面的問題了。消息是在Handler分發(fā)處理之后就會(huì)被自動(dòng)回收的:
public static void loop() {
final Looper me = myLooper();
if (me == null) {
// TODO: 2018/5/17 在子線程中創(chuàng)建handler的話,需要looper也要準(zhǔn)備好 ,要不然會(huì)報(bào)錯(cuò)
// 1、 首先拿到Looper對象(me),如果當(dāng)前的線程沒有Looper,那么就會(huì)拋出異常,
// 這就是為什么在子線程里面創(chuàng)建Handler如果不手動(dòng)創(chuàng)建和啟動(dòng)Looper會(huì)報(bào)錯(cuò)的原因
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 (; ; ) {
// TODO: 2018/5/17 Message
// 2、然后拿到Looper的成員變量MessageQueue,在MessageQueue里面不斷地去取消息,關(guān)于MessageQueue的next方法如下:
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;
// msg.target.dispatchMessage(msg)就是處理消息,緊接著在loop方法的最后調(diào)用了msg.recycleUnchecked()這就是回收了Message。
// TODO: 2018/5/17
處理消息
try {
處理消息
// TODO: 2018/5/17 msg中的target 就是handler的本體的對象 ,直接去handler中發(fā)送這個(gè)對象
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);
}
// TODO: 2018/5/17
我們平時(shí)寫Handler的時(shí)候不需要我們手動(dòng)回收,因?yàn)楣雀璧墓こ處熞呀?jīng)有考慮到這方面的問題了。消息是在Handler分發(fā)處理之后就會(huì)被自動(dòng)回收的:
msg.recycleUnchecked();
}
}
- 關(guān)于Message類
1、對象是實(shí)現(xiàn)了Parcelable接口的,因?yàn)镸essage消息可能需要跨進(jìn)程通信,這時(shí)候就需要進(jìn)程序列化以及反序列化操作了。
public final class Message implements Parcelable Message
2、obtain()得到Message對象,其中的設(shè)計(jì)模式享元模式:我見過最好的Demo,理解:采用一個(gè)共享類避免大量擁有相同的內(nèi)容的“小類的開銷”
享元模式德優(yōu)缺點(diǎn):優(yōu)點(diǎn)在于大幅度的降低內(nèi)存中對象的數(shù)量,但是,它做到這一點(diǎn)代價(jià)優(yōu)點(diǎn)高,享元模式使得系統(tǒng)更加復(fù)雜為了使對象可以共享,需要將一些狀態(tài)外部化,這使得一些程序邏輯更加的復(fù)雜享元模式將享元對象的狀態(tài)外部化,而讀取外部狀態(tài)使得運(yùn)行的時(shí)間稍微變長,更多的Demo可以看這篇文章二十三種設(shè)計(jì)模式
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();
}
3、消息的回收機(jī)制方法一:這個(gè)方法調(diào)用的時(shí)機(jī)是在MessageQueueen中。MessageQueueen.queueMessage(Message msg, long when)
public void recycle() {
if (isInUse()) {
if (gCheckRecycle) {
throw new IllegalStateException("This message cannot be recycled because it "
+ "is still in use.");
}
return;
}
recycleUnchecked();
}
4、消息的回收機(jī)制方法二:調(diào)用的地方是在 Looper.loop();谷歌的工程師幫我們調(diào)用,所以我們在開發(fā)過程中,沒有去調(diào)用這個(gè)消息回收,哈哈,向谷歌致敬,同時(shí)這個(gè)方法也會(huì)在recycle中調(diào)用。
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++;
}
}
}
- 關(guān)于MessageQueue類
1、 Message next() 方法:看到消息的取出用到了一些native方法,這樣做是為了獲得更高的效率,消息的去取出并不是直接就從隊(duì)列的頭部取出的,而是根據(jù)了消息的when時(shí)間參數(shù)有關(guān)的,因?yàn)槲覀兛梢园l(fā)送延時(shí)消息、也可以發(fā)送一個(gè)指定時(shí)間點(diǎn)的消息- 1、for循環(huán)的使用native 方法
- 2、根據(jù)時(shí)間戳獲取消息
Message next() {
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
//防止被反射修改了這個(gè)標(biāo)記,直接寫出for循環(huán)
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
//native 方法
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
//拿到當(dāng)前的時(shí)間戳
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
//判斷頭指針的Target(Handler是否為空(因?yàn)轭^指針只是一個(gè)指針的作用))
if (msg != null && msg.target == null) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
//遍歷下一條Message
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
//還沒有到執(zhí)行的時(shí)間
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
//到了執(zhí)行時(shí)間,直接返回
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;
}
}
2、 boolean enqueueMessage(Message msg, long when)方法中調(diào)用了 msg.recycle();
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);
// TODO: 2018/5/21 在這里調(diào)用的 釋放消息
msg.recycle();
return false;
}
}
2、quit的方法: Looper.myLooper().quit();調(diào)用的就是下面的方法 只不過safe==false
void quit(boolean safe) {
if (!mQuitAllowed) {
throw new IllegalStateException("Main thread not allowed to quit.");
}
synchronized (this) {
if (mQuitting) {
return;
}
//置位正在退出的標(biāo)志
mQuitting = true;
//清空所有消息
if (safe) {
//安全的(系統(tǒng)的),未來未處理的消息都移除
removeAllFutureMessagesLocked();
} else {
//如果是不安全的,例如我們自己定義的消息,就一次性全部移除掉
removeAllMessagesLocked();
}
// We can assume mPtr != 0 because mQuitting was previously false.
nativeWake(mPtr);
}
}
- 安全的(系統(tǒng)的),未來未處理的消息都移除
private void removeAllFutureMessagesLocked() {
final long now = SystemClock.uptimeMillis();
Message p = mMessages;
if (p != null) {
if (p.when > now) {
//如果所有消息都處理完了,就一次性把全部消息移除掉
removeAllMessagesLocked();
} else {
//否則就通過for循環(huán)拿到還沒有把還沒有執(zhí)行的Message,利用do循環(huán)
//把這些未處理的消息通過recycleUnchecked方法回收,放回到消息池里面
Message n;
for (;;) {
n = p.next;
if (n == null) {
return;
}
if (n.when > now) {
break;
}
p = n;
}
p.next = null;
do {
p = n;
n = p.next;
p.recycleUnchecked();
} while (n != null);
}
}
}
- 如果是不安全的,例如我們自己定義的消息,就一次性全部移除掉
private void removeAllMessagesLocked() {
Message p = mMessages;
while (p != null) {
Message n = p.next;
p.recycleUnchecked();
p = n;
}
mMessages = null;
}
- 關(guān)于Handler發(fā)送消息流程
- 通過一個(gè)Handler發(fā)送一個(gè)延遲5s的消息,
innerHandler.postDelayed(new Runnable() {
@Override
public void run() {
//todo
}
},5000);
- 調(diào)用到Handler中的postDelayed方法
public final boolean postDelayed(Runnable r, long delayMillis) {
return sendMessageDelayed(getPostMessage(r), delayMillis);
}
- getPostMessage(r)方法:通過obtain得到一個(gè)Message的對象
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
- sendMessageDelayed(getPostMessage(r), delayMillis):這里的delayMillis的時(shí)間小于0的話,也會(huì)為0
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
- 關(guān)于sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);SystemClock.uptimeMillis() 系統(tǒng)的時(shí)間返回為milliseconds==毫秒,在這個(gè)方法就可以看出,MessageQueue不可獲取
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);
}
- 那么關(guān)于mQueue何時(shí)初始化的呢,請看代碼分析
1、我們平時(shí)都是new Handler(),開始使用的
public Handler() {
this(null, false);
}
直接調(diào)用了這里的方法,同時(shí)這個(gè)構(gòu)造方法是Hide了的,在外界調(diào)用不掉,為啥把它Handler,我還不太懂,反正可以注意到 mQueue = mLooper.mQueue; 原MessageQueue是在Looper中初始化的,ok,往下走
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的構(gòu)造方法,可以看到MessageQueue初始化
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
那么Looper又在哪里初始化的呢:通過代碼可以發(fā)現(xiàn)prepare()方法中初始化,通過前面的代碼的分析又在ActivityThread中的main方法,通過調(diào)用Looper.prepareMainLooper()方法
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));
- 關(guān)于enqueueMessage(queue, msg, uptimeMillis);其實(shí)也就是調(diào)用到MessageQueue.enqueueMessage方法
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
- 關(guān)于MessageQueue.enqueueMessage():對msg一些的賦值,同時(shí)呢,也調(diào)用了,本地方法,這樣性能很高,如果真的需要看懂源碼的流程,一定打個(gè)斷點(diǎn),一步步的走下去,就可以看到很良好的結(jié)果。
boolean enqueueMessage(Message msg, long when) {
//1、目標(biāo)為空,那么拋出異常
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
//2、如果這個(gè)消息已經(jīng)被使用了的話,也拋出異常
// /*package*/ boolean isInUse() {
// return ((flags & FLAG_IN_USE) == FLAG_IN_USE);
// }
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
synchronized (this) {
//3、如果是退出了,就是App退出了,退出了的標(biāo)記
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w(TAG, e.getMessage(), e);
// TODO: 2018/5/21 在這里調(diào)用的 釋放消息
msg.recycle();
return false;
}
//4、標(biāo)記它正在使用中,
msg.markInUse();
//5、當(dāng)前的時(shí)間
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
// 6、新的頭,如果阻塞,喚醒事件隊(duì)列。
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.
//插入隊(duì)列中間。通常我們不必醒來
//增加事件隊(duì)列,除非隊(duì)列頭上有障礙物。
//消息是隊(duì)列中最早的異步消息。
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
//7、for保持消息的不斷的移動(dòng)
for (;;) {
//前一個(gè)消息,如果走到這里,那么這個(gè)p不會(huì)為null
prev = p;
//把這個(gè)消息下一個(gè)賦值給P,如果下個(gè)值為null的話,就直接break
p = p.next;
if (p == null || when < p.when) {
break;
}
//8、需要醒來,同時(shí)消息是異步的
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.next() 方法,就不斷的取出Message,做相應(yīng)的動(dòng)作,
- 如何分發(fā)消息呢?還得看Looper.loop()方法
public static void loop() {
//前面省略了方法
for (;;) {
//這樣MessageQueue.next() 方法,就不斷的取出Message
Message msg = queue.next(); // might block
msg.target.dispatchMessage(msg);
//省略了方法
}
Handle system messages here. 這樣就把消息分發(fā)下去了!
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
// TODO: 2018/5/17
//這個(gè)callback呢,即使他媽的一個(gè)線程
if (msg.callback != null) {
handleCallback(msg);
} else {
//兩個(gè)都沒有的話,就去把這個(gè)消息發(fā)送到handleMessage中去
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
- 說明幾點(diǎn)
- 1、 安卓的程序的入口的函數(shù)是ActivityThread.main(),反正每個(gè)App啟動(dòng)都會(huì)經(jīng)過它,具體為啥,我也不清楚
- 2、首先初始化的是Looper,Looper的構(gòu)造方法初始化MessageQueue,然后ThreadLocal.set()方法保存,原來是ThreadLocal里面有個(gè)ThreadLocalMap容器,底層的原理和HashMap差不多,有個(gè)初始長度為16的Entry數(shù)組,也有擴(kuò)容機(jī)制
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
- 3、由于Entry繼承的是一個(gè)WeakReference類,那么是弱應(yīng)用的子類,當(dāng)內(nèi)存不足,掃描到這里,就不被回收,導(dǎo)致App被kill,系統(tǒng)回到Launch,(當(dāng)然這僅僅是我的假設(shè),不正確),安卓系統(tǒng)不會(huì)把內(nèi)置的軟件給kill,不如說時(shí)間,主題,launch,如果要?dú)ⅲ椭荒軞㈤_發(fā)者的應(yīng)用了
- 4、在ActivityThread.main()后,有個(gè)Looper.loop(),可以得出在:子線程中創(chuàng)建handler的話,需要looper也要準(zhǔn)備好 ,要不然會(huì)報(bào)錯(cuò)。這就是為什么在子線程里面創(chuàng)建Handler如果不手動(dòng)創(chuàng)建和啟動(dòng)Looper會(huì)報(bào)錯(cuò)的原因
final Looper me = myLooper();
if (me == null) {
// TODO: 2018/5/17 在子線程中創(chuàng)建handler的話,需要looper也要準(zhǔn)備好 ,要不然會(huì)報(bào)錯(cuò)
// 1、 首先拿到Looper對象(me),如果當(dāng)前的線程沒有Looper,那么就會(huì)拋出異常,
// 這就是為什么在子線程里面創(chuàng)建Handler如果不手動(dòng)創(chuàng)建和啟動(dòng)Looper會(huì)報(bào)錯(cuò)的原因
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
- 5、程序能夠不斷的運(yùn)行著的原因,是Looper.loop中是一個(gè)死循環(huán),當(dāng)消息隊(duì)列沒有消息了,程序就會(huì)退出
- 6、消息的分發(fā)msg.target.dispatchMessage(msg); msg.target其實(shí)就是Handler對象,可以看到分發(fā)消息的最終結(jié)果,也可以從這里表明Message的使用有好多種可能。
public void dispatchMessage(Message msg) {
// TODO: 2018/5/17
//這個(gè)callback呢,即使他媽的一個(gè)線程
if (msg.callback != null) {
handleCallback(msg);
} else {
//兩個(gè)都沒有的話,就去把這個(gè)消息發(fā)送到handleMessage中去
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
- 7、Message中,目前是我見過享元模式最好的實(shí)現(xiàn)的方式。更多的Demo可以看這篇文章二十三種設(shè)計(jì)模式
- 8、為啥沒有消息回收,因?yàn)楣雀韫こ處煟呀?jīng)幫我們做了。致敬谷歌
- 9、MessageQueue.next(),使用的是本地方法,因?yàn)樾实膯栴},需要更高的效率,所以需要本地,原理說實(shí)話,我想扯一下,看了好多文檔,發(fā)現(xiàn)我自己也不明白,反正不是我們常規(guī)的隊(duì)列中取出,而是根據(jù)when時(shí)間參數(shù)有關(guān)。
- 10、Handler,發(fā)送消息的姿勢很多(注意是姿勢),需要不斷的嘗試,在集合源碼,就可以發(fā)現(xiàn)新大陸
- 11、后續(xù)會(huì)講到View的繪制啊
RESUME_ACTIVITY
activity獲取焦點(diǎn),底層通過的也是Handler,在ActivityThread 內(nèi)部類H 繼承的是Handler,這里也是View繪制的開始,后續(xù)會(huì)寫一篇文章分析。
private class H extends Handler{
public void handleMessage(Message msg) {
case RESUME_ACTIVITY:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityResume");
SomeArgs args = (SomeArgs) msg.obj;
handleResumeActivity((IBinder) args.arg1, true, args.argi1 != 0, true,
}
}
- 12、退出程序其實(shí)就是
mLooper.myLooper().quit();
case EXIT_APPLICATION:
if (mInitialApplication != null) {
mInitialApplication.onTerminate();
}
//退出Looper的循環(huán) 這里實(shí)際上是調(diào)用了MessageQueue的quit,清空所有Message。
mLooper.myLooper().quit();
break;
- 13、
handler
正確的使用的姿勢,可以看這篇文章安卓代碼、圖片、布局、網(wǎng)絡(luò)和電量優(yōu)化