我是代碼搬運(yùn)工,不能僅僅只是搬運(yùn)笙隙,還要整理一下。
1. Handler組成部分:
- Message:消息
- Handler:消息的發(fā)起者
- Looper:消息的遍歷者
- MessageQueue:消息隊列
2. Handler的使用流程:
使用Handler之前的準(zhǔn)備工作有三步:
調(diào)用Looper.prepare()(主線程不需要調(diào)這個,因?yàn)锳PP創(chuàng)建時,main方法里面已經(jīng)幫我們創(chuàng)建了)
創(chuàng)建Handler對象赂毯,重寫handleMessage方法(你可以不重寫),用于處理message回調(diào)的
調(diào)用Looper.loop()
其中:
Looper.prepare()的作用主要有以下三點(diǎn):
創(chuàng)建Looper對象
創(chuàng)建MessageQueue對象拣宰,并讓Looper對象持有
讓Looper對象持有當(dāng)前線程
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
// 規(guī)定了一個線程只有一個Looper党涕,也就是一個線程只能調(diào)用一次Looper.prepare()
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
// 如果當(dāng)前線程沒有Looper,那么就創(chuàng)建一個巡社,存到sThreadLocal中
sThreadLocal.set(new Looper(quitAllowed));
}
從上面的代碼可以看出膛堤,一個線程最多只有一個Looper對象。當(dāng)沒有Looper對象時晌该,去創(chuàng)建一個Looper肥荔,并存放到sThreadLocal中
private Looper(boolean quitAllowed) {
// 創(chuàng)建了MessageQueue,并供Looper持有
mQueue = new MessageQueue(quitAllowed);
// 讓Looper持有當(dāng)前線程對象
mThread = Thread.currentThread();
}
這里主要就是創(chuàng)建了消息隊列MessageQueue朝群,并讓它供Looper持有燕耿,因?yàn)橐粋€線程最多只有一個Looper對象,所以一個線程最多也只有一個消息隊列姜胖。然后再把當(dāng)前線程賦值給mThread誉帅。
Handler使用流程:
Handler.post(或sendMessage): handler發(fā)送消息msg
MessageQueue.enqueueMessage(msg, uptimeMillis):msg加入message隊列
loop() 方法中從MessageQue中取出msg,然后回調(diào)handler的dispatchMessage右莱,然后執(zhí)行callback(如果有的話) 或 handleMessage蚜锨。(注意,loop方法是一直在循環(huán)的慢蜓,從前面的handler準(zhǔn)備工作開始就已經(jīng)一直在運(yùn)行了)
如圖所示:
3. Handler具體源碼:
3.1. Message獲取
Message的獲取方式有兩種:
1. Message msg = new Message();
2. Message msg = Message.obtain();
從全局池返回一個新的消息實(shí)例亚再。允許我們在許多情況下避免分配新對象。
/**
* 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();
}
復(fù)用之前用過的 Message 對象晨抡,這里實(shí)際上是用到了一種享元設(shè)計模式针余,這種設(shè)計模式最大的特點(diǎn)就是復(fù)用對象饲鄙,避免重復(fù)創(chuàng)建導(dǎo)致的內(nèi)存浪費(fèi)
/**
* 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使用完了之后會調(diào)用recycleUnchecked回收message凄诞,方便下次使用
Message核心的信息有這些:
public int what;
public int arg1;
public int arg2;
public Object obj;
/*package*/ int flags;
/*package*/ long when;
/*package*/ Bundle data;
/*package*/ Handler target;
/*package*/ Runnable callback;
// sometimes we store linked lists of these things
/*package*/ Message next;
3.2 Handler的發(fā)送消息
handler提供的發(fā)送消息的方法有很多圆雁,大致分為兩類:
- Handler.post(xxx);
- Handler.sendMessage(xxx);
雖然方法很多,但最終都會回調(diào)到這個方法:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
這個方法就是將消息添加到隊列里帆谍。
3.3 MessageQueue的添加消息
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;
}
// 標(biāo)記這個 Message 已經(jīng)被使用
msg.markInUse();
msg.when = when;
// 這是這個消息隊列里的目前第一條待處理的消息(當(dāng)前消息隊列的頭部伪朽,有可能為空)
Message p = mMessages;
boolean needWake;
// 如果目前隊列里沒有消息 或 這條消息msg需要立即執(zhí)行 或 這條消息msg的延遲時間比隊列里的第一條待處理的消息還要早的話,走這個邏輯
if (p == null || when == 0 || when < p.when) {
// 把消息插入到消息隊列的頭部
// 最新的消息汛蝙,如果已經(jīng)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循環(huán)的作用就是找出msg應(yīng)該放置的正確位置
// 經(jīng)過下面這個for循環(huán),最終會找出msg的前一個消息是prev窖剑,后一個消息是p
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
// 上面的for循環(huán)得出的結(jié)果就是:msg應(yīng)該在prev后面坚洽,在p前面
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;
}
上面就是handler發(fā)送消息過來西土,然后添加到消息隊列里讶舰。
下面就開始講添加消息到隊列之后的事情:取消息,然后執(zhí)行需了。
3.4 Loop的取消息
前面已經(jīng)說到跳昼,在使用Handler之前有三步準(zhǔn)備工作:
調(diào)用Looper.prepare()(主線程不需要調(diào)這個,因?yàn)锳PP創(chuàng)建時肋乍,main方法里面已經(jīng)幫我們創(chuàng)建了)
創(chuàng)建Handler對象鹅颊,重寫handleMessage方法(你可以不重寫),用于處理message回調(diào)的
調(diào)用Looper.loop()
其中第三步的Looper.loop()的作用就是不斷的從MessageQueue隊列里取消息墓造,也就是說堪伍,在使用handler發(fā)消息之前,就已經(jīng)開始了loop的循環(huán)了觅闽。
loop()源碼比較長帝雇,這里摘取核心部分:
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*
* 大概的翻譯就是:在這個線程中運(yùn)行消息隊列。確保調(diào)用{@link #quit()}來結(jié)束循環(huán)谱煤。
*
*/
public static void loop() {
····
····
for (;;) {
// 不斷的從MessageQueue的next方法里取出隊列的頭部消息
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
·····
·····
·····
try {
// msg.target是Message在創(chuàng)建時傳入的Handler摊求,也就是發(fā)送這條消息的發(fā)送者h(yuǎn)andler
// 所以最終會回調(diào)到handler的dispatchMessage方法
msg.target.dispatchMessage(msg);
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
····
····
// 回收msg,重復(fù)利用
msg.recycleUnchecked();
}
}
loop()的作用就是不斷的從MessageQueue里取消息刘离,然后回調(diào)到dispatchMessage里室叉,再看看dispatchMessage里干啥了
/**
* 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);
}
}
所以最終會執(zhí)行callback或handleMessage。
簡書對文章長度有限制硫惕,剩下的放到下一篇文章:
(Handler知識收集整理-2)