Handler源碼分析

Handler主要用于線程切換烟瞧,一個典型的應(yīng)用場景是:子線程通過Handler更新主線程UI
本文將從源碼上來介紹Handler的實現(xiàn)原理
CSDN地址:http://blog.csdn.net/myterabithia/article/details/58603639

Handler的工作流程

先看一張圖:

Handler工作流程

主要流程如下:

  • 構(gòu)造Message對象
  • 通過Handler將Message發(fā)送到MessageQueue
  • Looper從MessageQueue里取出Message對象
  • Looper調(diào)用Message對象里保存的Handler對象的dispatchMessage方法將Message的處理移交給Handler

那么Looper和MessageQueue是哪來的呢伞辛?看一下Handler的構(gòu)造方法:

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

        mLooper = Looper.myLooper();//獲取Handler所在線程的Looper币绩。
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;//獲取Looper里的MessageQueue
        mCallback = callback;
        mAsynchronous = async;
    }

如果mLooper為空則直接拋異常了,所以如果不是在主線程創(chuàng)建Handler之前一定要在子線程里調(diào)用Looper.prepare()準(zhǔn)備好一個Looper瘸羡。Looper.prepare()會調(diào)用Looper的構(gòu)造方法創(chuàng)建一個Looper漩仙,在Looper的構(gòu)造方法中又創(chuàng)建了一個MessageQueue。

下面通過源碼來看這幾個步驟是如何實現(xiàn)的

1.構(gòu)造Message對象

通過Handler對象構(gòu)造
通過Message的靜態(tài)方法構(gòu)造

或者犹赖,直接

Message message = new Message();

各種方式在使用效果上最后的差別不大队他,任選其一即可。

2.通過Handler將Message發(fā)送到MessageQueue

//Handler
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;//注意這一句峻村,將target對象指向當(dāng)前handler
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);//將Message入消息隊列
    }

左右的發(fā)送消息的方法最終都調(diào)用到了這個方法麸折,顧名思義,這個方法將Message對象添加到MessageQueue隊列,在入隊之前,將message的target對象賦值為當(dāng)前handler對象筷频,最后會通過這個target對象來處理這個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 {
                // 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.next
                prev.next = msg;
            }

            // We can assume mPtr != 0 because mQuitting is false.
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }

可以看到芭析,MessageQueue其實是一個單鏈表,所以很多操作都是單鏈表的操作捌浩。如果p==null(當(dāng)前隊列為空)或者when==0(通過sendMessageAtFrontOfQueue方法發(fā)送的消息)或者when<p.when的時就將此消息插入到隊的頭部放刨,否則按時間先后順序入隊,這里的時間是什么時間呢尸饺?看下面代碼,其實是SystemClock.uptimeMillis() + delayMillis助币,也就是當(dāng)前開機時間的毫秒數(shù)加上我們設(shè)置的延時浪听。

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

3.Looper從MessageQueue里取出Message對象

當(dāng)創(chuàng)建好Looper后,會調(diào)用Looper.loop()方法不斷的從MessageQueue里讀取Message眉菱,如果是主線程迹栓,那么Looper.loop()方法在系統(tǒng)創(chuàng)建進(jìn)程的時候就已經(jīng)調(diào)用過了,如果在子線程則需要自己調(diào)用俭缓。

//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.");
        }
        final MessageQueue queue = me.mQueue;

        ...省略

        for (;;) {
            //從隊列里取出消息
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

            ...省略

            try {
                //將msg的處理移交給Handler
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            ...省略 
        }
    }

Message msg = queue.next(); // might block 通過一個無限的for循環(huán)中通過MessageQueue.next()讀消息克伊,如果隊列沒有消息則阻塞酥郭。在next方法中,如果隊首的消息執(zhí)行時間還沒到愿吹,就設(shè)置一個等待時間不从,如果到了就從鏈表里取出來,然后返回犁跪。

//MessageQueue
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.
      ...
      for(;;){
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }

            nativePollOnce(ptr, nextPollTimeoutMillis);
            synchronized (this) {
      ...
                    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;
                    }
      ...
              }
      }
    }

4.調(diào)用Handler的dispatchMessage方法將Message的處理移交給Handler

在Loopermsg.target.dispatchMessage(msg)讓Handler去處理椿息,這里的target就是在調(diào)用Handler.的enqueueMessage方法時賦值得,忘記了可以去步驟2里再看一下坷衍。

至此寝优,處理流程又回到了Handler的dispatchMessage方法里,邏輯很簡單枫耳,一個細(xì)節(jié)要注意乏矾,如果mCallback不為空,是不會調(diào)用handleMessage迁杨,這里mCallback是在創(chuàng)建Handler的時候就傳進(jìn)來的妻熊,所以使用Handler處理消息,要么在創(chuàng)建Handler的時候傳入一個Callback仑最,要么重寫handleMessage方法扔役。

//Handler
    /**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

    private static void handleCallback(Message message) {
        message.callback.run();
    }

    /**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(Message msg) {
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市警医,隨后出現(xiàn)的幾起案子亿胸,更是在濱河造成了極大的恐慌,老刑警劉巖预皇,帶你破解...
    沈念sama閱讀 218,525評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件侈玄,死亡現(xiàn)場離奇詭異,居然都是意外死亡吟温,警方通過查閱死者的電腦和手機序仙,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,203評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來鲁豪,“玉大人潘悼,你說我怎么就攤上這事∨老穑” “怎么了治唤?”我有些...
    開封第一講書人閱讀 164,862評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長糙申。 經(jīng)常有香客問我宾添,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,728評論 1 294
  • 正文 為了忘掉前任缕陕,我火速辦了婚禮粱锐,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘扛邑。我一直安慰自己怜浅,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,743評論 6 392
  • 文/花漫 我一把揭開白布鹿榜。 她就那樣靜靜地躺著海雪,像睡著了一般。 火紅的嫁衣襯著肌膚如雪舱殿。 梳的紋絲不亂的頭發(fā)上奥裸,一...
    開封第一講書人閱讀 51,590評論 1 305
  • 那天,我揣著相機與錄音沪袭,去河邊找鬼湾宙。 笑死,一個胖子當(dāng)著我的面吹牛冈绊,可吹牛的內(nèi)容都是我干的侠鳄。 我是一名探鬼主播,決...
    沈念sama閱讀 40,330評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼死宣,長吁一口氣:“原來是場噩夢啊……” “哼伟恶!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起毅该,我...
    開封第一講書人閱讀 39,244評論 0 276
  • 序言:老撾萬榮一對情侶失蹤博秫,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后眶掌,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體挡育,經(jīng)...
    沈念sama閱讀 45,693評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,885評論 3 336
  • 正文 我和宋清朗相戀三年朴爬,在試婚紗的時候發(fā)現(xiàn)自己被綠了即寒。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,001評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡召噩,死狀恐怖母赵,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情蚣常,我是刑警寧澤市咽,帶...
    沈念sama閱讀 35,723評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站抵蚊,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜贞绳,卻給世界環(huán)境...
    茶點故事閱讀 41,343評論 3 330
  • 文/蒙蒙 一谷醉、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧冈闭,春花似錦俱尼、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,919評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至耍休,卻和暖如春刃永,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背羊精。 一陣腳步聲響...
    開封第一講書人閱讀 33,042評論 1 270
  • 我被黑心中介騙來泰國打工斯够, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人喧锦。 一個月前我還...
    沈念sama閱讀 48,191評論 3 370
  • 正文 我出身青樓读规,卻偏偏與公主長得像,于是被迫代替她去往敵國和親燃少。 傳聞我的和親對象是個殘疾皇子束亏,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,955評論 2 355

推薦閱讀更多精彩內(nèi)容