【Android 异步操作】Handler 机制 ( Android 提供的 Handler 源码解析 | Handler 构造与消息分发 | MessageQueue 消息队列相关方法 )
文章目錄
- 一、Handler 構造函數
- 二、Handler 消息分發
- 三、MessageQueue 消息隊列相關函數
一、Handler 構造函數
一般使用 Handler 時 , 調用 Handler 的普通 無參構造函數 ,
public class Handler {/*** 默認的構造函數 , 與當前線程相關聯.* 如果該線程沒有 Looper , 該 Handler 不能接受 Message 消息 , 并拋出異常*/public Handler() {this(null, false);} }上面的無參構造函數調用了下面的構造方法 ,
第一個參數 Callback callback 是一個回調 , mCallback = callback , 該回調直接設置給了 mCallback 成員變量 ,
在該方法中 , 調用 mLooper = Looper.myLooper() 獲取線程本地變量 Looper ;
獲取 Looper 中的消息隊列 MessageQueue , mQueue = mLooper.mQueue ;
主線程的 Looper 是在 ActivityThread 中的 main 函數 中 , 使用 Looper.prepareMainLooper() 創建的 ,
在 ActivityThread 的 main 函數最后調用了 Looper.loop() , 無限循環獲取主線程 Looper 中封裝的 MessageQueue 消息隊列中的消息 ;
參考 : 【Android 異步操作】Handler ( 主線程中的 Handler 與 Looper | Handler 原理簡介 ) ,
public class Handler {/*** Use the {@link Looper} for the current thread with the specified callback interface* and set whether the handler should be asynchronous.** Handlers are synchronous by default unless this constructor is used to make* one that is strictly asynchronous.** Asynchronous messages represent interrupts or events that do not require global ordering* with respect to synchronous messages. Asynchronous messages are not subject to* the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.** @param callback The callback interface in which to handle messages, or null.* @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for* each {@link Message} that is sent to it or {@link Runnable} that is posted to it.** @hide*/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();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;} }Handler 中的 Callack 回調 接口 ;
public class Handler {/*** Callback interface you can use when instantiating a Handler to avoid* having to implement your own subclass of Handler.*/public interface Callback {/*** @param msg A {@link android.os.Message Message} object* @return True if no further handling is desired*/boolean handleMessage(@NonNull Message msg);} }二、Handler 消息分發
Handler 中的消息分發 , 在 Looper 的 loop 方法中 , 調用該消息 dispatchMessage 分發消息的方法 ,
在該分發消息方法中 , 首先會查看 消息 Message 中 是否有 Callback 回調 ,
如果有執行該回調 , 就是構造函數中賦值的 mCallback ,
如果沒有就調用 Handler 中的 handleMessage 方法 ;
public class Handler {/*** 在這里處理 Message 消息.*/public void dispatchMessage(@NonNull Message msg) {if (msg.callback != null) {handleCallback(msg);} else {if (mCallback != null) {if (mCallback.handleMessage(msg)) {return;}}handleMessage(msg);}} }使用 Handler 發送消息時 , 會 調用各種發送消息的方法 , 如
- public final boolean sendMessage(@NonNull Message msg)
- public final boolean sendEmptyMessage(int what)
- public final boolean sendEmptyMessageDelayed
- public final boolean sendEmptyMessageAtTime
- public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis)
等方法 , 所有的發送消息的方法 , 最終都會調用 public boolean sendMessageAtTime(@NonNull Message msg, long uptimeMillis) 方法 ,
在該方法中 , 調用 MessageQueue queue = mQueue , 獲取 消息隊列 MessageQueue ,
然后調用 enqueueMessage(queue, msg, uptimeMillis) 方法 , 將消息加入到 消息隊列 MessageQueue 中 ;
public class Handler {/*** Enqueue a message into the message queue after all pending messages* before the absolute time (in milliseconds) <var>uptimeMillis</var>.* <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>* Time spent in deep sleep will add an additional delay to execution.* You will receive it in {@link #handleMessage}, in the thread attached* to this handler.* * @param uptimeMillis The absolute time at which the message should be* delivered, using the* {@link android.os.SystemClock#uptimeMillis} time-base.* * @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. Note that a* result of true does not mean the message will be processed -- if* the looper is quit before the delivery time of the message* occurs then the message will be dropped.*/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);} }三、MessageQueue 消息隊列相關函數
下面的代碼是將消息存儲到消息隊列中的 enqueueMessage 方法 ;
public final class MessageQueue {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.nextprev.next = msg;}// We can assume mPtr != 0 because mQuitting is false.if (needWake) {nativeWake(mPtr);}}return true;} }從鏈表中取出數據 , 調用的是 消息隊列 MessageQueue 的 next 方法 , 獲取消息時 , 需要獲取當前的時間 , 用于判定是否有需要延遲發送的消息 ;
public final class MessageQueue {@UnsupportedAppUsageMessage 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 iterationint 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 {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 handlerboolean 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;}} }總結
以上是生活随笔為你收集整理的【Android 异步操作】Handler 机制 ( Android 提供的 Handler 源码解析 | Handler 构造与消息分发 | MessageQueue 消息队列相关方法 )的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Android 异步操作】手写 Han
- 下一篇: 【Android 异步操作】Handle