源碼使用Android Q
知識儲備
知道Handler是幹什麼的,怎麼使用的就可以了,如果不會可以看度娘。
獲取Handler的方法
以下方法爲Google官方文檔提供的說明
構造方法 | 說明 |
---|---|
Handler() | 默認構造函數將Handler與當前線程的Looper關聯。 |
Handler(Handler.Callback callback) | 構造函數將Handler與當前線程的Looper關聯,並接受一個回調接口,在該接口中可以處理消息。 |
Handler(Looper looper) | 使用傳入的Looper |
Handler(Looper looper, Handler.Callback callback) | 結合2、3 |
Handler源碼
構造方法
public Handler() {
this(null, false);
}
public Handler(@Nullable Callback callback) {
this(callback, false);
}
public Handler(@NonNull Looper looper) {
this(looper, null, false);
}
public Handler(@NonNull Looper looper, @Nullable Callback callback) {
this(looper, callback, false);
}
前兩個構造方法調用了以下方法:
public Handler(@Nullable 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();//說明1
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
構造方法裏說明1處獲取了Looper,然後創建了隊列。
後面兩個構造方法則使用了構造時提供的方法
public Handler(@NonNull Looper looper, @Nullable Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
這個就不多說了。
以上我們可以瞭解到Handler創建時綁定了Looper。
SendMessage方法
//1
public final boolean sendMessage(@NonNull Message msg) {
return sendMessageDelayed(msg, 0);
}
//2
public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis) {
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
//3
public boolean sendMessageAtTime(@NonNull 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);
}
第一步:調用下一個方法,忽略
第二部:設置默認delayMillis,調用下一個方法
第三步:獲取當前的MessageQueue,然後將當前消息入列調用 enqueueMessage方法
private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
long uptimeMillis) {
msg.target = this;
msg.workSourceUid = ThreadLocalWorkSource.getUid();
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
上述代碼關鍵點:
1、msg的target設置爲this(當前Handler)
2、設置workSouceUid
3、將當前msg加入MessageQueue裏
Post方法
//1
public final boolean post(@NonNull Runnable r) {
return sendMessageDelayed(getPostMessage(r), 0);
}
//2
//第二部之後和sendMessage方法相同
post方法其實和sendMessage一樣,只不過是調用了getPostMessage將Runnable包裝成Message
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
Handler的方法到此就差不多了,接下來看看Looper的。
獲取Looper的方法
獲取方法 | 說明 |
---|---|
getMainLooper() | 返回應用程序的主looper,它位於應用程序的主線程中。 |
prepare() | 初始化當前線程的Looper |
getMainLooper
public static Looper getMainLooper() {
synchronized (Looper.class) {
return sMainLooper;
}
}
一個App只有一個主線程,也就意味着只有一個主線程Looper。主線程的Looper是App啓動的時候創建的。
prepare
//1
public static void prepare() {
prepare(true);
}
//2
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
//3
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
通過prepare方法可以發現:
1、一個線程只有一個Looper在2代碼裏進行了限制
2、Looper在構造方法裏創建mQueue,也就是mQueue實在Looper裏構建的
loop
public static void loop() {
final Looper me = myLooper();//1
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;
...
for (;;) {
Message msg = queue.next(); // 2
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
...
try {
msg.target.dispatchMessage(msg);//3
if (observer != null) {
observer.messageDispatched(token, msg);
}
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} catch (Exception exception) {
if (observer != null) {
observer.dispatchingThrewException(token, msg, exception);
}
throw exception;
} finally {
ThreadLocalWorkSource.restore(origWorkSource);
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
...
msg.recycleUnchecked();
}
}
loop方法調用需要注意以下幾點
1、當前線程必須有Looper綁定
2、調用MessageQueue的next方法拿到隊列中的msg
3、msg.target.dispatchMessage(msg),最終調用handler的dispathchMessage方法
先看看MessageQueue的next方法
Message next() {
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);//1
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 {
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;
}
}
}
這裏最重要的就是nativePollOnce(ptr, nextPollTimeoutMillis);這個native方法
1、如果nextPollTimeoutMillis=-1,一直阻塞不會超時。
2、如果nextPollTimeoutMillis=0,不會阻塞,立即返回。
3、如果nextPollTimeoutMillis>0,最長阻塞nextPollTimeoutMillis毫秒(超時),如果期間有程序喚醒會立即返回。
nativePollOnce關鍵源碼
int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
Java層的阻塞是通過native層的epoll監聽文件描述符的寫入事件來實現的
再來看看入棧方法
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;
}
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
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;
}
以上代碼可以得出兩個結論
1、MessageQueue是一個單列表
2、有消息插入時會調用nativeWake方法
3、入隊是根據時間戳的順序入隊的
nativeWake關鍵源碼
ssize_t nWrite = TEMP_FAILURE_RETRY(write(mWakeEventFd, &inc, sizeof(uint64_t)));
nativeWake調用write文件寫入方法,重點是write(mWakeEventFd, &inc, sizeof(uint64_t)),寫入了一個inc,這個時候epoll就能監聽到事件,也就被喚醒了
下面看看Handler的dispatchMessage源碼
public void dispatchMessage(@NonNull Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
調用了我們最初傳進來的Msg的Runnable,最終回調了我們自己寫的處理方法
獲取Message的方法
獲取方法 | 說明 |
---|---|
Message.obtain | Message提供的默認實例獲取方法(使用msg池緩存推薦使用) |
Message.obtain()源碼
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的池,使用一個單鏈表,我們用過的message進過recycle方法就會進入這個池加以複用,如果池裏沒有Msg就會new一個
總結
1、創建Handler時綁定了Looper,主線程使用默認的Looper,其他線程需要調用prepare或者使用主線程的Looper
2、調用Handler的sendMessage或者post方法時,設置msg的target爲自己,然後將消息加入messageQueue
3、Looper創建後調用loop方法會一直循環,爲了防止ANR採用了Linux的epoll監聽文件描述符的寫入事件來實現loop的阻塞和喚醒,實現無線循環
4、最終Looper會調用msg.target.dispatchMessage(msg)來最終回調Handler處理事件
5、Message獲取時採用了回收複用的機制,建議使用obtain獲取Message
6、Looper的prepare方法會創建MessageQueue