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》

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容