Android 消息處理源碼分析(1)點擊打開鏈接
繼續接着分析剩下的類文件
Looper.java
public final class Looper {
final MessageQueue mQueue; //消息隊列
final Thread mThread; //Looper聯繫的線程
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) { //先會檢查是否有Looper,若有則拋出異常,沒有的話則創建一個Looper實例保存起來
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
//在這個線程中運行消息隊列,調用quit()停止
public static void loop() {
...
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(); // 從消息隊列中取出一條消息
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); //交給msg的handler分發消息處理
...
}
//取出當前線程的Looper,返回空則表示當前線程沒有Looper
public static Looper myLooper() {
return sThreadLocal.get();
}
}
Handler.java
public class Handler {
//定義Callback接口
public interface Callback {
public boolean handleMessage(Message msg);
}
//子類要實現的消息處理方法
public void handleMessage(Message msg) {
}
* Handle system messages here.
*/
public void dispatchMessage(Message msg) { //分發信息
if (msg.callback != null) { //若指定了msg.callback,則由它處理
handleCallback(msg);
} else {
if (mCallback != null) { //若指定了Handler.mCallback,則由它處理
if (mCallback.handleMessage(msg)) { //調用mCallback接口的實現方法
return;
}
}
handleMessage(msg); 最後才調用Handler自身重載的handleMessage方法
}
}
分發消息函數中,消息先會檢查自身有沒有處理自身的回調Runnable,若有則由它處理,若沒有則會檢查該handler有無自身的回調處理,若有則調用,若沒有則調用自身重載的handleMessage方法
//Handler的生成總是和它當前所處線程有關的,如果當前線程中沒有一個Looper,則會報錯,UI線程中默認有產生Looper的函數
public Handler() {
this(null, false);
}
//使用指定的Looper(可以處理那個Looper線程中的消息),不用默認的從當前線程中取出Looper
public Handler(Looper looper) {
this(looper, null, false);
}
...
}