Andorid的消息機制

Android的消息機制概述

Android的消息機制主要是指Handler的運行機制,Handler的運行機制須要底層的MessageQueue和Looper的支撐。數組

MessageQueue的中文爲消息隊列,顧名思義,它的內部存儲了一組消息,以隊列的形式對外提供插入和刪除的方法。雖然稱爲消息隊列,可是它的內部存儲結構並非真正的隊列,而是採用單鏈表的數據結構來存儲消息列表安全

Looper的中文翻譯是循環,這裏能夠理解爲消息循環。因爲MessageQueue只是一個消息的存儲單元,它不能去處理消息,而Looper會以無限循環的形式其查詢是否有新的消息,若是有的話就處理消息,不然就一直等待。服務器

Looper中還有一個特殊的概念,那就是ThreadLocal,ThreadLocal並非線程,它的做用是能夠在每一個線程中存儲數據。咱們知道,Handler建立的時候會採用當前線程的Looper來構造消息循環系統,那麼Handler內部如何獲取到當前線程的Looper呢?這就要使用ThreadLocal了,ThreadLocal能夠在不一樣的線程中互不干擾地存儲並提供數據,經過ThreadLocal就能夠輕鬆地獲取每一個線程的Looper。數據結構

須要注意的是,線程是默認沒有Looper的,若是須要使用Handler就必須爲線程建立Looper。而主線程,即UI線程,它就是ActivityThread,ActivityThread被建立時就會初始化Looper,這也是在主線程中默承認以使用Handler的緣由。多線程

Android消息機制分析

Android消息機制主要是指Handler的運行機制以及Handler所附帶的MessageQueue和Looper的工做過程,這三者其實是一個總體。Handler的做用主要是將一個任務切換到某個指定的線程中去執行,那麼Android爲何要提供這個功能呢?這是由於Android規定UI只能在主線程中進行,若是在子線程中訪問UI,那麼程序就會拋出運行時異常。ViewRootImp對UI操做作了驗證,這個驗證工做是由ViewRootImpl的checkThread方法來完成的,以下所示。併發

void checkThread() {

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

Android建議咱們不要在主線程中進行耗時的操做,不然會致使程序沒法響應ANR。考慮一種狀況,假如咱們須要從服務器拉取一些信息並將其顯示在UI上,這個時候必須在子線程中進行拉取工做,拉取完畢以後又不能在子線程中直接訪問UI,若是沒有Handler,那麼咱們確實沒有辦法將訪問UI的工做切換到主線程中執行,所以,系統提供Handler的主要緣由及時爲了解決在子線程中沒法訪問UI的矛盾。app

系統爲何不容許在子線程中訪問UI呢?這是 由於Android的UI控件不是線程安全的,若是在多線程中併發訪問可能會致使UI控件處於不可預期的狀態,而爲何系統不對UI控件的訪問加上鎖機制呢?缺點有兩個:首先加上鎖機制會讓UI訪問的邏輯變得複雜,其次鎖機制會下降UI訪問的效率,由於鎖機制會阻塞某些線程的執行。所以最簡單最高效的方法就是採用單線程模型來處理UI操做,對於開發者來講也不是很麻煩,只是須要經過Handler切換到UI訪問的執行線程便可。less

Handler的工做過程:Handler建立時會採用當前線程的Looper來構建內部的消息循環系統,若是當前線程沒有Looper,那麼就會報錯;Handler建立完畢後,這個時候其內部的MessageQueue和Looper就能夠協同工做了,而後經過Handler的post方法將一個Runnable傳遞到Handler內部的Looper中去處理,也能夠經過Handler的send方法來發送一個消息,這個消息一樣會在Looper中去處理。其實post方法最終也是在send方法中完成的。當Handler的send方法被調用時,它會調用MessageQueue的enqueueMessage方法將這個消息放入消息隊列中,而後Looper發現有新消息到來時,就會處理這個消息,最終消息中的Runnable或者Handler的handleMessage方法就會被調用。async

注意:Looper是運行在建立Handler所在的線程中的,這樣一來Handler中的業務邏輯就被切換到建立Handler所在的線程中去執行了。ide

ThreadLocal的工做原理

ThreadLocal是一個線程內部的數據存儲類,經過它能夠在指定的線程中存儲數據,數據存儲之後,只有在指定線程中能夠獲取到存儲的數據,對於其餘線程來講則沒法獲取到數據。

下面經過實際的例子來演示ThreadLocal的做用。首先定義一個ThreadLocal對象,這裏選擇Boolean類型的,以下所示:

private ThreadLocal<Boolean> mThreadLocal = new ThreadLocal<Boolean>();

而後在主線程、子線程1和子線程2中設置和訪問它的值,代碼以下所示:

mThreadLocal.set(true);
    System.out.println("main thread: " + mThreadLocal.get()); //true
    
    new Thread(new Runnable() {
        
        @Override
        public void run() {
            // TODO Auto-generated method stub
            mThreadLocal.set(false);
            System.out.println("thread 1: " + mThreadLocal.get()); //false
            
        }
    }).start();
    
    new Thread(new Runnable() {
        
        @Override
        public void run() {
            // TODO Auto-generated method stub
            
            System.out.println("thread 2: " + mThreadLocal.get()); //null,沒有設置值
            
        }
    }).start();

上述代碼中,根據對ThreadLocal的描述,主線中mThreadLocal.get()爲true,子線程1中mThreadLocal.get()爲false,子線程2中mThreadLocal.get()爲null。代碼運行打印以下:

15:54:55.478: I/System.out(11711): main thread: true
01-09 15:54:55.479: I/System.out(11711): thread 1: false
01-09 15:54:55.480: I/System.out(11711): thread 2: null

從上面的打印能夠看出,雖然不一樣的線程訪問的是同一個ThreadLocal對象,可是它們經過ThreadLocal獲取的值倒是不同的,這就是ThreadLocal的特色。ThreadLocal之因此有如此特色,是由於不一樣線程訪問同一個ThreadLocal的get方法,ThreadLocal內部會從各自的線程中取出一個數組,而後再從數組中根據當前的ThreadLocal索引去查找對應的value值。很顯然,不一樣線程中的數組是不一樣的,這就是爲何經過ThreadLocal能夠在不一樣的線程中維護一套數據的副本而且互不干擾。

上面描述的ThreadLocal的使用方法和工做過程,下面分析ThreadLocal的內部實現,ThreadLocal是一個泛型類,它的定義爲public class ThreadLocal<T>,只要弄清楚ThreadLocal的get和set方法就能夠明白它的工做原理。

首先看get和set方法,以下所示

public void set(T value) {
        Thread currentThread = Thread.currentThread();
        Values values = values(currentThread);
        if (values == null) {
            values = initializeValues(currentThread);
        }
        values.put(this, value);
    }

    Values initializeValues(Thread current) {
        return current.localValues = new Values();
    }

    /**
     * Gets Values instance for this thread and variable type.
     */
    Values values(Thread current) {
        return current.localValues;
    }

在上面的set方法中,首先會經過values方法來獲取當前線程中的ThreadLocal數據,如何獲取呢?在Thread內部有一個成員變量專門用於存儲線程的ThreadLocal數據:ThreadLocal.Values localValues;所以獲取當前線程的ThreadLocal數據就變得異常簡單。若是localValues的值爲null,那麼久須要對其進行初始化化,初始化後再將ThreadLocal的值進行存儲。

下面看一下ThreadLocal的值究竟是如何在localValues中進行存儲的。在localValues內部有一個數組:private Object[] table;ThreadLocal的值就存儲在這個table數組中。下面看一下localValues是如何使用put方法將ThreadLocal的值存儲到table數組中的,以下所示:

/**
     * Sets entry for given ThreadLocal to given value, creating an
     * entry if necessary.
     */
    void put(ThreadLocal<?> key, Object value) {
        cleanUp();

        // Keep track of first tombstone. That's where we want to go back
        // and add an entry if necessary.
        int firstTombstone = -1;

        for (int index = key.hash & mask;; index = next(index)) {
            Object k = table[index];

            if (k == key.reference) {
                // Replace existing entry.
                table[index + 1] = value;
                return;
            }

            if (k == null) {
                if (firstTombstone == -1) {
                    // Fill in null slot.
                    table[index] = key.reference;
                    table[index + 1] = value;
                    size++;
                    return;
                }

                // Go back and replace first tombstone.
                table[firstTombstone] = key.reference;
                table[firstTombstone + 1] = value;
                tombstones--;
                size++;
                return;
            }

            // Remember first tombstone.
            if (firstTombstone == -1 && k == TOMBSTONE) {
                firstTombstone = index;
            }
        }
    }

上面的代碼實現了數據的存儲過程,咱們能夠由上能夠得出一個存儲規則,那就是ThreadLocal的值在table數組中的存儲位置老是爲ThreadLocal的reference字段所標識的對象的下一個位置,好比ThreadLocal的reference對在table數組中的索引爲index,那麼ThreadLocal的值在table數組中的索引就是index+1.最終ThreadLocal的值會被存儲在table數組中:table[index + 1] = value;

接下來,分析get方法,以下所示

public T get() {
        // Optimized for the fast path.
        Thread currentThread = Thread.currentThread();
        Values values = values(currentThread);
        if (values != null) {
            Object[] table = values.table;
            int index = hash & values.mask;
            if (this.reference == table[index]) {
                return (T) table[index + 1];
            }
        } else {
            values = initializeValues(currentThread);
        }

        return (T) values.getAfterMiss(this);
    }

能夠發現,ThreadLocal的get方法一樣是取出當前線程的localValues對象,若是這個對象不爲null,那就取出它的table數組並找出ThreadLocal的reference對象在table數組中的位置,而後table數組中下一個位置所存儲的數據就是ThreadLocal的值。若是這個對象爲null,則返回初始值,初始值由ThreadLocal的initialValue方法來描述,默認狀況下爲null,固然也能夠重寫這個方法,它的默認實現以下

Object getAfterMiss(ThreadLocal<?> key) {
        Object[] table = this.table;
        int index = key.hash & mask;

        // If the first slot is empty, the search is over.
        if (table[index] == null) {
            Object value = key.initialValue();

            // If the table is still the same and the slot is still empty...
            if (this.table == table && table[index] == null) {
                table[index] = key.reference;
                table[index + 1] = value;
                size++;

                cleanUp();
                return value;
            }

            // The table changed during initialValue().
            put(key, value);
            return value;
        }

    protected T initialValue() {
        return null;
    }

從ThreadLocal的set和get方法能夠看出,它們所操做的對象都是當前線程的Values對象的table數組,所以在不一樣的線程中訪問同一個ThreadLocal的set和get方法,它們對ThreadLocal所在的讀/寫權限僅限各自線程的內部,這就是ThreadLocal能夠在不一樣線程中互不干擾的儲存和修改數據的緣由,理解ThreadLocal的工做方式有助於理解Looper的工做原理。

消息隊列的工做原理

消息隊列在Android中指的是MessageQueue,MessageQueue主要包括兩個操做:插入和讀取,讀取操做會伴隨着刪除操做,插入和讀取的方法分別是enqueueMessage和next,其中enqueueMessage的做用每每是往消息隊列中插入一條消息,而next的做用是往消息隊列中取出一條消息並將其從消息隊列中移除。儘管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("MessageQueue", 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 not 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;
    }

從enqueueMessage的實現來看,它的主要操做就是單鏈表的插入和刪除,下面看一下next方法的實現:

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 (false) Log.v("MessageQueue", "Returning message: " + msg);
                        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("MessageQueue", "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;
        }
    }

能夠發現next方法是一個無限循環的過程,若是消息隊列中沒有消息,那麼next方法會一直阻塞在這裏。當有新的消息到來時,next方法會返回這條消息並將其從單鏈表中移除。

Looper的工做原理

Looper在Android消息機制裏面扮演着消息循環的角色,具體來講它會不停地從MessageQueue中查看是否有新消息,若有有新消息就會馬上處理,不然就會一直阻塞在那裏。
首先看一下Looper的構造函數,在構造方法中它會建立一個MessageQueue即消息隊列,而後將當前線程的對象存儲起來,以下所示:

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

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

Handler的工做須要Looper,沒有Looper的線程就會報錯,那麼如何爲一個線程建立Looper呢?經過Looper.prepare()便可爲當前線程建立一個Looper,接着經過Looper.loop()來開啓消息循環,以下所示:

new Thread(new Runnable() {
        
        @Override
        public void run() {
            // TODO Auto-generated method stub
            Looper.prepare(); //建立Looper
            mHandler = new Handler(){
                
                @Override
                public void handleMessage(Message msg) {
                    // TODO Auto-generated method stub
                    super.handleMessage(msg);
                    
                    if (msg.what == 0) {
                        
                        System.out.println("msg: " + "123456"); 
                    }
                }
            };
            Looper.loop(); //開啓Looper循環
            
        }
    }).start();

    /**
     * 發送消息
     * @param view
     */
    public void click(View view) {
        
        mHandler.sendEmptyMessage(0);
    }

    /**
     * 退出Looper循環
     * @param view
     */
    public void quit(View view) {
        mHandler.getLooper().quit();
        mHandler.getLooper().quitSafely(); //API18
    }

Looper除了prepare方法外,還提供了prepareMainLooper()方法,這個方法主要是給主線程也就是ActivityThread建立Looper使用的,其本質也是經過prepare方法建立的。因爲主線程的Looper比較特殊,因此Looper提供了一個getMainLooper方法,經過它能夠在任何位置獲取主線程Looper。

Looper也是能夠退出的,Looper提供了quit和quitSafely來退出一個Looper,兩者的區別在於:quit會直接退出Looper,而quitSafely只是設定一個退出標誌,而後把消息隊列中的已有消息處理完畢後才安全地退出。Looper退出後,提供Handler發送的消息會失敗,這時Handler的send方法返回false。在子線程中,若是手動爲其建立了Looper,那麼在全部的事情完成之後應該調用quit方法來終止消息循環,不然這個子線程會一直處於等待狀態,而若是推出Looper之後,這個線程就會馬上終止,所以建議不須要的時候終止Looper。

Looper最重要的一個方法是loop方法,只有調用了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 bloc  退出時返回null
            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); //分發消息 msg.target = Handler

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

Looper的loop方法工做過程,loop方法是一個死循環,位移跳出循環的方式是MessageQueue的next方法返回null。當Looper的quit方法被調用時,Looper就會調用MessageQueue的quit或者quitSafely方法來通知消息隊列退出,當消息隊列表計爲退出狀態時,它的next方法就返回null。

Looper必須退出,不然loop方法會無線循環下去。loop方法會調用MessageQueue的next方法來獲取新的消息,而next是一個阻塞操做,當沒有消息時,next方法會一直阻塞在那裏,這也致使loop方法一直阻塞在那裏。若是MessageQueue的next方法返回了新的消息,Looper就會處理這條消息:msg.target.dispatchMessage(msg);這裏的msg.target是發送這條消息的Handler對象,這樣Handler的發送的消息最終在它的dispatchMessage中處理了。

Handler的工做原理

Handler的主要工做包含消息的發送和接收過程。消息的發送能夠經過post的一系列方法以及send的一系列方法實現,post的一系列方法最終是經過send的一系列方法來實現的。發送一條消息典型過程以下所示:

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

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

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

//送入消息隊列
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}

能夠發現,Handler發送消息的過程僅僅是向消息隊列插入了一條消息,MessageQueue的next方法就會返回這條消息給Looper,Looper收到消息後就開始處理了,最終消息由Looper交由Handler處理,即Handler的dispatchMessage方法會被調用,這是Handler就進入了消息處理階段。dispatchMessage實現以下:

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

Handler處理消息的過程以下:

首先,檢查Message的Callback是否爲null,不爲null則經過handleCallback來處理消息,Message的callback是一個Runnable對象,實際上就是Handler的post方法所傳遞的Runnable參數。

private static void handleCallback(Message message) {
    message.callback.run();  //messge.callback = Runnable對象
}

其次,若Message的Callback是爲null,則檢查mCallback是否爲null,不爲null就調用mCallback的handleMessage方法來處理消息,Callback是個接口,定義以下:

public interface Callback {
    public boolean handleMessage(Message msg);
}

經過Callback框圖用以下方式建立Handler對象:Handler mHandler = new Handler(mCallback)。那麼Callback的意義是什麼了?能夠用來建立一個Handler的實例但並不須要派生Handler的子類。

最後,若都爲null,則直接調用Handler中的handlerMessage方法來處理消息。

Handler還有一種特使的構造函數,那就是經過一個特定的Looper來構造Handler,經過這個構造方法能夠實現一些特殊的功能如IntentService,它的實現以下所示

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

Handler的一個默認構造方法public Handler(),這個構造方法會調用下面的的構造方法。很明顯,若是當前線程沒有Looper的話,就會拋出異常,這也解釋了在沒有Looper的子線程建立Handler會引起程序異常的緣由。

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

public Handler(Callback callback, boolean async) {

    ...

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

主線程的消息循環

Android的主線程就是ActivityThread,主線程的入口方法爲main,在main方法中系統會經過Looper.prepareMainLooper()來建立主線程的Looper以及MessageQueue,並經過Looper.loop()開啓主線程的消息循環,以下所示:

public static void main(String[] args) {
    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());

    Security.addProvider(new AndroidKeyStoreProvider());

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

主線程的消息循環開始之後,ActivityThread須要一個Handler來和消息隊列進行交互,這個Handler就是ActivityThread.H,它內部定義了一組消息類型,主要包含了四大組件的啓動和中止等過程,以下所示

ActivityThread經過ApplicationThread和AMS進行進程間通訊,AMS以進程間通訊的方式完成ActivityThread的請求後回調ApplicationThread中的Binder方法,而後ApplicationThread會向H發送消息,H收到消息後會將ApplicationThread中的邏輯切換到ActivityThread中去執行,即切換到主線程中執行,這個過程就是主線程的消息循環模型。

相關文章
相關標籤/搜索