Handler知識收集整理-1

我是代碼搬運工,不能僅僅只是搬運,還要整理一下。

1. Handler組成部分:

  1. Message:消息
  2. Handler:消息的發(fā)起者
  3. Looper:消息的遍歷者
  4. MessageQueue:消息隊列
Handler流程圖

2. Handler的使用流程:

使用Handler之前的準備工作有三步:

  1. 調用Looper.prepare()(主線程不需要調這個,因為APP創(chuàng)建時,main方法里面已經幫我們創(chuàng)建了)

  2. 創(chuàng)建Handler對象,重寫handleMessage方法(你可以不重寫),用于處理message回調的

  3. 調用Looper.loop()

其中:

Looper.prepare()的作用主要有以下三點:

  1. 創(chuàng)建Looper對象

  2. 創(chuàng)建MessageQueue對象,并讓Looper對象持有

  3. 讓Looper對象持有當前線程


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

    private static void prepare(boolean quitAllowed) {
        // 規(guī)定了一個線程只有一個Looper,也就是一個線程只能調用一次Looper.prepare()
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        // 如果當前線程沒有Looper,那么就創(chuàng)建一個,存到sThreadLocal中
        sThreadLocal.set(new Looper(quitAllowed));
    }
            
    

從上面的代碼可以看出,一個線程最多只有一個Looper對象。當沒有Looper對象時,去創(chuàng)建一個Looper,并存放到sThreadLocal中


    private Looper(boolean quitAllowed) {
        // 創(chuàng)建了MessageQueue,并供Looper持有
        mQueue = new MessageQueue(quitAllowed);
        // 讓Looper持有當前線程對象
        mThread = Thread.currentThread();
    }
    

這里主要就是創(chuàng)建了消息隊列MessageQueue,并讓它供Looper持有,因為一個線程最多只有一個Looper對象,所以一個線程最多也只有一個消息隊列。然后再把當前線程賦值給mThread。

Handler使用流程:

  1. Handler.post(或sendMessage): handler發(fā)送消息msg

  2. MessageQueue.enqueueMessage(msg, uptimeMillis):msg加入message隊列

  3. loop() 方法中從MessageQue中取出msg,然后回調handler的dispatchMessage,然后執(zhí)行callback(如果有的話) 或 handleMessage。(注意,loop方法是一直在循環(huán)的,從前面的handler準備工作開始就已經一直在運行了)

如圖所示:

ThreadLocal

3. Handler具體源碼:

3.1. Message獲取

Message的獲取方式有兩種:

1. Message msg = new Message();

2. Message msg = Message.obtain();

從全局池返回一個新的消息實例。允許我們在許多情況下避免分配新對象。

    /**
     * Return a new Message instance from the global pool.      Allows us to
     * avoid allocating new objects in many cases.
     */
    public static Message obtain() {
        synchronized (sPoolSync) {
            if (sPool != null) {
                Message m = sPool;
                sPool = m.next;
                m.next = null;
                m.flags = 0; // clear in-use flag
                sPoolSize--;
                return m;
            }
        }
        return new Message();
    }

復用之前用過的 Message 對象,這里實際上是用到了一種享元設計模式,這種設計模式最大的特點就是復用對象,避免重復創(chuàng)建導致的內存浪費

    /**
     * Recycles a Message that may be in-use.
     * Used internally by the MessageQueue and Looper when disposing of queued Messages.
     */
    void recycleUnchecked() {
        // Mark the message as in use while it remains in the recycled object pool.
        // Clear out all other details.
        flags = FLAG_IN_USE;
        what = 0;
        arg1 = 0;
        arg2 = 0;
        obj = null;
        replyTo = null;
        sendingUid = -1;
        when = 0;
        target = null;
        callback = null;
        data = null;

        synchronized (sPoolSync) {
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
    }
    
每次message使用完了之后會調用recycleUnchecked回收message,方便下次使用

Message核心的信息有這些:

    public int what;

    public int arg1;

    public int arg2;

    public Object obj;

    /*package*/ int flags;

    /*package*/ long when;

    /*package*/ Bundle data;

    /*package*/ Handler target;

    /*package*/ Runnable callback;

    // sometimes we store linked lists of these things
    /*package*/ Message next;

3.2 Handler的發(fā)送消息

handler提供的發(fā)送消息的方法有很多,大致分為兩類:

  1. Handler.post(xxx);
  2. Handler.sendMessage(xxx);

雖然方法很多,但最終都會回調到這個方法:

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

這個方法就是將消息添加到隊列里。

3.3 MessageQueue的添加消息

enqueueMessage(添加消息)

源碼分析如下:


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

            // 標記這個 Message 已經被使用
            msg.markInUse();
            msg.when = when;
            // 這是這個消息隊列里的目前第一條待處理的消息(當前消息隊列的頭部,有可能為空)
            Message p = mMessages;
            boolean needWake;
            // 如果目前隊列里沒有消息 或 這條消息msg需要立即執(zhí)行 或 這條消息msg的延遲時間比隊列里的第一條待處理的消息還要早的話,走這個邏輯
            if (p == null || when == 0 || when < p.when) {
                 // 把消息插入到消息隊列的頭部
                // 最新的消息,如果已經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循環(huán)的作用就是找出msg應該放置的正確位置
                // 經過下面這個for循環(huán),最終會找出msg的前一個消息是prev,后一個消息是p
                for (;;) {
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                // 上面的for循環(huán)得出的結果就是:msg應該在prev后面,在p前面
                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;
    }

上面就是handler發(fā)送消息過來,然后添加到消息隊列里。

下面就開始講添加消息到隊列之后的事情:取消息,然后執(zhí)行。

3.4 Loop的取消息

前面已經說到,在使用Handler之前有三步準備工作:

  1. 調用Looper.prepare()(主線程不需要調這個,因為APP創(chuàng)建時,main方法里面已經幫我們創(chuàng)建了)

  2. 創(chuàng)建Handler對象,重寫handleMessage方法(你可以不重寫),用于處理message回調的

  3. 調用Looper.loop()

其中第三步的Looper.loop()的作用就是不斷的從MessageQueue隊列里取消息,也就是說,在使用handler發(fā)消息之前,就已經開始了loop的循環(huán)了。

loop()源碼比較長,這里摘取核心部分:


    /**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the loop.
     *
     * 大概的翻譯就是:在這個線程中運行消息隊列。確保調用{@link #quit()}來結束循環(huán)。
     *
     */
    public static void loop() {
    
        ····
        ····

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

            ·····
            ·····
            ·····
           
            try {
                // msg.target是Message在創(chuàng)建時傳入的Handler,也就是發(fā)送這條消息的發(fā)送者handler
                // 所以最終會回調到handler的dispatchMessage方法
                
                msg.target.dispatchMessage(msg);
                
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            
           
           ····
           ····
            
            // 回收msg,重復利用
            msg.recycleUnchecked();
        }
    }

loop()的作用就是不斷的從MessageQueue里取消息,然后回調到dispatchMessage里,再看看dispatchMessage里干啥了


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

所以最終會執(zhí)行callback或handleMessage。

簡書對文章長度有限制,剩下的放到下一篇文章:

(Handler知識收集整理-2)

http://www.itdecent.cn/p/9d3aa5a06661

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容