android消息機制

1、消息機制概述

一、消息機制的簡介

在Android中使用消息機制,最早能想到的就是Handler。git

Handler是Android消息機制的上層接口。Handler的使用過程很簡單,經過它能夠輕鬆地將一個任務切換到Handler所在的線程中去執行。一般狀況下,Handler的使用場景是更新UI。github

即在子線程彙總,進行耗時操做,執行完後發送消息通知主線程更新UI。bash

這即是消息機制的典型應用場景。數據結構


二、消息機制的模型

消息機制主要包含:MessageQueue、Handler和Looper這三個部分,以及Message架構

  • 「Message」:須要傳遞的消息,能夠傳遞數據;
  • 「MessageQueue」:消息隊列,可是它的內部實現機制是經過單鏈表的數據結構來維護消息對壘,由於單鏈表在插入和刪除上比較有優點。主要功能向消息池投遞消息(MessageQueue.enqueueMessage())和取走消息池的消息(MessageQueue.next()
  • 「Handler」:消息複製類,主要功能向消息池發送各類消息事件(Handler.sendMessage())和處理對應消息事件(Handler.handleMessage())
  • Looper:不斷循環執行(Looper.loop()),從MessageQueue中讀取消息,按分發機制將消息分發給目標處理者。


三、消息機制的架構

消息機制的運行流程:異步

  • 在子線程執行完耗時操做,經過Handler.sendMessage()Handler.postMessage()發送消息,MessageQueue.enqueueMessage()方法將消息添加到消息隊列中。當經過Looper.loop()開啓循環後,會不斷地從線程池中讀取消息,即調用MessageQueue.next(),然後調用目標Handler(即發送該消息的Handler)的dispatchMessage()方法傳遞消息,而後返回到Handler所在的線程(能夠是主線程也能夠是子線程),目標Handler收到消息,調用handleMessage()方法,接受消息,處理消息。

圖片來源async


MessageQueue、Handler和Looper三者之間的關係:每一個線程中只能存在一個Looper一個Looper是保存在ThreadLocal中的。主線程(UI線程)已經建立了一個Looper,因此在主線程中不須要再建立Looper,可是在其餘線程中須要建立Looper。ide

每一個線程能夠有多個Handler,即一個Looper能夠處理多個Handler的消息。Looper中維護一個MessageQueue,來維護消息對壘,消息隊列的Message能夠來自不一樣的Handler。oop


2、消息機制的源碼分析

一、Looper

要想使用消息機制,首先要建立一個Looper源碼分析

  • 初始化Looper

無參數狀況下,默認調用prepare(true):表示的是這個Looper能夠退出,而對於false的狀況則表示當前Looper不能夠退出。

public static void prepare() {
        prepare(true);
}

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,並報錯在ThreadLocal中。

其中ThreadLocal是線程本地存儲區(Thread Local Storage,TLS),每一個線程都有本身的私有的本地存儲區域,不一樣線程之間彼此不能訪問對方的TLS區域。


  • 開啓Looper

public static void loop() {
    final Looper me = myLooper();  //獲取TLS存儲的Looper對象 
    if (me == null) {
        throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
    final MessageQueue queue = me.mQueue;  //獲取Looper對象中的消息隊列

    Binder.clearCallingIdentity();
    final long ident = Binder.clearCallingIdentity();

    for (;;) { //進入loop的主循環方法
        Message msg = queue.next(); //可能會阻塞,由於next()方法可能會無限循環
        if (msg == null) { //消息爲空,則退出循環
            return;
        }

        Printer logging = me.mLogging;  //默認爲null,可經過setMessageLogging()方法來指定輸出,用於debug功能
        if (logging != null) {
            logging.println(">>>>> Dispatching to " + msg.target + " " +
                    msg.callback + ": " + msg.what);
        }
        msg.target.dispatchMessage(msg); //獲取msg的目標Handler,而後用於分發Message 
        if (logging != null) {
            logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
        }

        final long newIdent = Binder.clearCallingIdentity();
        if (ident != newIdent) {
         
        }
        msg.recycleUnchecked(); 
    }
}複製代碼

loop()進入循環模式,不斷重複下面的操做,直到消息爲空時退出循環;

讀取MessageQueue的下一條Message(關於next(),後面詳細介紹);

把Message分發給對應的target(該target,即爲handler

當next()取出下一條消息時,若隊列中沒有消息時,則next()會無限循環,產生阻塞。等待MessageQueue中加入消息,而後從新喚醒

主線程中不須要本身建立Looper,由於在程序啓動時,系統已經幫咱們自動調用了Looper.prepare()方法。查看ActivityThread中的main()方法,以下:

public static void main(String[] args) {
    ..................
    Looper.prepareMainLooper();
    ..................
    Looper.loop();
    ..................
}複製代碼

其中「prepareMainLooper()」方法會調用prepare(false)


二、Handler

  • 建立Handler

public Handler() {
    this(null, false);
}

public Handler(Callback callback, boolean async) {
   .................................
    //必須先執行Looper.prepare(),才能獲取Looper對象,不然爲null.
    mLooper = Looper.myLooper();  //從當前線程的TLS中獲取Looper對象
    if (mLooper == null) {
        throw new RuntimeException("");
    }
    mQueue = mLooper.mQueue; //消息隊列,來自Looper對象
    mCallback = callback;  //回調方法
    mAsynchronous = async; //設置消息是否爲異步處理方式
}複製代碼

對於Handler的無參構造方法,默認採用當前線程TLS中的Looper對象,而且callback()回調方法爲null,且消息爲同步處理方法。只要執行的Looper.prepare方法,那麼即可以得到有效的Looper對象。


三、發送消息

發送消息有幾種 方法,但歸根到底都是調用了sendMessageAtTime()方法

在子線程中經過Handler的post()方法或send()方法發送消息,最終都會調用sendMessageAtTime()方法

  • post()方法

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

public final boolean postAtTime(Runnable r, long uptimeMillis){
   return sendMessageAtTime(getPostMessage(r), uptimeMillis);
}

 public final boolean postAtTime(Runnable r, Object token, long uptimeMillis){
    return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
}

 public final boolean postDelayed(Runnable r, long delayMillis){
    return sendMessageDelayed(getPostMessage(r), delayMillis);
}

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

就連子線程中調用Activity中的runOnUiThread()中更新UI,其實也是發送消息通知主線程更新UI,最終也會調用sendMessageAtTime()方法。

public final void runOnUiThread(Runnable action) {
    if (Thread.currentThread() != mUiThread) {
        mHandler.post(action);
    } else {
        action.run();
    }
}複製代碼

若是當前線程不等於UI線程(主線程),就去調用Handler的post()方法,最終也會調用sendMessageAtTime()方法。不然就直接調用Runnable對象的run()方法。


sendMessageAtTime()源碼:

public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
    //其中mQueue是消息隊列,從Looper中獲取的
    MessageQueue queue = mQueue;
    if (queue == null) {
        RuntimeException e = new RuntimeException(
                this + " sendMessageAtTime() called with no mQueue");
        Log.w("Looper", e.getMessage(), e);
        return false;
    }
    //調用enqueueMessage方法
    return enqueueMessage(queue, msg, uptimeMillis);
}複製代碼

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    //調用MessageQueue的enqueueMessage方法
    return queue.enqueueMessage(msg, uptimeMillis);
}複製代碼

能夠看到SendMessageAtTime()方法的做用很簡單,就是調用MessageQueue的enqueueMessage()方法,往消息隊列中添加一個消息。

下面來看enqueueMessage()方法的具體執行邏輯。

enqueueMessage()

boolean enqueueMessage(Message msg, long when) {
    // 每個Message必須有一個target
    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) {  //正在退出時,回收msg,加入到消息池
            msg.recycle();
            return false;
        }
        msg.markInUse();
        msg.when = when;
        Message p = mMessages;
        boolean needWake;
        if (p == null || when == 0 || when < p.when) {
            //p爲null(表明MessageQueue沒有消息) 或者msg的觸發時間是隊列中最先的, 則進入該該分支
            msg.next = p;
            mMessages = msg;
            needWake = mBlocked; 
        } else {
            //將消息按時間順序插入到MessageQueue。通常地,不須要喚醒事件隊列,除非
            //消息隊頭存在barrier,而且同時Message是隊列中最先的異步消息。
            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;
            prev.next = msg;
        }
        if (needWake) {
            nativeWake(mPtr);
        }
    }
    return true;
}複製代碼

MessageQueue是按照Message觸發事件前後順序排序的,隊頭的消息是將要最先觸發的消息。當有消息須要加入消息隊列時,會從隊列頭開始遍歷,直到找到消息應該插入的合適位置,以保證全部消息的時間順序。


四、獲取消息

當發送了消息後,在MessageQueue維護了消息隊列,而後在Looper中經過loop()方法,不斷地獲取消息。上面對loop()方法進行了介紹,其中最重要的是調用了queue.next()方法,經過該方法來提取下一條信息。下面咱們來看next()方法的具體流程。

  • next()

Message next() {
    final long ptr = mPtr;
    if (ptr == 0) { //當消息循環已經退出,則直接返回
        return null;
    }
    int pendingIdleHandlerCount = -1; // 循環迭代的首次爲-1
    int nextPollTimeoutMillis = 0;
    for (;;) {
        if (nextPollTimeoutMillis != 0) {
            Binder.flushPendingCommands();
        }
        //阻塞操做,當等待nextPollTimeoutMillis時長,或者消息隊列被喚醒,都會返回
        nativePollOnce(ptr, nextPollTimeoutMillis);
        synchronized (this) {
            final long now = SystemClock.uptimeMillis();
            Message prevMsg = null;
            Message msg = mMessages;
            if (msg != null && msg.target == null) {
                //當消息Handler爲空時,查詢MessageQueue中的下一條異步消息msg,爲空則退出循環。
                do {
                    prevMsg = msg;
                    msg = msg.next;
                } while (msg != null && !msg.isAsynchronous());
            }
            if (msg != null) {
                if (now < msg.when) {
                    //當異步消息觸發時間大於當前時間,則設置下一次輪詢的超時時長
                    nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                } else {
                    // 獲取一條消息,並返回
                    mBlocked = false;
                    if (prevMsg != null) {
                        prevMsg.next = msg.next;
                    } else {
                        mMessages = msg.next;
                    }
                    msg.next = null;
                    //設置消息的使用狀態,即flags |= FLAG_IN_USE
                    msg.markInUse();
                    return msg;   //成功地獲取MessageQueue中的下一條即將要執行的消息
                }
            } else {
                //沒有消息
                nextPollTimeoutMillis = -1;
            }
         //消息正在退出,返回null
            if (mQuitting) {
                dispose();
                return null;
            }
            ...............................
    }
}複製代碼

nativePossOnce()是阻塞操做,其中nextPollTimeoutMillis表明下一個消息到來前,還須要等待的時長;當nextPollTimeoutMillis=-1時,表示消息隊列中無消息,會一直等待下去

能夠看出next()方法根據消息的觸發事件,獲取下一條須要執行的消息隊列中消息爲空時,則會進行阻塞操做。


五、分發信息

在loop()方法中,獲取到下一條信息後,執行msg.target.dispatchMessage(msg),來分發消息到目標Handler對象。

  • dispatchMessage()

public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        //當Message存在回調方法,回調msg.callback.run()方法;
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            //當Handler存在Callback成員變量時,回調方法handleMessage();
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        //Handler自身的回調方法handleMessage()
        handleMessage(msg);
    }
}複製代碼

private static void handleCallback(Message message) {
    message.callback.run();
}複製代碼

分發消息流程:

當Message的msg.callback不爲空時,則回調方法msg.callback.run()

當Handler的mCallback不爲空時,則回調方法mCallback.handleMessage(msg);

最後調用Handler自身的回調方法handleMessage(),該方法默認爲空,Handler子類經過覆蓋該方法來完成具體的邏輯

消息分發的優先級:

Message的回調方法:message.callback.run(),優先級最高。

Handler中Callback的回調方法:Handler.mCallback.handleMessage(msg),優先級僅次於message.callback.run()

Handler的默認方法:Handler.handleMessage(),優先級最低

對於不少狀況下,消息分發後的處理方法時第3種,即Handler.handleMessage(),通常地每每經過重寫該方法從而實現本身的業務邏輯。

相關文章
相關標籤/搜索