Android 源碼分析-消息隊列和 Looper

1. Android 源碼分析-消息隊列和 Looper
概念

  1. 什么是消息隊列
    消息隊列在 android 中對應 MessageQueue 這個類,顧名思義,消息隊列中存放了大量的消息(Message)
  2. 什么是消息
    消息(Message)代表一個行為(what)或者一串動作(Runnable),有兩處會用到 Message:
    Handler 和 Messenger
  3. 什么是 Handler 和 Messenger
    Handler 大家都知道,主要用來在線程中發(fā)消息通知 ui 線程更新 ui。Messenger 可以翻譯為信使,可以實現(xiàn)進程間通信(IPC),Messenger 采用一個單線程來處理所有的消息,而且進程間的通信都是通過發(fā)消息來完成的,感覺不能像 AIDL 那樣直接調(diào)用對方的接口方法(具體有待考證),這是其和 AIDL 的主要區(qū)別,也就是說 Messenger 無法處理多線程,所有的調(diào) 用 都 是 在 一 個 線 程 中 串 行 執(zhí) 行 的 。 Messenger 的 典 型 代 碼 是 這 樣 的 : new
    Messenger(service).send(msg),它的本質(zhì)還是調(diào)用了 Handler 的 sendMessage 方法
  4. 什么是 Looper
    Looper 是循環(huán)的意思,它負責從消息隊列中循環(huán)的取出消息然后把消息交給目標處理
  5. 線程有沒有 Looper 有什么區(qū)別?
    線程如果沒有 Looper,就沒有消息隊列,就無法處理消息,線程內(nèi)部就無法使用 Handler。這就是為什么在子線程內(nèi)部創(chuàng)建 Handler 會報錯:"Can't create handler inside thread that has not called Looper.prepare()",具體原因下面再分析。
  6. 如何讓線程有 Looper 從而正常使用 Handler? 在線程的 run 方法中加入如下兩句:
  Looper.prepare();
  Looper.loop();

這一切不用我們來做,有現(xiàn)成的,HandlerThread 就是帶有 Looper 的線程。
想 用 線 程 的 Looper 來 創(chuàng) 建 Handler , 很 簡 單 , Handler handler = new
Handler(thread.getLooper()),有了上面這幾步,你就可以在子線程中創(chuàng)建 Handler 了,好吧, 其實 android 早就為我們想到這一點了,也不用自己寫,IntentService 把我們該做的都做了, 我們只要用就好了,具體怎么用后面再說。
消息隊列和 Looper 的工作機制
一個 Handler 會有一個 Looper,一個 Looper 會有一個消息隊列,Looper 的作用就是循環(huán)的遍歷消息隊列,如果有新消息,就把新消息交給它的目標處理。每當我們用 Handler 來發(fā)送消息,消息就會被放入消息隊列中,然后 Looper 就會取出消息發(fā)送給它的目標 target。一般情況,一個消息的 target 是發(fā)送這個消息的 Handler,這么一來,Looper 就會把消息交給
Handler 處理,這個時候 Handler 的 dispatchMessage 方法就會被調(diào)用,一般情況最終會調(diào)用
Handler 的 handleMessage 來處理消息,用 handleMessage 來處理消息是我們常用的方式。源碼分析

  1. Handler 發(fā)送消息的過程
public final boolean sendMessage(Message msg){
  return sendMessageDelayed(msg, 0);
}

public final boolean sendMessageDelayed(Message msg, long delayMillis){
    if (delayMillis < 0) { 
    delayMillis = 0;
    }
  return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}

public boolean sendMessageAtTime(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);
}

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
       msg.target = this;
        if (mAsynchronous) {
           msg.setAsynchronous(true);
        }
        //這里 msg 被加入消息隊列 queue
      return queue.enqueueMessage(msg, uptimeMillis);
}
  1. Looper 的工作過程
    public static void loop() {
        final Looper me = myLooper(); if (me == null) {
          throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
    //從 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();
    //死循環(huán),循環(huán)的取消息,沒有新消息就會阻塞for (;;) {
     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 Printer logging = me.mLogging;
    if (logging != null) {
          logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what);
    }
    //將消息交給 target 處理,這個 target 就是 Handler 類型
    msg.target.dispatchMessage(msg);
    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);
            }
      msg.recycle();
    }
}
  1. Handler 如何處理消息
    /**
      * Subclasses must implement this to receive messages.
      */
    public void handleMessage(Message msg) {
    }
    /**
      * Handle system messages here.
      */
    public void dispatchMessage(Message msg) {
       if (msg.callback != null) {
            //這個方法很簡單,直接調(diào)用 msg.callback.run(); 
            handleCallback(msg);
        } else {
            //如果我們設置了 callback 會由 callback 來處理消息
            if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
          }
      }

  //否則消息就由這里來處理,這是我們最常用的處理方式
    handleMessage(msg);
  }
}

我們再看看 msg.callback 和 mCallback 是啥東西
/package/ Runnable callback;
現(xiàn)在已經(jīng)很明確了, msg.callback 是個 Runnable , 什么時候會設置這個 callback :
handler.post(runnable),相信大家都常用這個方法吧

/**
* Callback interface you can use when instantiating a Handler to  avoid
* having to implement your own subclass of  Handler.
*
* @param msg A {@link android.os.Message Message} object
* @return True if no further handling is  desired
*/
public interface Callback {
 public boolean handleMessage(Message msg);
}

final Callback mCallback;
而 mCallback 是個接口, 可以這樣來設置 Handler handler = new Handler(callback), 這個
callback 的意義是什么呢,代碼里面的注釋已經(jīng)說了,可以讓你不用創(chuàng)建 Handler 的子類但是還能照樣處理消息, 恐怕大家常用的方式都是新 new 一個 Handler 然后 override 其
handleMessage 方法來處理消息吧,從現(xiàn)在開始,我們知道,不創(chuàng)建 Handler 的子類也可以處理消息。多說一句,為什么創(chuàng)建 Handler 的子類不好?這是因為,類也是占空間的,一個應用 class 太多,其占用空間會變大,也就是應用會更耗內(nèi)存。
HandlerThread 簡介

@Override
public void run() {
    mTid = Process.myTid(); 
    Looper.prepare(); 
    synchronized (this) {
          mLooper = Looper.myLooper(); notifyAll();
    }
    Process.setThreadPriority(mPriority); 
    onLooperPrepared();
    Looper.loop();
    mTid = -1;
}

HandlerThread 繼承自 Thread , 其在 run 方法內(nèi)部為自己創(chuàng)建了一個 Looper , 使用上
HandlerThread 和普通的 Thread 不一樣,無法執(zhí)行常見的后臺操作,只能用來處理新消息, 這是因為 Looper.loop()是死循環(huán),你的 code 根本執(zhí)行不了,不過貌似你可以把你的 code 放在 super.run()之前執(zhí)行,但是這好像不是主流玩法,所以不建議這么做。
IntentService 簡介

public void onCreate() {
// TODO: It would be nice to have an option to hold a partial wakelock
// during processing, and to have a static startService(Context, Intent)
// method that would launch the service & hand off a wakelock.
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]"); thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}

IntentService 繼承自 Service,它是一個抽象類,其被創(chuàng)建的時候就 new 了一個 HandlerThread和 ServiceHandler,有了它,就可以利用 IntentService 做一些優(yōu)先級較高的 task,IntentService 不會被系統(tǒng)輕易殺掉。使用 IntentService 也是很簡單, 首先 startService(intent), 然后
IntentService 會把你的 intent 封裝成 Message 然后通過 ServiceHandler 進行發(fā)送, 接著
ServiceHandler 會 調(diào) 用 onHandleIntent(Intent intent) 來 處 理 這 個 Message , onHandleIntent(Intent intent)中的 intent 就是你 startService(intent)中的 intent,ok,現(xiàn)在你需要做的是從 IntentService 派生一個子類并重寫 onHandleIntent 方法,然后你只要針對不同的
intent 做不同的事情即可,事情完成后 IntentService 會自動停止。所以,IntentService 是除了 Thread 和 AsyncTask 外又一執(zhí)行耗時操作的方式,而且其不容易被系統(tǒng)干掉,建議關鍵操作采用 IntentService。
在子線程創(chuàng)建 Handler 為什么會報錯?

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 mLooper = Looper.myLooper();
    //報錯的根本原因是:當前線程沒有 Looper
if (mLooper == null) {
    throw new RuntimeException(
    "Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue; mCallback = callback; mAsynchronous = async;
}

如何避免這種錯誤:在 ui 線程使用 Handler 或者給子線程加上 Looper。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容