Android Handler異步消息處理機制解讀

Android Handler異步消息處理機制解讀

前言

去年年底很忙,就沒什麼時間寫博客,後面就是疫情了,疫情在老家把整個人都搞的渾渾噩噩的,提不起興致。回到公司復工也是比較忙,沒啥時間寫,週末不陪陪媳婦兒還要不高興,最近稍微空閒了一點,準備重新開始繼續找回狀態吧,從基礎的安卓異步消息處理機制開始,網上類似博客很多,但是打算自己重新回顧一下加深印象。

開始之前

​ 說到消息機制,大家一定非常熟悉,因爲平時coding的時候高頻率的使用。我們都知道,Android系統規定只能在主線程更新UI,子線程進行耗時操作,如果主線程進行耗時操作就會出現ANR(Application Not Responding)的現象,子線程更新UI就會報錯,看看子線程更新UI會有什麼情況:

       new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                tvContent = findViewById(R.id.tv_content);
                tvContent.setText("89797");
            }
        }).start();

這段代碼,我們運行之後,不出意外會報下面的錯誤,

Only the original thread that created a view hierarchy can touch its views

那麼怎麼解決呢,當然是用handler機制啦,不過我們只知道如何使用肯定是不行的,不然也不用花費時間來寫這篇文章了。

(PS:有的人可能會說,子線程並非一定不能更新UI啊,我在onCreate裏創建一個子線程刷新UI就可以啊,當然沒錯,子線程可以在ViewRootImpl還沒有被創建之前更新UI,但是我們這裏指的是谷歌官方的規定,通用情況下,是不可以在子線程裏更新UI的)

先來看看如何解決這個問題,改完之後的代碼:

   new Thread(new Runnable() {
                @Override
                public void run() {
                  //  Looper.prepare();//子線程中創建handler Looper得先prepare
                    Handler handler = new Handler(){
                        @Override
                        public void handleMessage(Message msg) {
                            super.handleMessage(msg);
                            tvContent.setText(msg.obj.toString());
                        }
                    };
                    Message message = Message.obtain();
                    message.obj = "test";
                    message.what = 1;
                    handler.sendMessage(message);
                    //Looper.loop();//接收消息
                }
            }).start();

這樣就解決了,運行一下,發現又報錯了

   java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
        at android.os.Handler.<init>(Handler.java:203)
        at android.os.Handler.<init>(Handler.java:117)
        at com.lyj.git.MainActivity$1$1.<init>(MainActivity.java:33)
        at com.lyj.git.MainActivity$1.run(MainActivity.java:33)
        at java.lang.Thread.run(Thread.java:764)

好的,根據報錯提示,加上Looper.prepare(),解決,但是發現雖然沒有報錯了,但是消息沒有接收到,加上Looper.loop(),完美解決。

正題

好了,說了半天,進入正題,從源碼角度分析。
首先我們來看看這個報錯原因,爲什麼在子線程實例化的時候不調用Looper.prepare就會報錯呢,實例化一個Handler的時候,我們一步步跟代碼可以發現,最後都會走到下面這個方法

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

這個方法的倒數第六行我們可以看到,如果loop爲空,就會拋出異常,就是我們最開始出現的錯誤日誌,那麼什麼時候這個對象纔會爲空呢,我們來看看mylooper方法

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

這個方法很簡單,就是從sThreadLocal中獲取,很顯然如果sThreadLocal中有Looper存在就返回Looper,如果沒有Looper存在就返回空了

那麼這個又是在哪給sThreadLocal設置變量的呢,是在Loop.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));
    }

//可以看到,該方法在當前thread創建了一個Looper(), ThreadLocal主要用於維護線程的本地變量,  

 private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}

看這段代碼,判斷sThreadLocal中是否已經存在Looper了,如果還沒有則創建一個新的Looper設置進去。這樣也就完全解釋了爲什麼我們要先調用Loop.prepare()方法,才能創建Handler對象。同時也可以看出每個線程中最多隻會有一個Looper對象

那麼肯定有人會問了,我在主線程實例化handler的時候也沒有調用Loop.prepare()呀,其實在主線程被創建的時候,已經調用了。我們都知道,應用初始化的時候都會調用ActivityThread類中的main方法(不知道的可以去看看應用啓動流程),我們看看這個main方法中幹了啥

public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
        SamplingProfilerIntegration.start();

        // CloseGuard defaults to true and can be quite spammy.  We
        // disable it here, but selectively enable it later (via
        // StrictMode) on debug builds, but using DropBox, not logs.
        CloseGuard.setEnabled(false);

        Environment.initForCurrentUser();

        // Set the reporter for event logging in libcore
        EventLogger.setReporter(new EventLoggingReporter());

        // Make sure TrustedCertificateStore looks in the right place for CA certificates
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);

        Process.setArgV0("<pre-initialized>");
        //沒錯!!就是這裏!!!
        Looper.prepareMainLooper();

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

在這個方法裏面我們看到在應用初始化的時候主線程已經調用了Loop.prepare了,所以我們平時用的時候不用Looper.prepare。到這裏我們就可以在主線程發送消息了

消息入隊

不管你是用post的方式還是sendMessage的方式,我們一步步跟進源碼可以發現實際上調用的最終都是sendMessageAtTime方法,他倆本質上是沒有區別的,就是寫的方式不一樣罷了,下面我們來看看這個sendMessageAtTime方法

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

實際他調用的是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 {
                // 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;
    }
//我們可以看到,Message被存入MessageQueue時是將Message存到了上一個Message.next上, 
//形成了一個鏈式的列表,同時也保證了Message列表的時序性。

可以看到, MessageQueue 實際上裏面維護了一個 Message 構成的鏈表,每次插入數據都會按時間順序進行插入,也就是說 MessageQueue 中的 Message 都是按照時間排好序的,這樣的話就使得循環取出 Message 的時候只需要一個個地從前往後拿即可,這樣 Message 都可以按時間先後順序被消費

消息循環

存入我們看到了,那麼是何時取出的呢,想必都猜到是Loop裏面的邏輯,之前我們也發現子線程裏面創建handler需要Looper.prepare(),並且不調用Loop.loop()方法handler接受不到消息,現在我們來看看這個方法。

 public static void loop() {
     //在調用Looper.prepare()之前是不能調用該方法的,不然就得拋出異常了
        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 slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            final long end;
            try {
                msg.target.dispatchMessage(msg);
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (slowDispatchThresholdMs > 0) {
                final long time = end - start;
                if (time > slowDispatchThresholdMs) {
                    Slog.w(TAG, "Dispatch took " + time + "ms on "
                            + Thread.currentThread().getName() + ", h=" +
                            msg.target + " cb=" + msg.callback + " msg=" + msg.what);
                }
            }

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

第3,4行:判斷Looper對象是否爲空,如果是空,拋出"No Looper; Looper.prepare() wasn’t called on this thread."異常。這就是我們最開始寫示例代碼的時候拋出的異常,如果我們在線程中創建handler,並且調用sendMessage方法,由於沒有Looper對象,就會拋此異常。

消息的處理

for (;😉 循環裏面,是個死循環,不斷的執行next方法,這個方法這裏我們暫時先不分析,如果有新消息,就交給 msg.target.dispatchMessage(msg),這裏msg.target其實就是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屬性不爲空,則代表使用了post(Runnable r)發送消息,直接回調Runnable對象裏複寫的run()
2、若msg.callback屬性爲空,則代表使用了sendMessage(Message msg)發送消息,則回調複寫的

所以,一個最標準的異步寫法就是下面這樣的

class HandlerThread extends Thread {
        private Handler handler;
        @Override
        public void run() {
            Looper.prepare();
            handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    tvContent.setText("13232");
                }
            };
            Looper.loop();
        }
    }

到這裏,handler的消息異步處理機制就差不多了,我們來總結一下

Message:消息,其中包含了消息ID,消息處理對象以及處理的數據等,由MessageQueue統一列隊,終由Handler處理

MessageQueue:用於存儲 Message,內部維護了 Message 的鏈表,每次拿取 Message 時,若該 Message 離真正執行還需要一段時間,會通過 nativePollOnce 進入阻塞狀態,避免資源的浪費。若存在消息屏障,則會忽略同步消息優先拿取異步消息,從而實現異步消息的優先消費。

Looper:一個用於遍歷 MessageQueue 的類,每個線程有一個獨有的 Looper,它會在所處的線程開啓一個死循環,不斷從 MessageQueue 中拿出消息,並將其發送給 target 進行處理

Handler:事件的發送及處理者,在構造方法中可以設置其 async,默認爲 “默認爲 true。若 async 爲 false 則該 Handler 發送的 Message 均爲異步消息,有同步屏障的情況下會被優先處理”

1、一在handler所創建的線程需要維護一個唯一的Looper對象, 一個線程只能有一個Looper,每個線程的Looper通過ThreadLocal來保證,Looper對象的內部又維護有唯一的一個MessageQueue,所以一個線程可以有多個handler,但是只能有一個Looper和一個MessageQueue
2、Message在MessageQueue不是通過一個列表來存儲的,而是將傳入的Message存入到了上一個Message的next中,在取出的時候通過頂部的Message就能按放入的順序依次取出Message
3、Looper對象通過loop()方法開啓了一個死循環,不斷地從looper內的MessageQueue中取出Message然後通過handler將消息分發傳回handler所在的線程

借用網上的一張總結的不錯的圖來表示handler消息機制的流程:


關於消息屏障的內容,很多人都忽略了,我們下次再專門研究

參考:
https://blog.csdn.net/guolin_blog/article/details/9991569
https://blog.csdn.net/wsq_tomato/article/details/80301851
https://www.jianshu.com/p/ddc70efa57e4

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