Android原始碼學習之handler

散人丶發表於2019-01-12

前言

想必handler這個東西已經被討論的天花亂墜了,也經常被我們用在實際開發中,但是其中很多細節知識還是值得我們去學習深究的,比如,每個執行緒是怎麼保證只有一個looper的,Message訊息佇列是通過什麼實現的,handler.sendMessage()和handler.post()有什麼區別,handler是怎麼實現跨執行緒的訊息傳遞等等。本篇也僅在原始碼的角度來探討下其中的問題,水平有限,錯誤請及時指出。

文章可能比較長,請耐心閱讀~

1.基本用法

private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            //doSomething
            super.handleMessage(msg);
        }
    };
複製程式碼
Message message = Message.obtain();
message.what=1;
message.obj=new Object();
mHandler.sendMessage(message);
複製程式碼

第二種就是post方式

new Handler().post(new Runnable() {
            @Override
            public void run() {
                //doSomething
            }
        });
複製程式碼

這裡涉及的記憶體洩漏,先暫不討論,我們先來看看Handler最基本的構造方法有哪些:

  • Handler()
  • Handler(Callback callback)
  • Handler(Looper looper)
  • Handler(Looper looper, Callback callback)
  • Handler(boolean async)
  • Handler(Callback callback, boolean async)
  • Handler(Looper looper, Callback callback, boolean async)

我們看過載的最後兩個構造方法就行,因為前面的幾個也是依次呼叫到後的方法

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 " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }
複製程式碼

一進來就是一個判斷,眼尖的同學們可能看到了這個log,咦。。這個我好像見過...是的,當這個標誌位位True的時候,這裡會有一個校驗的過程,如果不是靜態的匿名,本地或成員類, 這類可能會產生洩漏,會有一個黃色的警告

接下來是mlooper的賦值,從Looper.myLooper()取出looper,如果為空的話,丟擲一個異常。。相信這個異常同學們也多多少少遇到過...扎心了,點進myLooper()方法:

public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }
複製程式碼

咦。。這麼簡單嗎,從ThreadLocal物件get出來一個looper,那麼有get,當然有set,looper是什麼時候set進去的呢?我們在Looper.prepare找到了答案

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));
    }
複製程式碼

在呼叫prepare方法時,當前sThreadLocal裡面的looper不為空的話,直接丟擲異常,這個異常也是蠻常見的...扎心,也就是保證了Looper.prepare()方法只當前執行緒能呼叫一次,注意是當前執行緒,至於ThreadLocal裡面的邏輯先不討論,後續我們展開再詳細說,也就是從這裡把looper給set進去了

所以在new handler的時候必須要先呼叫Looper.prepare()方法,當然,上面的例子是因為主執行緒中,ActivityThread類已經幫我們呼叫了,在子執行緒中建立handler的時候 需要手動呼叫Looper.prepare(),這裡貼出部分ActivityThread程式碼,這裡也是整個應用的入口,原始碼位置:/frameworks/base/core/java/android/app/ActivityThread.java,有興趣的可以去看看

        public static void main(String[] args) {
6042        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
6043        SamplingProfilerIntegration.start();
6044
6045        // CloseGuard defaults to true and can be quite spammy.  We
6046        // disable it here, but selectively enable it later (via
6047        // StrictMode) on debug builds, but using DropBox, not logs.
6048        CloseGuard.setEnabled(false);
6049
6050        Environment.initForCurrentUser();
6051
6052        // Set the reporter for event logging in libcore
6053        EventLogger.setReporter(new EventLoggingReporter());
6054
6055        // Make sure TrustedCertificateStore looks in the right place for CA certificates
6056        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
6057        TrustedCertificateStore.setDefaultUserDirectory(configDir);
6058
6059        Process.setArgV0("<pre-initialized>");
6060
6061        Looper.prepareMainLooper();
6062
6063        ActivityThread thread = new ActivityThread();
6064        thread.attach(false);
6065
6066        if (sMainThreadHandler == null) {
6067            sMainThreadHandler = thread.getHandler();
6068        }
6069
6070        if (false) {
6071            Looper.myLooper().setMessageLogging(new
6072                    LogPrinter(Log.DEBUG, "ActivityThread"));
6073        }
6074
6075        // End of event ActivityThreadMain.
6076        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
6077        Looper.loop();
6078
6079        throw new RuntimeException("Main thread loop unexpectedly exited");
6080    }
複製程式碼

另外一個構造方法其實就區別於looper的賦值,一個是從當前執行緒ThreadLocal物件去取looper,一個是從外界賦值

public Handler(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }
複製程式碼

2.傳送訊息

2.1 handler.sendMessage()

通過上面,我們的handler物件就建立出來了,接下來就是傳送訊息了,我們先來看看handler.sendMessage()到底幹了啥:

public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }
複製程式碼

呼叫了sendMessageDelayed方法,傳了一個0進去,接著看。。

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

呼叫了sendMessageAtTime方法,傳入了一個long的毫秒數,接著看。。

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);
    }
複製程式碼

這個也很清楚,把msg,uptimeMillis以及之前建構函式拿到的queue塞進去。

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

把當前handler物件賦值給msg.target,呼叫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;
            }

            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;
    }
複製程式碼

正主總算來了。。前面先校驗一波,如果handler為空或者當前msg處於使用中,丟擲異常。然後再持有MessageQueue.this鎖,然後將Message放入佇列中,整個流程可以分為幾步:

  1. 如果當前佇列為空,或者when等於0(也就是msg對應的時間點),或者msg時間點小於當前佇列頭部的p的時間點,就把我們傳進來的msg放入佇列首部,否則執行第二步
  2. 一個for的死迴圈,遍歷佇列中Message,找到when比當前Message的when大的Message,將Message插入到該Message之前,如果沒找到則將Message插入到佇列最後
  3. 判斷是否需要喚醒,這裡可以理解為,如果佇列沒有訊息時,當前執行緒讓出cpu資源,處於一種阻塞狀態,當有訊息到達時,需要喚醒next()函式,具體涉及到jni,後續詳細分析

由此我們可以看出來整個佇列訊息結構是一種連結串列形式的,這樣只要無限輪詢訊息,就能夠輕易遍歷除佇列中所有訊息

Android原始碼學習之handler

2.2 handler.post()

第二種handler發訊息方法 :

public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }
複製程式碼

咦。。我們發現還是呼叫的sendMessageDelayed方法,只不過通過getPostMessage方法將Runnable物件轉化為了msg物件

private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }
複製程式碼

注意這裡的callback,這裡message物件的callback就不為空了,上述handler.sendMessage()方法的message物件的callback是為空的,後續再回撥訊息中會用到。

3.輪詢訊息

我們知道,android是基本訊息機制的,主執行緒所有的行為都是由訊息機制驅動的,比如activity的什麼週期,點選事件等等。。。就主執行緒來說,在上面ActivityThread類中6077行可以看到Looper.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();
        }
    }
複製程式碼

程式碼基本能看清楚,一個for死迴圈,不斷的queue.next(),從佇列裡取出訊息,然後呼叫msg.target.dispatchMessage(msg),這裡的target應該很清楚了,也就是handler物件,可以對照上面enqueueMessage方法,也就是拿到訊息後,回撥了到handler的dispatchMessage方法,我們接著看:

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

終於到這了,相信同學們也已經很清楚。分幾種情況:

  1. 首先來判斷msg的callback是否為空,這個在哪裡賦值的呢,對的,對應上面第二種也就是handler.post()形式的傳進來的Runnable物件:
private static void handleCallback(Message message) {
        message.callback.run();
    }
複製程式碼

然後回到到run()方法裡面去,如果為空走第二種情況

  1. 又是一個判斷如果mCallback不為空的話,回撥handleMessage方法,這裡的mCallback是在handler建構函式賦值的,對應下面的使用用法,但一般這種用法比較少,否則走第三步
new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                return false;
            }
        });
複製程式碼
  1. 執行我們最終的handleMessage(msg)方法,也就是我們複寫的handleMessage(msg)方法,對應我們上面的第一種用法

到此整個流程也基本大致走完了,一步一步來也是蠻easy的嘛,以後再遇到handler的時候,不管是使用或者面試的時候,自己心裡也有點底

當然,裡面還有很多細節,考慮到本文篇幅,就不多贅述了,比如,looper.loop()為什麼不會導致ANR呢,Threadlocal的機制是什麼樣的等等,分析起來就比較耗時了,後續系列會跟大家再一起進行探討!

溜了溜了...感謝看到結尾,謝謝~~

相關文章