Message:消息,其中包含了消息ID,消息處理對象以及處理的數據等,由MessageQueue統一列隊,終由Handler處理。
Handler:處理者,負責Message的發送及處理。使用Handler時,需要實現handleMessage(Message msg)方法來對特定的Message進行處理,例如更新UI等。
MessageQueue:消息隊列,用來存放Handler發送過來的消息,并按照FIFO規則執行。當然,存放Message并非實際意義的保存,而是將Message以鏈表的方式串聯起來的,等待Looper的抽取。
Looper:消息泵,不斷地從MessageQueue中抽取Message執行。因此,一個MessageQueue需要一個Looper。
Thread:線程,負責調度整個消息循環,即消息循環的執行場所。
源碼解析
- Looper
public class Looper {
// 每個線程中的Looper對象其實是一個ThreadLocal,即線程本地存儲(TLS)對象
private static final ThreadLocal sThreadLocal = new ThreadLocal();
// Looper內的消息隊列
final MessageQueue mQueue;
// 當前線程
Thread mThread;
// 。。。其他屬性
// 每個Looper對象中有它的消息隊列,和它所屬的線程
private Looper() {
mQueue = new MessageQueue(); //添加消息隊列
mRun = true;
mThread = Thread.currentThread();
}
// 我們調用該方法會在調用線程的TLS中創建Looper對象
public static final void prepare() {
if (sThreadLocal.get() != null) {
// 試圖在有Looper的線程中再次創建Looper將拋出異常
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper());
}
// 其他方法
}
首先看prepare()方法
sThreadLocal是一個ThreadLocal對象,可以在一個線程中存儲變量。
可以看到,在第5行,將一個Looper的實例放入了ThreadLocal,并且2-4行判斷了sThreadLocal是否為null,否則拋出異常。
這也就說明了Looper.prepare()方法不能被調用兩次,同時也保證了一個線程中只有一個Looper實例。
.
下面看Looper的構造方法:
在構造方法中,創建了一個MessageQueue(消息隊列)。
.
然后再看loop()方法:
public static final void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare()
wasn't called on this thread.");
}
//myLooper()方法直接返回了sThreadLocal存儲的Looper實例,
//如果me為null則拋出異常,也就是說looper方法必須在prepare方法之后運行。
final MessageQueue queue = me.mQueue;
//拿到該looper實例中的mQueue(消息隊列)
// 這兩行沒看懂= = 不過不影響理解
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
// 開始循環
while (true) {
Message msg = queue.next(); // 取出message,如果沒有消息則阻塞。
if (msg != null) {
if (msg.target == null) {
// message沒有target為結束信號,退出循環
return;
}
// 日志。。。
if (me.mLogging!= null) me.mLogging.println(
">>>>> Dispatching to " + msg.target + " "
+ msg.callback + ": " + msg.what
);
// 非常重要!把消息交給msg的target的dispatchMessage方法去處理。
//Msg的target是什么呢?其實就是handler對象。這確保了
//looper執行到該message時能找到處理它的handler
msg.target.dispatchMessage(msg);
// 還是日志。。。
if (me.mLogging!= null) me.mLogging.println(
"<<<<< Finished to " + msg.target + " "
+ msg.callback);
// 下面沒看懂,同樣不影響理解
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf("Looper", "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);
}
// 回收message資源
msg.recycle();
}
}
}
Looper主要作用:
1、與當前線程綁定,保證一個線程只會有一個Looper實例,同時一個Looper實例也只有一個MessageQueue。
2、loop()方法,不斷從MessageQueue中去取消息,交給消息的target屬性的dispatchMessage去處理。
-
Handler
什么是handler?handler扮演了往MQ上添加消息和處理消息的角色(只處理由自己發出的消息),即通知MQ它要執行一個任務(sendMessage),并在loop到自己的時候執行該任務(handleMessage),整個過程是異步的。handler創建時會關聯一個looper,默認的構造方法將關聯當前線程的looper,不過這也是可以set的。默認的構造方法:
public class handler {
final MessageQueue mQueue; // 關聯的MQ
final Looper mLooper; // 關聯的looper
final Callback mCallback;
// 其他屬性
public Handler() {
// 沒看懂,直接略過,,,
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());
}
}
// 通過Looper.myLooper()獲取了當前線程保存的Looper實例
mLooper = Looper.myLooper();
// looper不能為空,即該默認的構造方法只能在looper線程中使用
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
// 重要!!!獲取了這個Looper實例中保存的MessageQueue(消息隊列),
//這樣就保證了handler的實例與我們Looper實例中MessageQueue關聯上了。
mQueue = mLooper.mQueue;
mCallback = null;
}
// 其他方法
}
一個線程可以有多個Handler,但是只能有一個Looper!
然后看我們最常用的sendMessage方法
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageDelayed(msg, delayMillis);
}
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);
}
最后調用了sendMessageAtTime,在此方法內部有直接獲取MessageQueue然后調用了enqueueMessage方法
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
enqueueMessage中首先為msg.target賦值為this,也就是把當前的handler作為msg的target屬性。最終會調用queue的enqueueMessage的方法,也就是說handler發出的消息,最終會保存到消息隊列中去。
.
現在已經很清楚了Looper會調用prepare()和loop()方法,在當前執行的線程中保存一個Looper實例,這個實例會保存一個MessageQueue對象,然后當前線程進入一個無限循環中去,不斷從MessageQueue中讀取Handler發來的消息。然后再回調創建這個消息的handler中的dispathMessage方法:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
方法中調用了handleMessage方法:
/**
* Subclasses must implement this to receive messages.
*/
public void handleMessage(Message msg) {
}
可以看到這是一個空方法,為什么呢,因為消息的最終回調是由我們控制的,我們在創建handler的時候都是復寫handleMessage方法,然后根據msg.what進行消息處理。
.
那么在Activity中,我們并沒有顯示的調用Looper.prepare()和Looper.loop()方法,為啥Handler可以成功創建呢,這是因為在Activity的啟動代碼中,已經在當前UI線程調用了Looper.prepare()和Looper.loop()方法。
參考博客CodingMyWorld、鴻洋_