1. 程式人生 > >Android Handler訊息機制原始碼解讀

Android Handler訊息機制原始碼解讀

這個東西在網上已經被很多人寫過了,自己也看過很多文章,大概因為自己比較愚笨一直對此不太理解,最近重新從原始碼的角度閱讀,並且配合著網上的一些相關部落格才算明白了一些

本文從原始碼的角度順著程式碼的執行去原始碼,限於作者的表達能力及技術水平,可能會有些問題,請耐性閱讀,如有不解或有誤的地方歡迎提出

從ActivityThread的入口去看

ActivityThread.class

    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物件 Looper.prepareMainLooper(); //這裡建立了ActivityThread物件,隨之一起初始化的還有一個用於處理相應訊息的Handler物件 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"); }

這裡是App的入口,有著我們非常熟悉的main方法,
Looper.prepareMainLooper();這個方法建立了屬於主執行緒的Looper物件,並且將其放到了ThreadLocal中,再在Looper.loop();中取出Looper物件開啟迴圈

看下Looper.prepareMainLooper();方法的原始碼
Looper.class

    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
    private static Looper sMainLooper;  // guarded by Looper.class

    final MessageQueue mQueue;
    final Thread mThread;

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

    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();
        }
    }
    
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }


prepareMainLooper()方法首先呼叫了prepare(false)方法,傳入的quitAllowed引數的意思是是否允許退出迴圈,主線是不允許的,其他的都是允許退出的,prepare方法首先要從sThreadLocal中get()一下判斷當前執行緒中是否已經有過Looper物件,如果已經有了就無法重複建立,如果沒有就初始化Looper物件然後放到sThreadLocal中去,sThreadLocal這個變數是ThreadLocal型別的,ThreadLocal這個類是用來儲存執行緒內的本地變數,或者是說,當前執行緒可以訪問的全域性變數,有興趣可以瞭解下原始碼,這裡就不說了.
Looper初始化的方法是私有的,所以只能通過prepare方法去建立,Looper初始化的時候順便初始化了MessageQueue物件和獲取了mThread這個當前執行緒的物件.然後prepare方法執行完成之後prepareMainLooper()方法還判斷了sMainLooper是否為空然後呼叫myLooper()方法取出放到sThreadLocal 中的Looper物件賦值給sMainLooper物件

所以根據上面的程式碼能得出結論,一個執行緒只有一個Looper物件,Looper物件中有一個MessageQueue物件

接下來看下Looper.loop()方法的原始碼:

Looper.class

    /**
     * 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
            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 {
                //分配給Message所對應的Handler處理
                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();
        }
    }

loop方法首先呼叫myLooper()方法來獲取當前執行緒存放在sThreadLocal中的Looper物件,然後進行一下非空判斷,在獲取到對應的
MessageQueue物件.然後來看關鍵程式碼:Message msg = queue.next(); 這句程式碼就是從訊息佇列裡面取出訊息,然後msg.target.dispatchMessage(msg);去分配給相應的Handler處理,msg.target是Message對應的Handler.
然後在呼叫msg.recycleUnchecked();對Message物件進行回收,等待再利用,如果next()取出的訊息為空就退出迴圈

接下來看queue.next();方法是如何將訊息取出來的
MessageQueue.class

    // True if the message queue can be quit.
    //是否允許退出,在初始化MessageQueue的時候傳入賦值
    private final boolean mQuitAllowed;

    @SuppressWarnings("unused")
    //這個屬性是有關底層c相關的東西,因為C相關的我也不會所以更底層的程式碼也沒看過,但是不影響去理解這個訊息機制
    private long mPtr; // used by native code
    
    //訊息佇列
    Message mMessages;
    //空閒時執行的程式碼
    private final ArrayList<IdleHandler> mIdleHandlers = new ArrayList<IdleHandler>();
    private SparseArray<FileDescriptorRecord> mFileDescriptorRecords;
    private IdleHandler[] mPendingIdleHandlers;
    //是否退出
    private boolean mQuitting;

    // Indicates whether next() is blocked waiting in pollOnce() with a non-zero timeout.
    //是否阻塞
    private boolean mBlocked;


    MessageQueue(boolean quitAllowed) {
        mQuitAllowed = quitAllowed;
        mPtr = nativeInit();
    }


    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;
        }
        
        //這個值用於控制IdleHandler是否被執行
        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }
            
            //這個是主要的阻塞方法,當訊息佇列中沒有時間或者需要執行的訊息沒到執行時間,就會阻塞,更底層是涉及到Linux的一些東西,我也不甚瞭解
            //nextPollTimeoutMillis這個引數是阻塞時間
            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());
                }
                //如果msg不為空
                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 (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // No more messages.
                    //沒有訊息為-1,無期限等待,直到有新訊息喚醒
                    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.
                //只有在上面沒有取到合適的訊息的時候才會執行到這一步,判斷pendingIdleHandlerCount是否小於0,只有小於0才會賦值,
                //小於0的情況只有在呼叫next方法進來的時候在迴圈體外面初始化
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                //經過上面的賦值,如果pendingIdleHandlerCount值小於等於0就不會執行下面的mIdleHandlers的相關程式碼
                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.
            //迴圈遍歷IdleHandler並執行,這裡的程式碼只有在沒有Message的時候才會執行
            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(TAG, "IdleHandler threw exception", t);
                }
                
                //false就會刪除掉
                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }

            // Reset the idle handler count to 0 so we do not run them again.
            //這個引數賦值為0,就不會被重新賦值,所以沒呼叫一次next方法,IdleHandler中的程式碼最多隻會執行一次
            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;
        }
    }

至此迴圈去訊息的程式碼的邏輯差不多就這些,每次迴圈都會從MessageQueue中的Message中取出訊息,Message不僅僅是訊息的載體,它還是一個單鏈表結構,中間有一個next屬性指向下一個Message.還有就是mIdleHandlers,這個是用來在空閒時間,即在沒有取到合適執行的Message的時候回去檢測呼叫執行的程式碼,並且每次next只會執行一次,使用方法如下:

        Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
            @Override
            public boolean queueIdle() {
                //do something
                return false;
            }
        });

下面來從Handler入口來看下怎麼把訊息放到訊息隊列當中去

        Handler handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {

                return false;
            }
        });

        handler.sendMessage(Message.obtain());

從Handler的初始化來引入:

Handler.calss

    final Looper mLooper;//Loper物件,如果不傳入則預設是本執行緒的Looper物件,如果為空則拋異常
    final MessageQueue mQueue;
    final Callback mCallback;
    final boolean mAsynchronous;//是否非同步,預設為false
    
    public Handler() {
        this(null, false);
    }
    
    public Handler(Callback callback) {
        this(callback, false);
    }

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

    public Handler(boolean async) {
        this(null, async);
    }
    
    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;
    }