Handler消息機制源碼詳解

轉載請註明出處:http://blog.csdn.net/Alpha58/article/details/71325699

前言

辭職後,最近又開始加入找工作的大隊伍中。不得不說今年找工作確實比以前難了。從幾個朋友說他們公司快倒閉的情況也驗證了這一點。最近面了2家,竟然都問到了Handler消息機制,雖然以前看過源碼,但是很久沒看,也忘得差不多了,總體的雖然都講的出,但是卻沒有徹底征服面試官,所以自己乾脆再總結一遍寫篇博客記錄下來好了。

正確閱讀源碼的姿勢

有些人閱讀源碼是力求每行代碼都要讀懂,我個人感覺這個方法是錯誤的。正確的方法是應該按平時你使用某個框架或者某個系統源碼的執行流程,抓重點去看。例如看Handler源碼,應該按照創建Handler-發送消息-處理消息的執行流程去看。並且要看最新版本的源碼。例如Android2.3與Android7.0的Handler源碼相差還是很大的,Android2.3中Handler的構造方法是沒有進行封裝的,Android7.0則進行了封裝。Android2.3中Handler回收消息的時候消息池大小判斷不嚴謹,但是高版本的就改過來了。

Handler的用法

handler實現機制:

1,Message對象,表示要傳遞的一個消息,內部使用鏈表數據結構實現一個消息池,用於重複利用,
避免大量創建消息對象,造成內存浪費
2,MessageQueue對象,存放消息對象的消息隊列,先進先出原則
3,Looper對象負責管理當前線程的消息隊列
4,handler對象負責把消息push到消息隊列中,以及接收Looper從消息隊列中取出的消息

handler的內存泄露問題(activity已經退出,而handler沒有退出,這樣就可能導致內存泄露)



Handler最常用的用法,即子線程完成耗時任務然後通知主線程更新UI,步驟爲:創建Handler-發送消息-處理消息。如下:

        //2,發送消息(子線程)
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = Message.obtain();
                message.what = 1;
                message.arg1 = 666;
                mHandler.sendMessage(message);
            }
        }).start();

        private static final int TAG = 1;
        //1,創建Handler(主線程)
        final Handler mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
            //3,處理消息
                if(msg.what == TAG){
                    tvText.setText(msg.arg1);
                }
            }
        };

開始閱讀源碼

現在我們就根據上面Handler使用的執行流程去解析源碼。

一、創建Handler—-Handler handler = new Handler();

有人問:爲什麼要在主線程中創建Handler,而不在子線程中創建呢?
因爲如果你在子線程創建Handler(如下),程序則會崩潰,並且會報錯誤:Can’t create handler inside thread that has not called Looper.prepare() ,翻譯爲:不能在沒有調用Looper.prepare() 的線程中創建Handler。

        new Thread(new Runnable() {  
            @Override  
            public void run() {  
                Handler handler = new Handler();  
            }  
        }).start();  

那如果在子線程中先調用一下Looper.prepare()呢,如下:

        new Thread(new Runnable() {  
            @Override  
            public void run() {  
                Looper.prepare()
                Handler handler = new Handler();  
            }  
        }).start();  

果然程序就能正常運行了。玄機就藏在源碼當中!

首先我們點擊我們創建的Handler進去源碼是這樣的:
【Handler.java】

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

然後再跟到這個構造方法裏,發現是走了有參構造
【Handler.java】

    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();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

可以看到,在第13行拋出的異常錯誤剛好就是我們剛剛上面報的錯誤!報錯的原因是mLooper對象爲空了,而mLooper對象則是在第10行代碼中獲取的,接下來我們點進去看看myLooper()這個方法,如下:
【Looper.java】

    public static Looper myLooper() {
        return sThreadLocal.get();
    }

可以看到,mLooper對象是通過sThreadLocal的get()方法獲取的。由此可以聯想到應該是有sThreadLocal.set()方法設置了mLooper對象。在當前類中查找,果然找到了。如下:
【Looper.java】

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

果然,子第5行sThreadLocal.set()方法正是在Looper.prepare()方法裏面。這段代碼比較簡單:首先判斷sThreadLocal中有沒有Looper對象,有就拋出異常,沒有則new一個新的Looper進去。這樣就得出結論:之前爲什麼會報如上錯誤了(不能在沒有調用Looper.prepare() 的線程中創建Handler)。

但是但是!爲什麼在主線程中創建Handler之前就不用調用Looper.prepare() 呢??
查找資料發現,Android程序的入口中,系統就默認幫我們調用了Looper.prepare()方法。
Android程序的入口在ActivityThread中的main()方法,ActivityThread這個類在Android studio中是看不到的,只能利用工具source insight來看。代碼如下:
【ActivityThread.java】

public static void main(String[] args) {  
    SamplingProfilerIntegration.start();  
    CloseGuard.setEnabled(false);  
    Environment.initForCurrentUser();  
    EventLogger.setReporter(new EventLoggingReporter());  
    Process.setArgV0("<pre-initialized>");  
    Looper.prepareMainLooper();  
    ActivityThread thread = new ActivityThread();  
    thread.attach(false);  
    if (sMainThreadHandler == null) {  
        sMainThreadHandler = thread.getHandler();  
    }  
    AsyncTask.init();  
    if (false) {  
        Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread"));  
    }  
    Looper.loop();  
    throw new RuntimeException("Main thread loop unexpectedly exited");  
} 

可以看到,在第7行調用了Looper.prepareMainLooper()方法,跟進去,prepareMainLooper()方法中又調用了prepare()方法
【ActivityThread.java】

public static final void prepareMainLooper() {  
    prepare();  
    setMainLooper(myLooper());  
    if (Process.supportsProcesses()) {  
        myLooper().mQueue.mQuitAllowed = false;  
    }  
} 

這樣就說明了在主線程中創建Handler同樣需要調用Looper.prepare()方法,只是這個方法系統已經幫我們調用了。

接下來Handler的有參構造就只剩下面三行了。

        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;

可以看到,一開始我們用的是無參構造,即傳入了一個null的Callback,async的值也是false,所以這裏就不考慮這2行,mQueue = mLooper.mQueue;則是獲取一個消息隊列MessageQueue。用於將所有收到的消息以隊列的形式進行排列,並提供入隊和出隊的方法。MessageQueue這個類是在Looper的構造函數中創建的,因此一個Looper也就對應了一個MessageQueue。

小總結:主線程中可以直接創建Handler,在子線程中需要先調用Looper.prepare()才能創建Handler。Handler的構造方法中主要是獲取輪詢器(即Looper對象)和消息隊列(即MessageQueue對象)。

二、發送消息—-mHandler.sendMessage(message);

點擊sendMessage()方法進去,如下:
【Handler.java】

    public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }

可以看到,調用了sendMessageDelayed()方法,點進去,如下:
【Handler.java】

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

可以看到,delayMillis < 0判斷是爲了防止用戶傳入的延遲參數爲負數。之後又調用了sendMessageAtTime()方法,點進去,如下:
【Handler.java】

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

可以看到,我們代碼中調用sendMessage()方法,最終就是走的sendMessageAtTime()方法。
而且其他發送消息的方法除了sendMessageAtFrontOfQueue(),例如sendMessageDelayed(),sendEmptyMessageDelayed()最終都會走sendMessageAtTime()方法。

sendMessageAtTime()方法接收兩個參數,其中msg參數就是我們發送的Message對象,而uptimeMillis參數則表示發送消息的時間,它的值等於自系統開機到當前時間的毫秒數再加上延遲時間,如果你調用的不是sendMessageDelayed()方法,延遲時間就爲0。第二行中的mQueue則是我們在創建Handler的時候獲取的消息隊列,然後將這三個參數都傳遞到enqueueMessage()方法中。
【Handler.java】

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

可以看到,enqueueMessage()方法中,首先將當前的Handler綁定給msg.target,接着調用MessageQueue的enqueueMessage()方法

MessageQueue的enqueueMessage()方法則是消息入隊的方法,點擊進去,如下:
【MessageQueue.java】

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

可以看到,代碼的第2行,當msg.target爲null時是直接拋異常的。代碼的第22-45行,首先判斷如果當前的消息隊列爲空,或者新添加的消息的執行時間when是0,或者新添加的消息的執行時間比消息隊列頭的消息的執行時間還早,就把消息添加到消息隊列頭(消息隊列按時間排序),否則就要找到合適的位置將當前消息添加到消息隊列。

小總結:發送消息的方法除了sendMessageAtFrontOfQueue(),例如sendMessage(),sendMessageDelayed()最終都會走sendMessageAtTime()方法。在sendMessageAtTime()方法中又調用MessageQueue的enqueueMessage()方法將所有的消息按時間來進行排序放在消息隊列中。

三、處理消息—-Looper.loop()

消息發送完成並且也已經入隊列了,接下來我們就是處理消息隊列中的消息了。首先要從隊列中取出消息,取消息主要靠輪詢器,看Looper.loop()方法
【Looper.java】

    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) {
                // 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
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            try {
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

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

可以看到,代碼第6行,從輪詢器中獲取消息隊列。接着通過一個死循環來把消息隊列中的消息逐個取出來。代碼第14行,通過MessageQueue的next()方法取出消息,當queue.next返回null時會退出消息循環。有消息則調用msg.target.dispatchMessage(msg),target就是發送message時跟message關聯的handler,Message被處理後會被調用recycleUnchecked()進行回收。

接下來看看MessageQueue的next()方法
【MessageQueue.java】

    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.
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }

        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 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) {
                        // 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;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }

                // Process the quit message now that all pending messages have been handled.
                if (mQuitting) {
                    dispose();
                    return null;
                }

                // If first time idle, then get the number of idlers to run.
                // Idle handles only run if the queue is empty or if the first message
                // in the queue (possibly a barrier) is due to be handled in the future.
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    // No idle handlers to run.  Loop and wait some more.
                    mBlocked = true;
                    continue;
                }

                if (mPendingIdleHandlers == null) {
                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
                }
                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
            }

            // Run the idle handlers.
            // We only ever reach this code block during the first iteration.
            for (int i = 0; i < pendingIdleHandlerCount; i++) {
                final IdleHandler idler = mPendingIdleHandlers[i];
                mPendingIdleHandlers[i] = null; // release the reference to the handler

                boolean keep = false;
                try {
                    keep = idler.queueIdle();
                } catch (Throwable t) {
                    Log.wtf(TAG, "IdleHandler threw exception", t);
                }

                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }

            // Reset the idle handler count to 0 so we do not run them again.
            pendingIdleHandlerCount = 0;

            // While calling an idle handler, a new message could have been delivered
            // so go back and look again for a pending message without waiting.
            nextPollTimeoutMillis = 0;
        }
    }

大概意思是如果當前MessageQueue中存在mMessages就將這個消息取出來,標記爲已用並從消息隊列中移除該消息,然後讓下一條消息成爲mMessages,否則就進入一個阻塞狀態,一直等到有新的消息入隊。

接下來看看Handler的dispatchMessage()方法
【Handler.java】

    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

可以看到,第2行進行判斷,如果msg.callback不爲空,則調用handleCallback(msg);方法,否則直接調用Handler的handleMessage()方法。這裏的handleMessage()方法是不是很熟悉?沒錯!就是我們在主線程中處理消息的handleMessage()方法。

接下來看看Handler的handleCallback()方法
【Handler.java】

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

可以看到,處理消息是在run方法中,即Runnable對象的run方法,也就是我們不用最常用的方法使用handle,而是以callback的方式使用。如下:

        //1,創建Handler(主線程)
         Handler mHandler = new Handler();

        new Thread(new Runnable() {
            @Override
            public void run() {
            //3,處理消息
                mMessage = Message.obtain(mHandler, new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("--------------callback的形式處理消息--------------" + mMessage.arg1);
                    }
                });
                mMessage.arg1 = 666;
                //2,發送消息
                mHandler.sendMessage(mMessage);

            }
        }).start();

其實Handler的post()方法源碼也是走了handleCallback()方法。自己點擊post()方法進去看看就知道了。

小總結:通過輪詢器的Looper.loop()方法中執行一個死循環把消息隊列中的消息逐個取出來。死循環中主要通過MessageQueue的next()方法取出消息,取出消息後通過調用Handler的dispatchMessage()方法最終在handleCallback(msg)或者handleMessage(msg)方法處理消息。

好了,Handler消息機制源碼終於走完了。希望這篇文章可以在面試當中幫到你們。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章