android Handler 分析

首先需要明白,handler發消息是爲了做異步操作.異步大家都很清楚.一個比較常用的例子就是.一個輔助線程要更新UI線程的畫面,直接用View操作是不行的.這就需要異步更新.給UI線程發消息,讓他更新.
那Handler是如何做到異步發消息更新的呢?需要解決以下幾個問題.
系統如何知道我這個handler是給哪個線程發消息.
系統是如何做到異步的呢?
看代碼吧.在UI線程啓動後,會
public static final void prepare() {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper());
    }
這樣就創建了個Looper, 並且在構造函數中創建消息隊列,並且集註當前線程.
private Looper() {
        mQueue = new MessageQueue();  //轉載者補充:消息隊列是由Looper創建的
        mRun = true;
        mThread = Thread.currentThread();
    }
當我們在創建handler對象時候.以下代碼位於Handler的構造函數中。
mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
在我們handler裏會有了這個looper引用。以及得到該looper的消息隊列.

MessageQueue

消息隊列MessageQueue是一個以執行時間爲序的優先級隊列:
o 普通消息的執行爲當前時間,先發送的在前面,後發送在後面,這是典型的FIFO。
o 最高優先級的消息執行時間爲0,所以直接插在隊列的最前面,通常會立即執行。
o 而在將來執行的Message相當於timer,執行時間爲當前時間+delay的時間。

MessageQueue的函數boolean enqueueMessage(Message msg, long when)用來向隊列中插入消息。
那如何證明這句話呢?
enqueueMessage的具體實現過程.
msg.when = when;
            //Log.d("MessageQueue", "Enqueing: " + msg);
            Message p = mMessages;
            if (p == null || when == 0 || when < p.when) {
                msg.next = p;
                mMessages = msg;
                this.notify();
            } else {
                Message prev = null;
                while (p != null && p.when <= when) {
                    prev = p;
                    p = p.next;
                }
                msg.next = prev.next;
                prev.next = msg;
                this.notify();

這就看出來了,根據when把消息插到消息隊列裏,根據時間順序,時間值小的放前面,大的放後面.排序了.
轉載者補充:用鏈表實現了消息隊列,如果當前消息的when爲0或者小於消息隊列第一個消息的when,那麼就把該message作爲鏈表(消息隊列)的第一個元素,將mMessage指向它,即mMessage指向消息隊列的第一個元素。否則,將遍歷這個消息隊列鏈表,直到找到比當前message的when大的消息,並在之前插入。

Handler


Handler 對消息隊列的enqueueMessage做了包裝,這其實並不重要,因爲完全可以直接調用enqueueMessage來實現。重要的Handler在包裝enqueueMessage的同時,把Message的target設成了自己,即爲Message指定執行的行爲
  public boolean sendMessageAtTime(Message msg, long uptimeMillis)
    {
        boolean sent = false;
        MessageQueue queue = mQueue;
        if (queue != null) {
            msg.target = this;
            sent = queue.enqueueMessage(msg, uptimeMillis);
        }
這樣一來,當前Message被處理的時候就會調用Handler的dispatchMessage,而這個函數就會調用你要實現的虛函數handleMessage了。經過消息隊列代碼轉了一圈,還是調用了你自己的實現函數,但是同步操作變成了異步操作。

    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

當我們send消息時候,過程就很明朗了.

 

所有的發送消息的動作代碼都會跑這步.把消息按系統時間送到消息隊列裏.那發送進去了.什麼時候取出來呢?


Message放在消息隊列裏了,誰來一個一個的取出來處理呢?這時輪到Looper上場了,它的函數loop會一直循環處理隊列中的消息,直到遇上一個沒有target的Message:
    public static final void loop() {
        Looper me = myLooper();
        MessageQueue queue = me.mQueue;
        while (true) {
            Message msg = queue.next(); // might block
            //if (!me.mRun) {
            //    break;
            //}
            if (msg != null) {
                if (msg.target == null) {
                    // No target is a magic identifier for the quit message.
                    return;
                }
                if (me.mLogging!= null) me.mLogging.println(
                        ">>>>> Dispatching to " + msg.target + " "
                        + msg.callback + ": " + msg.what
                        );
                msg.target.dispatchMessage(msg);
                if (me.mLogging!= null) me.mLogging.println(
                        "<<<<< Finished to    " + msg.target + " "
                        + msg.callback);
                msg.recycle();
            }
        }
    }
由此可見:一個Looper總是和一個MessageQueue關聯起來的。

Thread


loop只是一個函數,它也需要別人來執行它。由於它一執行就會阻塞在那裏,所以一定需要一個線程來調用
  *  class LooperThread extends Thread {
  *      public Handler mHandler;
  *      
  *      public void run() {
  *          Looper.prepare();
  *          
  *          mHandler = new Handler() {
  *              public void handleMessage(Message msg) {
  *                  // process incoming messages here
  *              }
  *          };
  *          
  *          Looper.loop();
  *      }
  *  }
一個Looper也總是和一個Thread關聯起來的,不過不一定要創建新線程,可以是主線程的。Handler和Thread不是一一對應的,理論上,在一個LooperThread中,可以有任何多個Handler,每個消息都可以指定不同的Handler,因爲每個消息都可以有不同的行爲。

在創建Handler時並不會創建Thread,它只是取當前線程的Looper的MessageQueue:

    public Handler() {
        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 that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = null;
    }
通過myLooper取出當前線程的Looper:

    public static final Looper myLooper() {
        return (Looper)sThreadLocal.get();
    }
這個Looper是在Looper.prepare裏創建的:


    public static final void prepare() {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper());
    }


這個過程就很清楚了,UI線程啓動後,會不斷的從消息隊列取消息,當沒有消息時候,會
while (true) {
            Message msg = queue.next(); // might block
在這阻塞,直到有消息近來,然後通過 msg.target.dispatchMessage(msg);
來調用我們的handler註冊的HandleMessage來處理消息.

 

 

 

 轉自:http://www.wscxy.com/nuaa/article.asp?id=116

發佈了51 篇原創文章 · 獲贊 0 · 訪問量 4503
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章