Android消息機制(Handler、Looper、MessageQueue)

本文內容基于《Android開發藝術探索》,有興趣的同學可以買本書,值得一看。
圖來自[Android消息處理探秘](http://blog.csdn.net/cloudwu007/article/details/6825085)
圖來自[Android消息處理探秘](http://blog.csdn.net/cloudwu007/article/details/6825085)

1.Handler工作原理

Handler主要任務是發送和接收處理消息,發送消息可以通過post或者send相關方法來實現,我們先來看一下Handler類中postsend方式的代碼實現

public final boolean post(Runnable r){
   return  sendMessageDelayed(getPostMessage(r), 0);
}

private static Message getPostMessage(Runnable r) {
    Message m = Message.obtain();
    m.callback = r;
    return m;
}

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);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}

我們可以發現post還是通過調用send方式來發送消息的,發送消息只是通過queue.enqueueMessage(msg, uptimeMillis);向消息隊列中插入一條消息,MessageQueue會把消息交給LooperLooper再把消息交給HandlerdispatchMessage方法處理,具體過程會在下面分析,現在我們來看一下dispatchMessage的實現

public void dispatchMessage(Message msg) {
    if (msg.callback != null) { //如果消息已設置callback,則調用該callback函數 
        handleCallback(msg);
    } else {
        if (mCallback != null) { //如果Handler已設置callback,則調用該callback處理消息 
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg); //默認為空函數,用戶可重載處理自定義消息  
    }
}

從上面代碼可以看出,首先檢查Messagecallback是否為null,不為null則交給handleCallback方法執行,Messagecallback是一個Runnable對象,實際上就是post傳入的Runable對象(可查看HandlergetPostMessage()方法),handleCallback中直接調用callbackrun方法,handleCallback實現如下

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

如果msg.callback為null,即消息是通過send方式發送的,則會再判斷mCallback是否為null,不為null則調用mCallbackhandleMessage方法,CallbackHandler類中的一個接口,我們可以在中通過Handler handler = new Handler(callback)來創建handler并實現Callback來處理消息。

public interface Callback {
    public boolean handleMessage(Message msg);
}

如果mCallbacknull則會調用HandlerhandleMessage方法來處理消息,這是我們最常用的方式。

2.MessageQueue工作原理

接下來分析一下MessageQueue的工作原理,MessageQueue中通過enqueueMessage()方法來插入消息,通過next()方法來取出數據。enqueueMessage方法實現如下

boolean enqueueMessage(Message msg, long when) {
    ...
    synchronized (this) {
        ...
        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; //mBlocked=true表示線程已被掛起
        } 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.next為空的Message對象來插入消息,接下來看看next方法的實現

Message next() {
    ...
    int pendingIdleHandlerCount = -1; //空閑的handler個數。只有在第一次循環的時候值為-1。
    int nextPollTimeoutMillis = 0; //下次輪詢時間,如果當前消息隊列中沒有消息,它要等待,為0,表示不等待,不為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) { //判斷時間是否可以處理這個消息,如果符合條件,把消息返回傳給looper處理。否則,算出需要等待時間,等待到該時間,然后執行
                    // 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 (false) Log.v("MessageQueue", "Returning message: " + msg);
                    return msg;
                }
            } else {
                // 如果msg為null則吧nextPollTimeoutMillis賦值為-1,表示等到下一個消息
                nextPollTimeoutMillis = -1;
            }
            ...
        }
        ...
    }
}

可以看出next方法中有一個無限循環的代碼塊在獲取message,如果有新消息則將詳細從鏈表中移除并返回這條消息,如果消息隊列中沒有消息那么next方法會一直阻塞在這里。

3.Looper工作原理

Looper主要作用是循環從MessageQueue取出消息處理,如果沒有新的消息則會阻塞,它的構造方法中會創建一個MessageQueue對象,并獲取當前現成對象的引用

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

Handler的創建必須在含有Looper的線程中,否則會報錯,Looper的創建可調用Looper.prepare(),主線程中會在ActivityThreadmain()方法中調用Looper.prepareMainLooper()方法為主線程創建Looper對象,所以在主線程中創建Handler對象是不需要我們顯示的創建Looper對象,在工作線程中創建線程如下所示

new Thread() {
    @Override
    public void run() {
        Looper.prepare();  //創建Looper對象
        Handler handler = new Handler(); //創建Handler對象
        Looper.loop(); //開啟循環
    }
}

只有點用loop()方法消息循環才會起作用,loop方法的實現如下

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;
    // 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();
    for (;;) {
        Message msg = queue.next(); // might block
        if (msg == null) { //只有queue.next()返回為null才會跳出循環,MessageQueue只有退出next才會返回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);
        }
        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.recycleUnchecked();
    }
}

loop()中是一個死循環,只有queue.next()返回為null才會跳出循環,MessageQueue只有退出next()才會返回null,否則有新消息則會返回消息,沒有消息則會阻塞。獲取到新消息會掉用msg.target.dispatchMessage(msg);來處理消息,msg.target是發送這條消息的Handler對象,這樣就達到了誰發送的消息誰處理的效果。

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

推薦閱讀更多精彩內容