android消息處理源碼分析

1、簡介android

消息處理機制主要涉及到這幾個類: 1.Looper 2.MessageQueue 3.Message 4.Handlerbash

image

2、源碼分析async

Looper.class的關鍵源碼:oop

//保存Looper對象,在android中每建立一個消息隊列,就有一個而且是惟一一個與之對應的Looper對象 
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
//主線程的Looper
private static Looper sMainLooper;
//消息隊列
final MessageQueue mQueue;
final Thread mThread;

//子線程中經過調用該方法來建立消息隊列
public static void prepare() {
    prepare(true);
}

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


//主線程調用該方法來建立消息隊列
public static void prepareMainLooper() {
    prepare(false);
    synchronized (Looper.class) {
        if (sMainLooper != null) {
            throw new IllegalStateException("The main Looper has already been prepared.");
        }
        sMainLooper = myLooper();
    }
}

//實例化Looper,建立消息隊列,獲取當前線程
private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}

//調用loop方法開啓消息循環 
public static void loop() { 
    //獲取當前的Looper對象,若爲null,拋出異常 
    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 (;;) { 
        //調用next()方法從消息隊列中獲取消息,若是爲null,結束循環;不然,繼續執行(有可能會阻塞) 
        Message msg = queue.next(); 
        if (msg == null) { 
            return; 
        } 
        ...... 
        try { 
            //調用handler的dispatchMessage(msg)分發消息  
            msg.target.dispatchMessage(msg); 
        } finally {
        ...... 
        } 
        //回收消息資源  
        msg.recycleUnchecked(); 
    }
}

//消息循環退出
public void quit() {
    mQueue.quit(false);
}

public void quitSafely() {
    mQueue.quit(true);
}
複製代碼

消息循環退出過程源碼分析

從上面能夠看到loop()方法是一個死循環,只有當MessageQueue的next()方法返回null時纔會結束循環。那麼MessageQueue的next()方法什麼時候爲null呢?ui

在Looper類中咱們看到了兩個結束的方法quit()和quitSalely()。 二者的區別就是quit()方法直接結束循環,處理掉MessageQueue中全部的消息。 quitSafely()在處理完消息隊列中的剩餘的非延時消息(延時消息(延遲發送的消息)直接回收)時才退出。這兩個方法都調用了MessageQueue的quit()方法this

MessageQueue.class 的關鍵源碼:spa

MessageQueue中最重要的就是兩個方法: 1.enqueueMessage()向隊列中插入消息 2.next() 從隊列中取出消息線程

/*
*MessageQueue中enqueueMessage方法的目的有兩個:
*1.插入消息到消息隊列
*2.喚醒Looper中等待的線程(若是是即時消息而且線程是阻塞狀態)
*/
boolean enqueueMessage(Message msg, long when) {
    //發送該消息的handler爲null,拋出異常
    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");
            msg.recycle();
            return false;
        }
        msg.markInUse();
        msg.when = when;
        //消息隊列的第一個元素,MessageQueue中的成員變量mMessages指向的就是該鏈表的頭部元素。
        Message p = mMessages;
        boolean needWake;
        if (p == null || when == 0 || when < p.when) {
            //若是此隊列中頭部元素是null(空的隊列,通常是第一次),或者此消息不是延時的消息,則此消息須要被當即處理,
            //將該消息做爲新的頭部,並將此消息的next指向舊的頭部。若是是阻塞狀態則須要喚醒。
            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;
            prev.next = msg;
        }
        if (needWake) {
            nativeWake(mPtr);
        }
    }
    return true;
}

Message next() {
    //與native方法相關,當mPtr爲0時返回null,退出消息循環
    final long ptr = mPtr; 
    if (ptr == 0) {
        return null;
    }

    int pendingIdleHandlerCount = -1;
    //0不進入睡眠,-1進入睡眠 
    int nextPollTimeoutMillis = 0;  
    for (;;) {
        if (nextPollTimeoutMillis != 0) {
            //處理當前線程中待處理的Binder進程間通訊請求
            Binder.flushPendingCommands();  
        }
        //native方法,nextPollTimeoutMillis爲-1時進入睡眠狀態
        //阻塞方法,主要是經過native層的epoll監聽文件描述符的寫入事件來實現的。
        //若是nextPollTimeoutMillis=-1,一直阻塞不會超時。
        //若是nextPollTimeoutMillis=0,不會阻塞,當即返回。
        //若是nextPollTimeoutMillis>0,最長阻塞nextPollTimeoutMillis毫秒(超時),若是期間有程序喚醒會當即返回
        nativePollOnce(ptr, nextPollTimeoutMillis); 
        synchronized (this) {
            final long now = SystemClock.uptimeMillis();
            Message prevMsg = null;
            Message msg = mMessages;
            if (msg != null && msg.target == null) {
                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 {
                    //正常取出消息,設置mBlocked = false表明目前沒有阻塞
                    mBlocked = false;
                    if (prevMsg != null) {
                        prevMsg.next = msg.next;
                    } else {
                        mMessages = msg.next;
                    }
                    msg.next = null;
                    msg.markInUse();
                    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);
            }
        }            
        //非睡眠狀態下處理IdleHandler接口 
        for (int i = 0; i < pendingIdleHandlerCount; i++) { 
            final IdleHandler idler = mPendingIdleHandlers[i]; 
            // release the reference to the handler 
            mPendingIdleHandlers[i] = null; 
            boolean keep = false; 
            try { 
               keep = idler.queueIdle(); 
            } catch (Throwable t) { 
                Log.wtf(TAG, "IdleHandler threw exception", t); 
            } 
            if (!keep) { 
                synchronized (this) { 
                    mIdleHandlers.remove(idler); 
                } 
            } 
        } 
        pendingIdleHandlerCount = 0; 
        nextPollTimeoutMillis = 0;
    }        
}
複製代碼

Handler.class源碼分析:code

/*
*經過handler類向線程的消息隊列發送消息,
*每一個Handler對象中都有一個Looper對象和MessageQueue對象
*/
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());
        }
    }
    //獲取Looper對象
    mLooper = Looper.myLooper(); 
    if (mLooper == null) {...}
    //獲取消息隊列
    mQueue = mLooper.mQueue;  
    mCallback = callback;
    mAsynchronous = async;
}

/*
*多種sendMessage方法,最終都調用了同一個方法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); 
}
    
/*
*1.當Message中的callback不爲null時,執行Message中的callback中的方法。這個callback時一個Runnable接口。
*2.當Handler中的Callback接口不爲null時,執行Callback接口中的方法。
*3.直接執行Handler中的handleMessage()方法。
*/
public void dispatchMessage(Message msg) {
    // 消息Callback接口不爲null,執行Callback接口
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            //Handler Callback接口不爲null,執行接口方法
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        //處理消息
        handleMessage(msg); 
    }
}
複製代碼

有疑問有興趣的朋友歡迎留言討論。

相關文章
相關標籤/搜索