1. 程式人生 > >Android應用程式訊息處理機制

Android應用程式訊息處理機制

1,建立執行緒訊息佇列

(1) Looper.prepareMainLooper() UI執行緒訊息佇列 MessageQueue

public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

(2) Looper.prepare() 子執行緒訊息佇列 MessageQueue

private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        //sThreadLocal用來儲存當前執行緒的Looper物件
        sThreadLocal.set(new Looper(quitAllowed));
    }

在Looper的構造方法中  

 private Looper(boolean quitAllowed) {
        //建立當前執行緒衛唯一的訊息佇列
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

MessageQueue的構造方法

MessageQueue(boolean quitAllowed) {
     mQuitAllowed = quitAllowed;
    //mPtr為int型別儲存了c++層中NativeMessageQueue物件的地址
    /**
     * 創建出c++層中NativeMessageQueue物件,
     * NativeMessageQueue物件會建立c++層Looper物件,
     * Looper物件會建立一個管道,
     * 這個管道的讀檔案描述符和寫檔案描述符儲存在它的成員變數mWakeReedPipeFd和
     * mWakeReadPipeFd中(int型別)
     * 當一個執行緒的訊息佇列沒有訊息需要處理時,它就會在這個管道的讀端檔案描述符上進行睡眠等待
     * 直到其他執行緒通過這個管道的寫端檔案描述符來喚醒它為止
     */
     mPtr = nativeInit();
}

 

2,訊息迴圈過程 

 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;
        
        for (;;) {
            Message msg = queue.next(); // might block
            //如果msg 為null當前執行緒會在next()中休眠直到有新的訊息要處理為止
            if (msg == null) {
                return;
            }
           ......
            try {
                msg.target.dispatchMessage(msg);
            } finally {
                ......
            }
         ......
        }
    }
    Message next() {
        //用來儲存註冊到訊息佇列中空閒訊息處理器(IdleHandler)的個數
        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        /**
         * nextPollTimeoutMillis為當訊息佇列中沒有新的訊息要處理時,當前執行緒需要
         * 進入休眠等待狀態的時間
         * 當nextPollTimeoutMillis = 0 時,表示即使訊息佇列中沒有新的訊息要處理,
         * 也不進入睡眠等待狀態;如果nextPollTimeoutMillis = -1 時,表示訊息佇列中
         * 沒有新的訊息要處理,執行緒進入睡眠狀態,直到被其它執行緒喚醒
         */
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }
            //檢查當前執行緒的訊息佇列中是否有新的訊息要處理,如果nextPollTimeoutMillis = -1,執行緒將進入睡眠狀態
            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執行緒進入休眠的時間
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // Got a message.
                        //如果當前執行緒為睡眠狀態mBlocked=true 
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        //取出當前訊息返回
                        return msg;
                    }
                } else {
                    // No more messages.
                    //下次呼叫nativePollOnce(ptr, nextPollTimeoutMillis)時,執行緒將進入睡眠狀態
                    nextPollTimeoutMillis = -1;
                }

           ......

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

}

nativePollOnce(ptr, nextPollTimeoutMillis)是個本地方法,

會呼叫NativeMessageQueue的pollOnce(nextPollTimeoutMillis)函式;

static void android_os_MessageQueue_nativePollOnce(JNIEnv* env, jobject obj,  
        jint ptr, jint timeoutMillis) {  
    NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr);  
    nativeMessageQueue->pollOnce(timeoutMillis);  
}

然後會呼叫c++層Looper的pollOnce(nextPollTimeoutMillis)函式;

void NativeMessageQueue::pollOnce(int timeoutMillis) {  
    mLooper->pollOnce(timeoutMillis);  
}
 nt Looper::pollInner(int timeoutMillis) {
        ......
        int result = ALOOPER_POLL_WAKE;
        ......
        
        struct epoll_event eventItems[EPOLL_MAX_EVENTS];
//監聽註冊在前面的所建立的管道(epoll)例項中描述的檔案IO讀寫事件,如果沒有IO事件發生,執行緒就會在epoll_wait()進入睡眠狀態,時間為timeoutMillis
        int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
        ......

        size_t requestedCount = mRequestedFds.size();
        int eventCount = poll(mRequestedFds.editArray(), requestedCount, timeoutMillis);
        
        ......
        //檢查那個檔案發生了IO事件
        for (int i = 0; i < eventCount; i++) {
            int fd = eventItems[i].data.fd;
            uint32_t epollEvents = eventItems[i].events;
            if (fd == mWakeReadPipeFd) {
                //發生IO讀寫事件的檔案描述符是否與當前執行緒關聯的的管道的檔案描述符一致
                //返回true說明其他執行緒向當前執行緒關聯的管道寫入了一個新的資料
                //當其他執行緒想當前執行緒的訊息佇列傳送一個訊息時,他就會向當前執行緒關聯的管道寫一個數據,目的是喚醒當前執行緒,以便它去處理剛剛訊息佇列接收的訊息
                if (epollEvents & EPOLLIN) {
                    //將當前執行緒關聯的管道中的訊息讀出來,清理舊資料
                    awoken();
                } else {
                    LOGW("Ignoring unexpected epoll events 0x%x on wake read pipe.", epollEvents);
                }
            } else {
               ......
            }
        }
     ......
        return result;
    }

3,訊息的傳送過程 

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) {
        //將當前的handler物件賦值給Mesage的target(handler型別)
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

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) {
            //訊息在使用
            msg.markInUse();
            msg.when = when;
            //mMessages隊頭的訊息
            Message p = mMessages;
            boolean needWake;
            // p == null目標訊息佇列是個空佇列
            // when == 0要插入的訊息的優先順序最高,要把它插入到訊息佇列的頭部優先執行
            // when < p.when 執行的時間早於P,插入到P前面
            //這三種都需要插入到頭部
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                //如果訊息不是睡眠狀態不需要喚醒,如果mBlocked==true說明執行緒處於睡眠狀態
                needWake = mBlocked;
            } else {
                // Inserted within the middle of the queue.  Usually we don't have to wake
                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;
    }

 nativeWake(mPtr)是個本地方法,它由nativeMessageQueue的wake()方法來實現,接著會呼叫c++層的mLooper->wake()

mLooper呼叫wake()方法,向它的所描述的管道寫一個新的資料,這時候執行緒會因為這個管道發生了一個IO寫事件而被喚醒

4,執行緒訊息處理過程

當一個執行緒沒有訊息需要處理時,它就會在c++層的Looper類成員函式pollInner()中被進入睡眠等待狀態,因此當這個執行緒有新的訊息要處理時,首先會在c++層的loope類的pollInner()中被喚醒,然後延之前的路徑一直返回到java層的Looper類的靜態函式loop()中,最後就可以對訊息進行處理了

 

 (1) looper.loop();

    public static void loop() {
        final Looper me = myLooper();
        final MessageQueue queue = me.mQueue;
        ......

        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

               ......
           
                msg.target.dispatchMessage(msg);
               ......                      

        }
    }

 

    public void dispatchMessage(Message msg) {
         //當要處理的訊息在傳送時指定了一個回撥介面時msg.callback != null返回true
         //當呼叫handler.post(Runable r)時,handler會為這個訊息指定一個回撥介面
        if (msg.callback != null) { //1
            handleCallback(msg);
        } else {
            //當呼叫handler的可指定callback構造方法時
            if (mCallback != null) {  //2
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            } 
            handleMessage(msg);//3
        }
    }

    public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }

    private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;//指定一個回撥介面
        return m;
    }


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

    public Handler(Callback callback, boolean async) { //2    
        mLooper = Looper.myLooper();     
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

 還有一種訊息,執行緒空閒,不討論了