Android面試題-Handler機制

Handler機制相信很多人在面試Android崗的時候都會被問到相關的問題,雖然已經有很多人整理了,但我還是想自己整理一下,權當是給自己的加深自己對於handler機制的理解。

首先我們先了解下關於Handler的四個主要組成部分:Handler、Looper、Messagequeue、Message

  • Looper :負責關聯線程以及消息的分發,在該線程下從 MessageQueue 獲取 Message,分發給 Handler。
  • MessageQueue :是個隊列,負責消息的存儲與管理,負責管理由 Handler 發送過來的 Message。
  • Handler : 負責發送並處理消息,面向開發者,提供 API,並隱藏背後實現的細節。
  • Message:final類不可繼承, 實現了Parcelable 序列化接口,可以在不同進程之間傳遞。

 

來看Handler的構造方法:

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

    public Handler(@Nullable Callback callback) {
        this(callback, false);
    }

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

    public Handler(@NonNull Looper looper, @Nullable Callback callback) {
        this(looper, callback, false);
    }

     /**
     * @hide
     */
    @UnsupportedAppUsage
    public Handler(boolean async) {
        this(null, async);
    }

    /**
     * @hide
     */
    public Handler(@Nullable 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 " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

     /**
     * @hide
     */
    @UnsupportedAppUsage
    public Handler(@NonNull Looper looper, @Nullable Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

當我們調用handler構造方法,都會走到最後的兩個使用@hide註解的方法,我們可以看到,初始化了mLooper 和 mQueue。當我們沒有構造方法中傳Looper,會通過 Looper.myLooper() 方法來當前線程綁定的Looper,從這個方法一層層的往下找。

Looper#myLooper

public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

ThreadLocal#get

public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

可以看到該方法通過ThreadLocal來拿到當前線程綁定的Looper。那麼 ThreadLocal在哪裏和Looper綁定線程呢?

Looper#prepare

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

ThreadLocal#set

public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

可以看到,通過調用 Looper.prepare 方法,通過ThreadLocal將當前線程和Looper綁定起來。

然後調用Looper#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;
        ...
        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }
            ...
            try {
                //關鍵方法--------
                msg.target.dispatchMessage(msg);
                //關鍵方法---------
                if (observer != null) {
                    observer.messageDispatched(token, msg);
                }
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } catch (Exception exception) {
                if (observer != null) {
                    observer.dispatchingThrewException(token, msg, exception);
                }
                throw exception;
            } finally {
                ThreadLocalWorkSource.restore(origWorkSource);
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
        }
    }

MessageQueue#next

@UnsupportedAppUsage
    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 (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        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 (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);
            }


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

                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }
            pendingIdleHandlerCount = 0;
            nextPollTimeoutMillis = 0;
        }
    }

我簡化了一些,關鍵代碼標識出來了,在Looper中通過調用queue.next方法獲取message,而在MessageQueue.next中也是通過死循環遍歷msg.next,保證了當前的handler不會退出。在獲死循環取到msg,調用 msg.target.dispatchMessage(msg)方法,Message中的target就是我們當前線程綁定的handler

@UnsupportedAppUsage
    /*package*/ Handler target;

所以相當於調用了Handler#dispatchMessage(msg):

/**
     * Handle system messages here.
     */
    public void dispatchMessage(@NonNull Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

可以看到,回調了handlerMessage方法,到這裏是不是很熟悉了,我們來看看我們經常使用handler的方法

val mHandler = object : Handler() {
            override fun handleMessage(msg: Message) {
                super.handleMessage(msg)
                when(msg.what){
                    //根據消息去做想要的事
                }
            }
        }

這樣,我們發送的消息就通過該回調方法被我們獲取到了。

總結:

Handler 中聲明瞭 一個 LooperThreadLocal ,Looper中又實例化了一個MessageQueue,在Handler的構造方法中,調用了Looper.myLooper()來獲取線程綁定的Looper,所以在實例化Handler前需要通過調用Looper.prepare() 方法來創建 Looper,並且該方法通過 ThreadLocal 將Looper與當前線程綁定。Looper.loop()方法則會開始不斷嘗試從 MessageQueue 中獲取 Message, 並執行msg.target.dispatchMessage(msg) ,msg.target 就是發送該消息的 Handler,Handler的dispatchMessage(msg)方法中回調了handleMessage(msg),這樣就能在Handler中的handleMessage(msg)中處理接收到的msg。

但是光知道這個還不夠,還會有以下問題:

問題一、爲什麼Looper死循環沒能造成UI線程卡死?

我們來看ActivityThread#main方法

public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
        AndroidOs.install();
        CloseGuard.setEnabled(false);
        Environment.initForCurrentUser();
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);
        Process.setArgV0("<pre-initialized>");
        Looper.prepareMainLooper();
        long startSeq = 0;
        if (args != null) {
            for (int i = args.length - 1; i >= 0; --i) {
                if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
                    startSeq = Long.parseLong(
                            args[i].substring(PROC_START_SEQ_IDENT.length()));
                }
            }
        }
        ActivityThread thread = new ActivityThread();
        thread.attach(false, startSeq);
        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }
        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);

        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

可以看到loop方法在main方法的最後,loop之後就是拋異常了。之所以死循環,可以保證UI線程不會被退出,因爲Android中界面繪製都是通過Handler消息來實現,這樣可以讓界面保持可繪製的狀態。真正會卡死主線程的操作是在回調方法onCreate/onStart/onResume等操作時間過長,會導致掉幀,甚至發生ANR,looper.loop本身不會導致應用卡死。

問題二、爲什麼在主線程使用handler不需要管Looper?

ActivityThread#main方法中,有調用到 Looper.prepareMainLooper();  和  Looper.loop(); 兩個方法;

Looper#prepareMainLooper:

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

可以看到該方法中調用了prepare方法,並且通過myLooper調用到了ThreadLocal.get方法拿到當前主線程的Looper。

問題三、在使用Handler時有沒有碰到如下警告?

因爲直接使用內部類的方式實例化handler會造成handler持有當前的activity實例,從而導致內存泄漏。通常做法使用靜態內部類 或者 單獨拎出來,使用弱引用來持有當前的activity。

如下代碼:

class MyHandler(activity: ActivityA) : Handler() {
        //持有弱引用HandlerActivity,GC回收時會被回收掉.
        private val mActivity: WeakReference<ActivityA> = WeakReference(activity)

        override fun handleMessage(msg: Message) {
            val activity = mActivity.get()
            super.handleMessage(msg)
            if (activity != null) {
                //執行業務邏輯
            }
        }
    }

好了,就是以上這些,我要去學習了,我愛學習...

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章