一,簡述
MessageQueue在Android中指消息隊列,顧名思義就是存放消息的消息池,但是它的内部實作并不是隊列而是一個單連結清單,可能是單連結清單的删除和插入比較有優勢吧。MessageQueue的内部對消息的主要操作就是插入,讀取删除,不具備處理消息的能力。
二,源碼分析
1,重要屬性資訊介紹
// True if the message queue can be quit.
private final boolean mQuitAllowed;
@SuppressWarnings("unused")
private long mPtr; // used by native code
Message mMessages;
private final ArrayList<IdleHandler> mIdleHandlers = new ArrayList<IdleHandler>();
private SparseArray<FileDescriptorRecord> mFileDescriptorRecords;
private IdleHandler[] mPendingIdleHandlers;
private boolean mQuitting;
// Indicates whether next() is blocked waiting in pollOnce() with a non-zero timeout.
private boolean mBlocked;
mQuitAllowed:是否允許MessageQueue退出
mPtr:可以了解成是C/C++的指針,是一個記憶體位址,當為0的時候說明消息隊列被釋放了
mMessage:表示存儲消息連結清單的頭Head
mQuitting:目前隊列是否處于正在退出狀态
mBlocked:是否被阻塞
2,構造方法
MessageQueue(boolean quitAllowed) {
mQuitAllowed = quitAllowed;
mPtr = nativeInit();
}
可以看到建立MessageQueue的時候就需要指定MessageQueue是否可以退出。nativeInit();是一個Jni方法用來初始化mPtr
3,enqueueMessage(Message msg,long when)
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);
msg.recycle();
return false;
}
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
将新消息放在連結清單頭部的條件:
1,隊列為空 ;2,接收到的新消息需要立即處理:when = 0;3,新消息等待處理的時間比連結清單隊頭要短
這時候隻需要将新消息的next指向目前連結清單的頭部,讓mMessages指向新消息,如果目前的隊列是阻塞的就喚醒隊列
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();
周遊處理新消息的位置:prev指向p的上一個消息,p開始向隊尾移動,如果新消息需要執行的等待時間小于p所指向的消息,
就将新消息放在prev和p之間
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.
如果需要喚醒隊列,調用nativeWake(mPtr);喚醒隊列
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
enqueueMessage();是MessageQueue的核心方法,主要功能是向MessageQueue中插入消息
4,next()
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;
mPtr == 0說明消息隊列被釋放了
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
阻塞操作,等待nextPollTimeoutMillis時長
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 {
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;
}
如果消息隊列正在處于退出狀态傳回null,調用dispose();釋放該消息隊列
// 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;
}
}
next();方法是MessageQueue的和新方法也是比較難了解的一個方法。主要做的工作是從消息隊列中取出消息。
void removeMessages(Handler h, int what, Object object) {
if (h == null) {
return;
}
synchronized (this) {
Message p = mMessages;
// Remove all messages at front.
while (p != null && p.target == h && p.what == what
&& (object == null || p.obj == object)) {
Message n = p.next;
mMessages = n;
p.recycleUnchecked();
p = n;
}
// Remove all messages after front.
while (p != null) {
Message n = p.next;
if (n != null) {
if (n.target == h && n.what == what
&& (object == null || n.obj == object)) {
Message nn = n.next;
n.recycleUnchecked();
p.next = nn;
continue;
}
}
p = n;
}
}
}
移除消息隊列中的消息removeMessage();這個方法有兩個重載方法,大緻邏輯是一樣的。在這個方法中有兩個while循環,對這兩個while講解比較詳細的部落格。
上面說過MessageQueue是一個連結清單,連結清單分兩種:帶頭節點的不帶頭節點的。這兩種連結清單的周遊方式不同:不帶頭節點的連結清單中,第一個元素需要單獨處理,然後将後續部分當作是帶頭節點的連結清單使用while循環周遊。MessageQueue是不帶頭節點的連結清單,是以我們可以看到有兩個while循環。
第一個while循環:如果隊列中的第一個Message的target,what,object與指定的handler,what,object相同,删除第一個元素。後續部分就成了帶頭節點的連結清單。第二個循環删除連結清單中後續中符合條件的Message
以上就是對MessageQueue的全部分析内容,有不足的地方或是有誤的地方歡迎大家提出指正。