csdn博客同步地址csdn博客鏈接
先上handler機制的圖片屠尊,然后來逐步分析峡谊,查看他的源碼
Handler源碼分析
創(chuàng)建Handler
Handler提供了多種構造方法的重載,主要分為兩類更胖,一類是不指定Looper對象平窘,也就是直接使用當前線程的Looper荣倾,另一類是制定Looper关拒,先看看他的構造方法
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;
}
從這個構造函數(shù)可以看出桌硫,如果不是靜態(tài)的內部類的話,會打印出內存泄漏的警告趋箩,而且可以知道在創(chuàng)建線程之前當前線程必須有l(wèi)ooper對象赃额,主線程的looper在源碼中已經(jīng)默認實現(xiàn)好了
在看下另外個構造方法
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
就是簡單對傳入的looper進行賦值
發(fā)送消息
使用handler最多的就是sentMessage(message)
先看看他的源碼
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
他其實就是調用sendMessageDelayed(Message,long)
我們看下這個方法內部
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
就是為當前時間加上個目標時間,然后穿進去作為參數(shù)
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);
}
可以看到這個方法調用了enqueueMessage(MessageQueue,Message,long)
方法叫确,就是讓消息去排隊
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
從這里可以看出兩個事情
1.Message對象被加入MessageQueue的隊列中
2.Messagetarget是用來持有Handler的強應用跳芳,而Handler如果是非靜態(tài)內部類,是默認持有外部Activity強引用的竹勉,這樣就會造成所謂的內存泄漏
除了sentMessage外飞盆,還有一種就是post(Runnable)
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
其實就是調用了sentMessageDelayed(Message,long)
,只不過就是把Runable封裝進入Message
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
最后被送入消息隊列中
處理消息
當消息被丟進消息對壘中,就要被處理,我們經(jīng)常用Handler就是重寫handleMessage(Message)
方法來處理Message吓歇,其實還有另外一種方式就是實現(xiàn)Handler.Callback接口孽水,這個接口要求必須實現(xiàn)帶boolean值得handleMessage(Message)
方法,這兩種實現(xiàn)方法如下
private static class MyHandler extends Handler{
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
//處理消息城看,
}
}
private static class MyHanderCallback implements Handler.Callback{
@Override
public boolean handleMessage(Message msg) {
return false;
}
}
private Handler myHandler = new Handler(new MyHanderCallback());
這兩種處理方式有什么區(qū)別呢女气?就在于,第二種實現(xiàn)handler.Callback
的處理方法是有boolean值得析命,Handler會優(yōu)先處理Handler.Callback
實現(xiàn),然后根據(jù)返回值決定是否調用Handler的handlerMassage(Message)
方法逃默,接下來看下dispatchMessage(Message)
方法
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);//處理Runable類型消息
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {//當Callback.handleMessage返回true時候直接return鹃愤,就不再執(zhí)行handleMessage
return;
}
}
handleMessage(msg);
}
}
當一個消息從隊列中被取出時候,會通過dispatchMessage(Message)
方法分配給Handler完域。在處理消息的時候優(yōu)先處理Runable類型的消息软吐,然后再根據(jù)Handle.Callback.handleMessage(Message)
最后才是Handler.handleMessage(Message)
Message源碼分析
Message相當于一個消息媒介,我們通過對這個message對象進行設置吟税,然后最后將他發(fā)送出去
創(chuàng)建Message
創(chuàng)建消息時我們不是直接newMessage凹耙,而是通過Message.obtain()
方法,從Message內部維護的一個消息池里面獲取一個Message對象肠仪,這樣的話就可以復用肖抱,而不會因為頻繁發(fā)送消息而造成頻繁gc,內存抖動那些异旧,先看看Message源碼
public final class Message Implements Parcelable{
private static final int MAX_POOL_SIZE = 50意述;//消息池最大數(shù)量為50
private static Message sPool;//消息池
Message next;//消息池實際上是一個鏈表結構
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
為了實現(xiàn)復用荤崇,Message被處理完后就會回到消息池中,回收的過程就是清空所有數(shù)據(jù)潮针,全部設置被默認值
public void recycle() {
if (isInUse()) {
if (gCheckRecycle) {
throw new IllegalStateException("This message cannot be recycled because it "
+ "is still in use.");
}
return;
}
recycleUnchecked();
}
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++;
}
}
}
MessageQueue源碼分析
MessageQueue就是消息隊列术荤,我們通過Handler發(fā)送消息都會進入到這個Mess個Queue中,之后Looper會提取消息進行處理每篷,看看MessageQUeue源碼
消息入列
先從他的enqueueMessage(Message瓣戚,long)
源碼看下
boolean enqueueMessage(Message msg, long when) {
synchronized (this) {
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
//根據(jù)時間節(jié)點來插入Message
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;
}
}
}
可以看出他是根據(jù)when這個時間節(jié)點進行排隊的,根據(jù)時間的排序找到一個合適的Message對象插入隊列中
消息出列
接下來看看消息出列的代碼焦读,也就是MessageQueue.next()
方法带兜,Looper實際上通過這個方法獲取下一個要執(zhí)行的Message對象,
Message next() {
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
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)
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
//還沒有到達時間的情況吨灭,就設置一個定時器讓他喚醒
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// Got a message.
mBlocked = false;
if (prevMsg != null) {
//有barrier情況
prevMsg.next = msg.next;
} else {
//無barrier的情況
mMessages = msg.next;
}
msg.next = null;
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;
}
}
上面邏輯大概就是:判斷消息隊列中第一個消息是否到達執(zhí)行時間點刚照,如果滿足條件就移除并返回第一個Message對象,否則邏輯往下走執(zhí)行idlerHandler喧兄,所謂的idlerHandler就是在空閑的時候會被執(zhí)行一次无畔,如果queueIdle返回false的話就會執(zhí)行之后移除空閑隊列
關閉隊列###
void quit(boolean safe) {
if (!mQuitAllowed) {
throw new IllegalStateException("Main thread not allowed to quit.");
}
synchronized (this) {
if (mQuitting) {
return;
}
mQuitting = true;
if (safe) {
//安全的方式關閉隊列
//就是對沒有到達時間點的消息進行移除啊楚,把沒有到達時間點的執(zhí)行完先
removeAllFutureMessagesLocked();
} else {
//直接暴力的關閉隊列
removeAllMessagesLocked();
}
// We can assume mPtr != 0 because mQuitting was previously false.
nativeWake(mPtr);
}
}