android Looper、MessageQueue、Handler原理源碼解析

前言

Handler是一項很重要的技術,它的使用地方很多,使用的時候我們很多是創建一個Handler對象,重寫handleMessage()方法,但原理是什么,還是需要認真研究下~

一:關聯類的名稱以及作用

Message:消息,其中包含了消息ID,消息處理對象以及處理的數據等,由MessageQueue統一列隊,終由Handler處理
Handler::處理者,負責Message的發送及處理。使用Handler時,需要實現handleMessage(Message msg)方法來對特定的Message進行處理,例如更新UI等
MessageQueue:消息隊列,用來存放Handler發送過來的消息,并按照FIFO規則(先進先出)執行
Looper :讓MessageQueue動起來

關系圖

二:從ActivityThread的main()方法說起

ActivityThread的main()方法是程序的入口,我們看下關于Looper、Handler的這部分做了些什么

...省略
        //創建一個主線程Looper對象保存在TheadLocal中
        Looper.prepareMainLooper();
...省略
        ActivityThread thread = new ActivityThread();
        thread.attach(false, startSeq);
        //創建了一個主線程Handler對象
        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }
        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
       //開始從MessageQueue中抽取Message
        Looper.loop();

在開始分析之前,我們先看下Looper類對象的成員

public final class Looper {
    private static final String TAG = "Looper";

   //靜態的ThreadLocal<Looper>對象
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
    //主線程Looper對象
    private static Looper sMainLooper;  // guarded by Looper.class
    //當前線程消息隊列
    final MessageQueue mQueue;
    //當前線程
    final Thread mThread;

其中sMainLooper是在prepareMainLooper中初始化賦值
mQueue和mThread是在構造函數中初始化的

    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

關于ThreadLocal,大家可以參考這兩篇文章:
ThreadLocal是什么
ThreadLocal和synchronized區別

Looper.prepareMainLooper()調用了prepare()方法,然對sMainLooper 對象判空,如果不為空,那么拋出異常

    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

可以看到,prepare()方法把當前Looper存放到了ThreadLocal中

    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));
    }

Looper.looper()方法從Messagequeue中獲取Message,然后執行msg.target.dispatchMessage(msg),把消息分發出去

 public static void loop() {
        //從ThreadLocal中獲取到當前線程的Looper
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        //獲取當前Looper中的MessageQueque
        final MessageQueue queue = me.mQueue;
...省略
        //開始循環
        for (;;) {
            //鏈表中獲取到一個Message
            Message msg = queue.next(); // might block
            if (msg == null) {
...省略
            try {
                //Meesage的target(該對象就是Message持有的Handler對象)
                msg.target.dispatchMessage(msg);
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } finally {
...省略  
            //對已經分發的消息進行回收操作,實際上是把Message的對象制空,標識,參數清零等操作
            msg.recycleUnchecked();
        }
    }

關于dispatchMessage()方法,稍后具體分析
通過以上流程,我們大致了解了這幾個東西到底是干些什么的

三:關于Handler

我們先從Handler.class的成員變量、構造方法開始看起
以下是Handler中比較重要的成員變量

    final Looper mLooper;
    final MessageQueue mQueue;
    final Callback mCallback;
    final boolean mAsynchronous;
    IMessenger mMessenger;

來看下構造函數
構造函數有很多個,但最終都是調用到這個構造函數

    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,給當前線程的Looper賦值
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        //獲取到當前Looper的MessageQueue,并指向當前Handler的queue
        mQueue = mLooper.mQueue;
        //給回調這個成員變量賦值
        mCallback = callback;
        mAsynchronous = async;
    }

我們來看下剛才說到的dispatchMessage()方法

    public void dispatchMessage(Message msg) {
        //如果message對象的CallBack不為null,那么執行messageCallback
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            //如果Handler類構造函數傳入的callBack不為null,那么執行這個callBack
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            //如果都不滿足,那么執行這個函數
            handleMessage(msg);
        }
    }

那么handlerMessage()是什么我們不用過多解釋了,繼承一個Handler都要重寫的方法,最后的回調,也是上面的邏輯


四:怎么發送一個Message

我們還是先來看下Message這個類的重要成員

    /*package*/ int flags;
    /*package*/ long when;
    /*package*/ Bundle data;
    /*package* handler對象/ Handler target;
    /*package* 回調/ Runnable callback;
    // sometimes we store linked lists of these things
    /*package* 指針/ Message next;
    /** @hide * 類鎖/
    public static final Object sPoolSync = new Object();

一般發送Message有兩種方式
第一種:創建一個Message

        Message message = new Message();
        message.what = 1;
        mHandler.sendMessage(message);

第二種:獲取一個Message

        Message message = mHandler.obtainMessage();
        message.what = 1;
        message.sendToTarget();

這兩種的區別就是:前者是新創建一個Message加入MessageQueue,后者是從整個Messge池中返回一個新的Message實例

不論是sendMessage或者sendToTarget最后都會執行到Handler類的enqueueMessage方法,這個方法給Message的Handler對象target賦值,然后執行MessageQueue的enqueueMessage方法

    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

五:MessageQueue的入隊和出隊

enqueueMessage()方法也就是我們常說的”入隊“,把當前這個Message放入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 {
                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;
    }

先看下新消息需要放到隊頭的情況:p == null || when == 0 || when < p.when。即隊列為空,或者新消息需要立即處理,或者新消息處理的事件比隊頭消息更早被處理。這時只要讓新消息的next指向當前隊頭,讓mMessages指向新消息即可完成插入操作。
除了上述三種情況就需要遍歷隊列來確定新消息位置了,下面結合示意圖來說明。
假設當前消息隊列如下


開始遍歷:p向隊尾移,引入prev指向p上一個元素


假設此時p所指消息的when比新消息晚,則新消息位置在prev與p中間


最后便是調用native方法來喚醒

Looper.loop()中調用到MessageQueue的next()方法是我們常說的出隊

    Message next() {
...省略
        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        for (;;) {
...省略
            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 {
                            //取出一個Message
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }
...省略
        }
    }

可以看到這里就成功取出了一個Message
至此,關于Looper、MessageQueue、Handler就分析的差不多了

End

In the bleak midwinter...--《Peaky fucking Blinders》

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,428評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,024評論 3 413
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,285評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,548評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,328評論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,878評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,971評論 3 439
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,098評論 0 286
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,616評論 1 331
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,554評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,725評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,243評論 5 355
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 43,971評論 3 345
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,361評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,613評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,339評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,695評論 2 370

推薦閱讀更多精彩內容