android Handler、Looper、Messsage、MessageQueue原始碼解析
Handler:傳送和接收訊息
Looper:訊息(迴圈)輪詢器
Message:訊息池
MessageQueue:訊息佇列。雖然名為佇列,但事實上它的內部儲存結構並不是真正的佇列,而是採用單鏈表的資料結構來儲存訊息列表的
先來看Handler,其實系統很多東西都是通過Handler訊息來實現的,其中也包括activity的生命週期,應用程式的退出等;在ActivityThread類中的main方法中可以很清楚的看到,同時main方法也是android應用程式的主入口;
public static void main(String[] args) { Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain"); SamplingProfilerIntegration.start(); // CloseGuard defaults to true and can be quite spammy. We // disable it here, but selectively enable it later (via // StrictMode) on debug builds, but using DropBox, not logs. CloseGuard.setEnabled(false); Environment.initForCurrentUser(); // Set the reporter for event logging in libcore EventLogger.setReporter(new EventLoggingReporter()); // Make sure TrustedCertificateStore looks in the right place for CA certificates final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId()); TrustedCertificateStore.setDefaultUserDirectory(configDir); Process.setArgV0("<pre-initialized>"); //例項化一個main Looper Looper.prepareMainLooper(); //例項化ActivityThread ActivityThread thread = new ActivityThread(); //呼叫attach方法 thread.attach(false); //通過ActivityThread獲取Handler物件 if (sMainThreadHandler == null) { sMainThreadHandler = thread.getHandler(); } if (false) { Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread")); } // End of event ActivityThreadMain. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); //開啟訊息輪詢器 Looper.loop(); throw new RuntimeException("Main thread loop unexpectedly exited"); }
在例項化一個main looper的時候呼叫的是prepareMainLooper();方法;prepareMainLooper();方法是Looper類中的方法;
public static void prepareMainLooper() { //呼叫prepare方法 prepare(false); synchronized (Looper.class) { //這裡需要注意只能例項化一個main Looper物件,多次例項化會報錯 if (sMainLooper != null) { throw new IllegalStateException("The main Looper has already been prepared."); } sMainLooper = myLooper(); } }
prepare();方法這裡就暫時不講了,後面會講到,例項化完mian looper後,就會去例項化ActivityThread物件並呼叫其中的attach()方法及getHandler()方法去例項化一個Handler物件;
final Handler getHandler() {
//mH extends Handler 在載入ActivityThread的時候就已經初始化了
return mH;
}
H類就是一個內部類,看到LAUNCH_ACTIVITY、PAUSE_ACTIVITY、EXIT_APPLICATION、STOP_SERVICE等很多訊息標識,這樣通過handler訊息來控制activity的生命週期以及一些其他東西;當msg.what為EXIT_APPLICATION時,應用程式就會退出,並不是activity的生命週期都會走,當訊息標識為EXIT_APPLICATION應用程式就已經退出了,而應用程式的退出時呼叫Looper中的quit方法;private class H extends Handler { public static final int LAUNCH_ACTIVITY = 100; public static final int PAUSE_ACTIVITY = 101; public static final int DESTROY_ACTIVITY = 109; public static final int EXIT_APPLICATION = 111; public static final int STOP_SERVICE = 116; String codeToString(int code) { if (DEBUG_MESSAGES) { switch (code) { case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY"; case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY"; case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY"; case EXIT_APPLICATION: return "EXIT_APPLICATION"; case STOP_SERVICE: return "STOP_SERVICE"; } } return Integer.toString(code); } public void handleMessage(Message msg) { if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what)); switch (msg.what) { case LAUNCH_ACTIVITY: { Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart"); final ActivityClientRecord r = (ActivityClientRecord) msg.obj; r.packageInfo = getPackageInfoNoCheck( r.activityInfo.applicationInfo, r.compatInfo); handleLaunchActivity(r, null, "LAUNCH_ACTIVITY"); Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); } break; case PAUSE_ACTIVITY: { Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause"); SomeArgs args = (SomeArgs) msg.obj; handlePauseActivity((IBinder) args.arg1, false, (args.argi1 & USER_LEAVING) != 0, args.argi2, (args.argi1 & DONT_REPORT) != 0, args.argi3); maybeSnapshot(); Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); } break; case DESTROY_ACTIVITY: Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityDestroy"); handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0, msg.arg2, false); Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); break; case EXIT_APPLICATION: if (mInitialApplication != null) { mInitialApplication.onTerminate(); } Looper.myLooper().quit(); break; case STOP_SERVICE: Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceStop"); handleStopService((IBinder)msg.obj); maybeSnapshot(); Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); break; } }
public void quit() {
mQueue.quit(false);
}
這裡就粗略而過,後面會詳細講;這是一些系統handler的使用,還是看看平時開發中的使用吧;
public class MainActivity extends AppCompatActivity {
Handler mHanlder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//開啟子執行緒
new MyThread().start();
}
class MyThread extends Thread implements Runnable {
@Override
public void run() {
super.run();
//例項化訊息輪詢器
Looper.prepare();
//例項化handler物件
mHanlder = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
//獲取message物件
Message message = mHanlder.obtainMessage();
message.what = 1;
//傳送訊息
mHanlder.sendMessage(message);
//開啟looper輪詢器
Looper.loop();
}
}
}
這是一段在子執行緒中例項化handler的程式碼,當然了也可以不線上程中例項化handler,這樣子就不需要例項化一個Looper,系統已經實現了的,如果在子線中例項化handler就需要同樣例項化一個Looper,確保handler所線上程和Looper所在的執行緒一致,否則會報錯;
先來看第一步Looper.prepare()例項化一個Looper;
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
//呼叫prepare方法quitAllowed就為true,呼叫的是prepareMainLooper方法quitAllowed就是false
//sThreadLocal.get()是直接從ThreadLocal池中獲取 這裡同樣只能例項化一個Looper,多次例項化會報錯
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
//直接new 一個Looper,並將例項化的Looper物件新增到ThreadLocal池中
sThreadLocal.set(new Looper(quitAllowed));
}
在new 一個looper的時候會去例項化一個MessageQueue物件;
private Looper(boolean quitAllowed) {
//直接例項化一個MessageQueue物件
mQueue = new MessageQueue(quitAllowed);
//獲取當前執行緒
mThread = Thread.currentThread();
}
第二步handler的例項化
handler提供多個構造方法,可以傳入一個Looper,Callback回撥等,這裡直接用了無參構造;
public Handler() {
this(null, false);
}
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());
}
}
//獲取例項化好的looper物件,這裡是從ThreadLocal池中直接獲取的
mLooper = Looper.myLooper();
//如果獲取到的looper物件為null就會報錯,所以要保證例項化好的looper物件和handler物件所在的執行緒要一致,
//也就是平時如果在子執行緒中例項化handler沒有例項化looper報錯的原因
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
//獲取MessageQueue物件,MessageQueue物件在例項化looper的構造方法中就已經例項化好了
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
public static @Nullable Looper myLooper() {
//myLooper是looper類中的方法,從ThreadLocal池中直接獲取looper物件
return sThreadLocal.get();
}
第三步Message物件的例項化,通過obtainMessage();方法獲取的Message物件,當然也可以直接new 一個Message,不過建議使用obtainMessage();方法獲取;
public final Message obtainMessage()
{
//呼叫Handler類中的obtainMessage方法,返回一個Message物件,不過呼叫的是Message中的obtain方法,並將Handler本身做引數傳入
return Message.obtain(this);
}
public static Message obtain(Handler h) {
//這裡又呼叫了Message中的obtain()方法
Message m = obtain();
//將傳入的handler物件賦值給Message中的target變數
m.target = h;
return m;
}
/**
* Return a new Message instance from the global pool. Allows us to
返回一個Message例項,從全域性池中
* avoid allocating new objects in many cases.
*/
public static Message obtain() {
synchronized (sPoolSync) {
//判斷Message池是否為null
if (sPool != null) {
//不為null就將sPool物件賦值個m
Message m = sPool;
//又將m中的賦值給sPool 這裡是連結串列結構
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
//將獲取到的message例項返回
return m;
}
}
//sPool為null的情況下直接new 一個Message物件並返回
return new Message();
}
Message類中還提供了recycleUnchecked()方法,用於handler訊息的回收,這裡暫不說;Message物件有了,呼叫sendMessage()傳送訊息,當然了Handler類中不只這一個方法可以傳送訊息,還有其他的方法,具體可以看Handler原始碼;
/**
* Pushes a message onto the end of the message queue after all pending messages
* before the current time. It will be received in {@link #handleMessage},
* in the thread attached to this handler.
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*/
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
//delayMillis延遲傳送的時間 毫秒值
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
//獲取MessageQueue物件,mQueue是在例項化handler時,通過looper物件獲取,最初是在例項化looper物件的構造方法中例項化的
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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
//將當前的handler賦值給Message中的handler
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
走到這裡就會去呼叫MessageQueue中的enqueueMessage()方法;
boolean enqueueMessage(Message msg, long when) {
//msg.target就是handler物件,上面已經進行了賦值操作
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);
//呼叫recycle方法,如果沒有被回收就會呼叫recycleUnchecked()方法進行handler訊息的回收
msg.recycle();
return false;
}
msg.markInUse();
msg.when = when;
//建立新的Message物件,並賦值
Message p = mMessages;
boolean needWake;
//建立的message物件為null或者沒有延遲傳送訊息或者延遲傳送訊息的時間小於傳送的時間
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if 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 (;;) {
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;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
這樣子就將訊息新增到佇列中了,通過Looper.loop();開啟輪詢去取訊息;
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static void loop() {
//獲取looper物件,如果為null說明沒有例項化looper物件,會報錯
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
//獲取MessageQueue物件,MessageQueue物件是在例項化looper物件的構造方法中例項化的
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死迴圈,不管是ActivityThread中的void main方法,還是平時使用loop()方法都是在最後面呼叫,這樣不會阻塞
for (;;) {
//這裡是連結串列結構,通過next()去獲取每一個message物件
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 traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
//將獲取到的message訊息通過handler中的dispatchMessage方法進行分發
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
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);
}
//通過messsage中的recycleUnchecked方法對訊息進行回收
msg.recycleUnchecked();
}
}
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
//訊息迴圈
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
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) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
//將msg賦值給prevMsg
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
//獲取到的時間訊息訊息的時間
// Next message is not ready. Set a timeout to wake up when it is ready.
//下一條訊息尚未準備好。設定一個超時,以便在準備就緒時喚醒。
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// Got a message.
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;
}
}
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
//設定了callback就會走這裡
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
//這裡是沒有設定callback
handleMessage(msg);
}
}
/**
* Subclasses must implement this to receive messages.
*例項化handler的時候都會去重寫該方法,在該方法中進行訊息的處理
*/
public void handleMessage(Message msg) {
}
在訊息處理完畢後,還會對訊息進行回收的;
/**
* 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++;
}
}
}
Looper.loop();中是一個死迴圈,所以在使用handler訊息的時候需要注意當頁面銷燬後要將訊息移除掉,避免造成記憶體洩漏什麼的;handler提供一些移除訊息的方法;
/**
* Remove any pending posts of callbacks and sent messages whose
* <var>obj</var> is <var>token</var>. If <var>token</var> is null,
* all callbacks and messages will be removed.
*/
public final void removeCallbacksAndMessages(Object token) {
//token為null的時候所有的callback和messages都會被移除掉
mQueue.removeCallbacksAndMessages(this, token);
}
當然也可以移除指定的訊息或者callback;上面就是對handler訊息的一些原始碼分析。