Android Handler的運行機(jī)制

Handler的運行機(jī)制

Handler的作用:

當(dāng)我們需要在子線程處理耗時的操作(例如訪問網(wǎng)絡(luò),數(shù)據(jù)庫的操作),而當(dāng)耗時的操作完成后,需要更新UI,這就需要使用Handler來處理,因為子線程不能做更新UI的操作。Handler能幫我們很容易的把任務(wù)(在子線程處理)切換回它所在的線程。簡單理解,Handler就是解決線程和線程之間的通信的。

Handler的使用

使用的handler的兩種形式:
1.在主線程使用handler;
2.在子線程使用handler。

在主線程使用handler的示例:

    public class TestHandlerActivity extends AppCompatActivity {
    
    
        private static final String TAG = "TestHandlerActivity";
        
        private Handler mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                //獲得剛才發(fā)送的Message對象,然后在這里進(jìn)行UI操作
                Log.e(TAG,"------------> msg.what = " + msg.what);
            }
        };
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_handler_test);
            initData();
        }
    
        private void initData() {
    
            //開啟一個線程模擬處理耗時的操作
            new Thread(new Runnable() {
                @Override
                public void run() {
    
                    SystemClock.sleep(2000);
                    //通過Handler發(fā)送一個消息切換回主線程(mHandler所在的線程)
                    mHandler.sendEmptyMessage(0);
                }
            }).start();
    
        }   
這里寫圖片描述

在主線程使用handler很簡單,只需在主線程創(chuàng)建一個handler對象,在子線程通過在主線程創(chuàng)建的handler對象發(fā)送Message,在handleMessage()方法中接受這個Message對象進(jìn)行處理。通過handler很容易的從子線程切換回主線程了。

那么來看看在子線程中使用是否也是如此。

 public class TestHandlerActivity extends AppCompatActivity {
    
    
        private static final String TAG = "TestHandlerActivity";
        //主線程中的handler
        private Handler mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                //獲得剛才發(fā)送的Message對象,然后在這里進(jìn)行UI操作
                Log.e(TAG,"------------> msg.what = " + msg.what);
            }
        };
        //子線程中的handler
        private Handler mHandlerThread = null;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_handler_test);
            initData();
        }
    
        private void initData() {
    
            //開啟一個線程模擬處理耗時的操作
            new Thread(new Runnable() {
                @Override
                public void run() {
    
                    SystemClock.sleep(2000);
                    //通過Handler發(fā)送一個消息切換回主線程(mHandler所在的線程)
                    mHandler.sendEmptyMessage(0);
                    //在子線程中創(chuàng)建Handler
                    mHandlerThread = new Handler(){
                        @Override
                        public void handleMessage(Message msg) {
                            super.handleMessage(msg);
                            Log.e("sub thread","---------> msg.what = " + msg.what);
                        }
                    };
    
                    mHandlerThread.sendEmptyMessage(1);
                }
            }).start();
    
        }
這里寫圖片描述

程序崩潰了。報的錯誤是沒有在子線程調(diào)用Looper.prepare()的方法。而為什么在主線程中使用不會報錯?通過源碼的分析可以解析這個問題。

在子線程中正確的使用Handler應(yīng)該是這樣的。

 public class TestHandlerActivity extends AppCompatActivity {
    
    
        private static final String TAG = "TestHandlerActivity";
    
        //主線程的Handler
        private Handler mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                //獲得剛才發(fā)送的Message對象,然后在這里進(jìn)行UI操作
                Log.e(TAG,"------------> msg.what = " + msg.what);
            }
        };
        //子線程中的Handler
        private Handler mHandlerThread = null;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_handler_test);
            initData();
        }
    
        private void initData() {
    
            //開啟一個線程模擬處理耗時的操作
            new Thread(new Runnable() {
                @Override
                public void run() {
    
                    SystemClock.sleep(2000);
                    //通過Handler發(fā)送一個消息切換回主線程(mHandler所在的線程)
                    mHandler.sendEmptyMessage(0);
    
                    //調(diào)用Looper.prepare()方法
                    Looper.prepare();
    
                    mHandlerThread = new Handler(){
                        @Override
                        public void handleMessage(Message msg) {
                            super.handleMessage(msg);
                            Log.e("sub thread","---------> msg.what = " + msg.what);
                        }
                    };
    
                    mHandlerThread.sendEmptyMessage(1);
    
                    //調(diào)用Looper.loop()方法
                    Looper.loop();
                }
            }).start();
    
        }
                
這里寫圖片描述

可以看到,通過調(diào)用Looper.prepare()運行正常,handleMessage方法中就可以接收到發(fā)送的Message。

至于為什么要調(diào)用這個方法呢?去看看源碼。

Handler的源碼分析

Handler的消息處理主要有五個部分組成,Message,Handler,Message Queue,Looper和ThreadLocal。首先簡要的了解這些對象的概念

Message:Message是在線程之間傳遞的消息,它可以在內(nèi)部攜帶少量的數(shù)據(jù),用于線程之間交換數(shù)據(jù)。Message有四個常用的字段,what字段,arg1字段,arg2字段,obj字段。what,arg1,arg2可以攜帶整型數(shù)據(jù),obj可以攜帶object對象。

Handler:它主要用于發(fā)送和處理消息的發(fā)送消息一般使用sendMessage()方法,還有其他的一系列sendXXX的方法,但最終都是調(diào)用了sendMessageAtTime方法,除了sendMessageAtFrontOfQueue()這個方法

而發(fā)出的消息經(jīng)過一系列的輾轉(zhuǎn)處理后,最終會傳遞到Handler的handleMessage方法中。

Message Queue:MessageQueue是消息隊列的意思,它主要用于存放所有通過Handler發(fā)送的消息,這部分的消息會一直存在于消息隊列中,等待被處理。每個線程中只會有一個MessageQueue對象。

Looper:每個線程通過Handler發(fā)送的消息都保存在,MessageQueue中,Looper通過調(diào)用loop()的方法,就會進(jìn)入到一個無限循環(huán)當(dāng)中,然后每當(dāng)發(fā)現(xiàn)Message Queue中存在一條消息,就會將它取出,并傳遞到Handler的handleMessage()方法中。每個線程中只會有一個Looper對象。

ThreadLocal:MessageQueue對象,和Looper對象在每個線程中都只會有一個對象,怎么能保證它只有一個對象,就通過ThreadLocal來保存。Thread Local是一個線程內(nèi)部的數(shù)據(jù)存儲類,通過它可以在指定線程中存儲數(shù)據(jù),數(shù)據(jù)存儲以后,只有在指定線程中可以獲取到存儲到數(shù)據(jù),對于其他線程來說則無法獲取到數(shù)據(jù)。

了解了這些基本概念后,我們深入源碼來了解Handler的工作機(jī)制。

MessageQueue的工作原理

MessageQueue消息隊列是通過一個單鏈表的數(shù)據(jù)結(jié)構(gòu)來維護(hù)消息列表的。下面主要看enqueueMessage方法和next()方法。如下:

    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(TAG, 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't 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;
        }

可以看出,在這個方法里主要是根據(jù)時間的順序向單鏈表中插入一條消息。

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 (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 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(TAG, "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方法是一個無限循環(huán)的方法,如果有消息返回這條消息并從鏈表中移除,而沒有消息則一直阻塞在這里。

Looper的工作原理

每個程序都有一個入口,而Android程序是基于java的,java的程序入口是靜態(tài)的main函數(shù),因此Android程序的入口也應(yīng)該為靜態(tài)的main函數(shù),在android程序中這個靜態(tài)的main在ActivityThread類中。我們來看一下這個main方法,如下:

     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());
    
            // 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.prepareMainLooper();
    
            ActivityThread thread = new ActivityThread();
            thread.attach(false);
    
            if (sMainThreadHandler == null) {
                sMainThreadHandler = thread.getHandler();
            }
    
            if (false) {
                Looper.myLooper().setMessageLogging(new
                        LogPrinter(Log.DEBUG, "ActivityThread"));
            }
    
            Looper.loop();
    
            throw new RuntimeException("Main thread loop unexpectedly exited");
        }

在main方法中系統(tǒng)調(diào)用了 Looper.prepareMainLooper();來創(chuàng)建主線程的Looper以及MessageQueue,并通過Looper.loop()來開啟主線程的消息循環(huán)。來看看Looper.prepareMainLooper()是怎么創(chuàng)建出這兩個對象的。如下:

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

可以看到,在這個方法中調(diào)用了 prepare(false);方法和 myLooper();方法,我在進(jìn)入這個兩個方法中,如下:

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

在這里可以看出,sThreadLocal對象保存了一個Looper對象,首先判斷是否已經(jīng)存在Looper對象了,以防止被調(diào)用兩次。sThreadLocal對象是ThreadLocal類型,因此保證了每個線程中只有一個Looper對象。Looper對象是什么創(chuàng)建的,我們進(jìn)入看看,如下:

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

可以看出,這里在Looper構(gòu)造函數(shù)中創(chuàng)建出了一個MessageQueue對象和保存了當(dāng)前線程。從上面可以看出一個線程中只有一個Looper對象,而Message Queue對象是在Looper構(gòu)造函數(shù)創(chuàng)建出來的,因此每一個線程也只會有一個MessageQueue對象。

對prepare方法還有一個重載的方法:如下

  public static void prepare() {
            prepare(true);
        }

prepare()僅僅是對prepare(boolean quitAllowed) 的封裝而已,在這里就很好解釋了在主線程為什么不用調(diào)用Looper.prepare()方法了。因為在主線程啟動的時候系統(tǒng)已經(jīng)幫我們自動調(diào)用了Looper.prepare()方法。

在Looper.prepareMainLooper()方法中還調(diào)用了一個方法myLooper(),我們進(jìn)去看看,如下:

        /**
         * Return the Looper object associated with the current thread.  Returns
         * null if the calling thread is not associated with a Looper.
         */
        public static Looper myLooper() {
            return sThreadLocal.get();
        }

在調(diào)用prepare()方法中在當(dāng)前線程保存一個Looper對象sThreadLocal.set(new Looper(quitAllowed));my Looper()方法就是取出當(dāng)前線程的Looper對象,保存在sMainLooper引用中。

在main()方法中還調(diào)用了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;
    
            // 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
                Printer logging = me.mLogging;
                if (logging != null) {
                    logging.println(">>>>> Dispatching to " + msg.target + " " +
                            msg.callback + ": " + msg.what);
                }
    
                msg.target.dispatchMessage(msg);
    
                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.recycle();
            }
    }
    

在這個方法里,進(jìn)入一個無限循環(huán),不斷的從MessageQueue的next方法獲取消息,而next方法是一個阻塞操作,當(dāng)沒有消息的時候一直在阻塞,當(dāng)有消息通過 msg.target.dispatchMessage(msg);這里的msg.target其實就是發(fā)送給這條消息的Handler對象。

Handler的運行機(jī)制

看看Handler的構(gòu)造方法。如下:

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

我們?nèi)タ纯礇]有Looper 對象的構(gòu)造方法:

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

可以看到,到looper對象為null,拋出 "Can't create handler inside thread that has not called Looper.prepare()"異常由這里可以知道,當(dāng)我們在子線程使用Handler的時候要手動調(diào)用Looper.prepare()創(chuàng)建一個Looper對象,之所以主線程不用,是系統(tǒng)啟動的時候幫我們自動調(diào)用了Looper.prepare()方法。

handler的工作主要包含發(fā)送和接收過程。消息的發(fā)送主要通過post和send的一系列方法,而post的一系列方法是最終是通過send的一系列方法來實現(xiàn)的。而send的一系列方法最終是通過sendMessageAtTime方法來實現(xiàn)的,除了sendMessageAtFrontOfQueue()這個方法。去看看這些一系列send的方法,如下:

    public final boolean sendMessage(Message msg)
        {
            return sendMessageDelayed(msg, 0);
        }
    
        public final boolean sendEmptyMessage(int what)
        {
            return sendEmptyMessageDelayed(what, 0);
        }  
    
        public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
            Message msg = Message.obtain();
            msg.what = what;
            return sendMessageAtTime(msg, uptimeMillis);
        }
    
        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);
        }
    
        public final boolean sendMessageAtFrontOfQueue(Message msg) {
            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, 0);
        }
    
        private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
            msg.target = this;
            if (mAsynchronous) {
                msg.setAsynchronous(true);
            }
            return queue.enqueueMessage(msg, uptimeMillis);
        }

可以看出,handler發(fā)送一條消息其實就是在消息隊列插入一條消息。在Looper的loop方法中,從Message Queue中取出消息調(diào)msg.target.dispatchMessage(msg);這里其實就是調(diào)用了Handler的dispatchMessage(msg)方法,進(jìn)去看看,如下:

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

判斷msg.callback是否為空,不為空調(diào)用 handleCallback(msg);來處理消息。其實callback是一個Runnable對象,就是Handler發(fā)送post消息傳過來的對象。

     public final boolean post(Runnable r)
        {
           return  sendMessageDelayed(getPostMessage(r), 0);
        }
    
         public final boolean postAtTime(Runnable r, long uptimeMillis)
        {
            return sendMessageAtTime(getPostMessage(r), uptimeMillis);
        }
    
        public final boolean postAtTime(Runnable r, Object token, long uptimeMillis)
        {
            return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
        }
        
       
        public final boolean postDelayed(Runnable r, long delayMillis)
        {
            return sendMessageDelayed(getPostMessage(r), delayMillis);
        }
        
        
        public final boolean postAtFrontOfQueue(Runnable r)
        {
            return sendMessageAtFrontOfQueue(getPostMessage(r));
        }

        private static Message getPostMessage(Runnable r) {
            Message m = Message.obtain();
            m.callback = r;
            return m;
        }

進(jìn)去handleCallback方法看看怎么處理消息的,如下:

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

可以看出,其實就是回調(diào)Runnable對象的run方法。Activity的runOnUiThread,View的postDelayed方法也是同樣的原理,我們先看看runOnUiThread方法,如下:

    public final void runOnUiThread(Runnable action) {
            if (Thread.currentThread() != mUiThread) {
                mHandler.post(action);
            } else {
                action.run();
            }
        }

View的postDelayed方法。如下:

 public boolean postDelayed(Runnable action, long delayMillis) {
            final AttachInfo attachInfo = mAttachInfo;
            if (attachInfo != null) {
                return attachInfo.mHandler.postDelayed(action, delayMillis);
            }
            // Assume that post will succeed later
            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
            return true;
        }

實質(zhì)上都是在UI線程中執(zhí)行了Runnable的run方法。

如果msg.callback是否為null,判斷mCallback是否為null?mCallback是一個接口,如下:

       /**
         * Callback interface you can use when instantiating a Handler to avoid
         * having to implement your own subclass of Handler.
         *
         * @param msg A {@link android.os.Message Message} object
         * @return True if no further handling is desired
         */
        public interface Callback {
            public boolean handleMessage(Message msg);
        }

CallBack其實提供了另一種使用Handler的方式,可以派生子類重寫handleMessage()方法,也可以通過設(shè)置CallBack來實現(xiàn)。

我們梳理一下我們在主線程使用Handler的過程。

首先在主線程創(chuàng)建一個Handler對象 ,并重寫handleMessage()方法。然后當(dāng)在子線程中需要進(jìn)行更新UI的操作,我們就創(chuàng)建一個Message對象,并通過handler發(fā)送這條消息出去。之后這條消息被加入到MessageQueue隊列中等待被處理,通過Looper對象會一直嘗試從Message Queue中取出待處理的消息,最后分發(fā)會Handler的handler Message()方法中。

這里寫圖片描述

END.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容