天天看點

結合源碼分析android的消息機制描述開始看源碼總結遺留問題

描述

結合幾個問題去看源碼。 1.Handler, MessageQueue, Message, Looper, LocalThread這5者在android的消息傳遞過程中扮演了什麼樣的角色? 2.一個線程中可以有多個Handler嗎?多個Looper呢? 3.整個消息處理過程,消息是怎麼流動的? 4.為什麼隻有UI線程可以更改UI?(就憑他叫UI線程?其實也可以叫主線程或者ActivityThread)

開始看源碼

1.View的繪制都是從ViewRootImpl這個類開始,我們在這個類中找找,為什麼異步線程不能更新UI,發現了這個方法

void checkThread() {
    if (mThread != Thread.currentThread()) {
        throw new CalledFromWrongThreadException(
                "Only the original thread that created a view hierarchy can touch its views.");
    }
}
           

其中mThread就是大名鼎鼎的UI線程,這段代碼說明不是UI線程就直接抛異常,相當粗暴。接着我們發現

@Override
public void requestFitSystemWindows() {
    checkThread();
    mApplyInsetsRequested = true;
    scheduleTraversals();
}

@Override
public void requestLayout() {
    if (!mHandlingLayoutInLayoutRequest) {
        checkThread();
        mLayoutRequested = true;
        scheduleTraversals();
    }
}
           

還有更多就不一一列舉了,對UI的操作都調用了這個檢查的方法,是以非UI線程不能更新UI。這樣做有什麼好處?大概有2點 a.防止耗時操作導緻的ANR,嚴重影響體驗 b.UI控件不是線程安全的,多線程通路會出問題

2.接着看Handler,當我們new出一個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;
}
           

這個構造器最直接。首先需要一個Looper,哪裡來的?在子線程中,我們通常要執行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));
}
           

發現系統建立了一個Looper對象,并且存在了threadLocal中。當Looper建立的時候,同時建立了消息隊列

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

當handler構造時,調用Looper.myLooper()方法,從threadLocal中取出建立的Looper對象。如果你沒用調用Looper.myLooper(),執行下邊代碼就遇到那個熟悉的異常了。

if (mLooper == null) {
        throw new RuntimeException(
            "Can't create handler inside thread that has not called Looper.prepare()");
    }
           

在主線程中沒用調用,為什麼沒有報錯?因為ActivityThread幫你調了

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

看Looper.prepareMainLooper()和Looper.loop()都調了。

3.再看下Handler的post和send方法,Message怎麼被Handler送進MessageQueue的。發現最後他們都進了這個方法

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

通過enqueueMessage方法将消息體也就是Message對象壓入MessageQueue中。

4,然後調用Looper.loop(),開始處理消息

/**
 * Run the message queue in this thread. Be sure to call
 * {@link #quit()} to end the loop.
 */
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
        Printer logging = me.mLogging;
        if (logging != null) {
            logging.println(">>>>> Dispatching to " + msg.target + " " +
                    msg.callback + ": " + msg.what);
        }

        msg.target.dispatchMessage(msg);

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

一個死循環,然後不斷通過queue.next()方法把Message從MessageQueue中取出來處理

5.将消息取出來後,通過調用msg.target.dispatchMessage(msg)來處理消息。msg.target指的是Handler對象,來具體看下:

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

這個方法說明當有Runnable對象(handler.post(new Runnable())設定)時,消息交給handleCallback()處理

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

直接調用了Runnable的run方法。這也解釋了handler.post(new Runnable())時沒有建立線程的問題。當有mCallBack(new Handler(new CallBack())時設定),調用callBack的方法handlerMessage()。都沒有,則調用Handler的handlerMessage方法。

6.自此消息基本從 産生->加入隊列->處理 過程基本走通了。

總結

1.很多細節沒講到,主要是從源碼角度分析整個過程 2.handler可以在任意線程發送消息,這些消息會被添加到關聯的MessageQueue上 3.消息最終會交給産生handler的線程處理,是以子線程可以持handler的引用更新UI 4.MessageQueue和Looper和目前線程相關 5.handler可以建多個,Looper隻能有一個 5.ThreadLocal是個存儲類,從他儲存建立的Looper對象可以看出,以後細說

遺留問題

1.handler的回調中明明列印的目前是子線程,為什麼還是可以更新UI? 2.但是調用延時的方法後又不行了?

實驗代碼:

Log.e("---1---", String.valueOf(Thread.currentThread())
        + "\nThreadID:" + Thread.currentThread().getId());
new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            Looper.prepare();
            Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    Log.e("---3---", String.valueOf(Thread.currentThread())
                    + "\nThreadID:" + Thread.currentThread().getId());
                    btn.setText("handlerMessage");
                }
            };
            Log.e("---2---", String.valueOf(Thread.currentThread())
                    + "\nThreadID:" + Thread.currentThread().getId());
            handler.sendEmptyMessage(0);
                      handler.sendEmptyMessageDelayed(0, 2000);
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Log.e("---4---", String.valueOf(Thread.currentThread())
                            + "\nThreadID:" + Thread.currentThread().getId());
                    btn.setBackgroundColor(Color.YELLOW);
                }
            });
            Looper.loop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}).start();
           

結果: 01-07 14:55:40.688 21362-21362/com.empty.animationtest E/---1---: Thread[main,5,main] ThreadID:1 01-07 14:55:40.698 21362-21394/com.empty.animationtest E/---2---: Thread[Thread-37592,5,main]                                                                  ThreadID:37592 01-07 14:55:40.698 21362-21394/com.empty.animationtest E/---3---: Thread[Thread-37592,5,main]                                                                  ThreadID:37592 01-07 14:55:40.698 21362-21394/com.empty.animationtest E/---4---: Thread[Thread-37592,5,main]                                                                  ThreadID:37592 01-07 14:55:42.698 21362-21394/com.empty.animationtest E/---3---: Thread[Thread-37592,5,main]                                                                  ThreadID:37592 01-07 14:55:42.698 21362-21394/com.empty.animationtest W/System.err: 01-07 14:55:42.698 21362-21394/com.empty.animationtest W/System.err: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. 01-07 14:55:42.698 21362-21394/com.empty.animationtest W/System.err:     at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6294) 01-07 14:55:42.698 21362-21394/com.empty.animationtest W/System.err:     at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:878) 01-07 14:55:42.698 21362-21394/com.empty.animationtest W/System.err:     at android.view.ViewGroup.invalidateChild(ViewGroup.java:4344) 01-07 14:55:42.698 21362-21394/com.empty.animationtest W/System.err:     at android.view.View.invalidate(View.java:10957) 01-07 14:55:42.698 21362-21394/com.empty.animationtest W/System.err:     at android.view.View.invalidate(View.java:10912) 

結果分析: 執行到3,4确實是子線程,也完成了UI的更新。而延時的第二個3,不能成功更新UI,為什麼?