Android之Handler和Loooper源碼分析

1、handler在主線程和子線程互相通信(子線程和子線程的通信)簡單使用

      我們使用handler,可以實現(xiàn)主線程和子線程之間的相互通信,然后子線程和子線程之間的通信,如果不清楚,基本用法請先參考我的這篇博客

Android之用Handler實現(xiàn)主線程和子線程互相通信以及子線程和子線程之間的通信  http://blog.csdn.net/u011068702/article/details/75577005

 
2、handler在主線程為什么不需要調(diào)用Looper.prepare()

我們看下Looper.java這個類,它在安卓android.os包下,我們看這個類的一開始的注釋

 

      * <p>This is a typical example of the implementation of a Looper thread,
      * using the separation of {@link #prepare} and {@link #loop} to create an
      * initial Handler to communicate with the Looper.
      *
      * <pre>
      *  class LooperThread extends Thread {
      *      public Handler mHandler;
      *
      *      public void run() {
      *          Looper.prepare();
      *
      *          mHandler = new Handler() {
      *              public void handleMessage(Message msg) {
      *                  // process incoming messages here
      *              }
      *          };
      *
      *          Looper.loop();
      *      }
      *  }</pre>


很明顯,在一個線程里面需要使用Handler之前需要Looper.prepare(),但是我們平時在主線程更新UI的時候,為什么沒有看到這行代碼呢?

 

我們看下ActivityThread.java這個類,它在安卓包名android.app目錄下,我們知道ActivityThread.java這個類是安卓程序的入口,我們看下main函數(shù)的代碼

 

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


我們可以看到有Looper.prepareMainLooper()函數(shù),我們點(diǎn)擊進(jìn)去


        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(false)函數(shù),我們再點(diǎn)擊這個函數(shù)


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


我們可以看到這里就調(diào)用prepare函數(shù),所以主線程不需要調(diào)用Looper.prepare()函數(shù),然后我們也可以看到這里有行這個代碼


            if (sThreadLocal.get() != null) {
                throw new RuntimeException("Only one Looper may be created per thread");
            }


在Looper.java類中,我們的Looper保存在ThreadLocal里面


static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

用ThreadLocal修飾的變量,可以理解為只有當(dāng)前線程可以改變這個參數(shù),其它線程不可以改變這個參數(shù),如果你對ThreadLocal不清楚,單獨(dú)可以先看下我這篇博客的簡單使用


 java之ThreadLocal簡單使用總結(jié)    http://blog.csdn.net/u011068702/article/details/75770226

 

            if (sThreadLocal.get() != null) {
                throw new RuntimeException("Only one Looper may be created per thread");
            }

上面的代碼寫得很清楚了,如果當(dāng)前的sThreadLocal對象里面有個Looper對象,那么就會拋出異常,而且英文也提示了,所以,一個線程為什么只能有一個Looper對象的原因,所以如果在程序里面,每個線程調(diào)用2次Looper.prepare()就會報錯,我們再看這行代碼

 

        sThreadLocal.set(new Looper(quitAllowed));


點(diǎn)擊Looper的構(gòu)造函數(shù)

 

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


里面構(gòu)建了一個MessageQueue對象,上面我們分析一個線程只有一個Looper對象,那么Looper對象只構(gòu)建一個,也就意味著MessageQueue對象也只構(gòu)建一次,所以一個線程也只有一個MessageQueue對象的原因。
 

在main函數(shù)里面,也調(diào)用了Looper.loop()函數(shù),后面分析這個方法

 
 
3、分析Handler發(fā)送消息

我們先看下Handler.java的構(gòu)造方法,這個類在安卓 android.os這個目錄下面

 

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

這里看出初始化變量,然后保存了當(dāng)前線程中的Looper對象。

 

    發(fā)送消息的時候我們一般都這樣寫
    handler.sendMessage(message)

 

所以我們點(diǎn)擊 sendMessage方法看下

 

        public final boolean sendMessage(Message msg)
        {
            return sendMessageDelayed(msg, 0);
        }


再點(diǎn)擊sendMessageDelayed(msg, 0);

 

        public final boolean sendMessageDelayed(Message msg, long delayMillis)
        {
            if (delayMillis < 0) {
                delayMillis = 0;
            }
            return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
        }


再點(diǎn)擊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);
        }


再點(diǎn)擊enqueueMessage(queue, msg, uptimeMillis)

 

        private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
            msg.target = this;
            if (mAsynchronous) {
                msg.setAsynchronous(true);
            }
            return queue.enqueueMessage(msg, uptimeMillis);
        }

這里msg.target就是Handler對象本身,再點(diǎn)擊queue.enqueueMessage(msg, uptimeMillis)(在MessageQueue這個類里面)



     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("MessageQueue", 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;
        }


可以看出MessageQueue從而按照時間將所有的Message排序


然后我們不是最后還調(diào)用了Looper.loop()函數(shù)嗎?點(diǎn)擊進(jìn)去


    /**
         * 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
                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.recycleUnchecked();
            }
        }

Looper.loop()方法里起了一個死循環(huán),不斷的判斷MessageQueue中的消息是否為空,如果為空則直接return掉,然后執(zhí)行queue.next()方法,點(diǎn)擊進(jìn)去



    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 (false) Log.v("MessageQueue", "Returning message: " + msg);
                            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("MessageQueue", "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;
            }
        }

Message的出棧操作,里面可能對線程,并發(fā)控制做了一些限制等。獲取到棧頂?shù)腗essage對象,然后就執(zhí)行這個函數(shù)

 

 msg.target.dispatchMessage(msg);


我么知道m(xù)sg.tartget對象就是handler對象,我們點(diǎn)擊dispatchMessage(msg)函數(shù)

 


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


我們可以知道m(xù)sg.callback  != null的時候,就執(zhí)行了handleCallback(msg)

 

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


意味著這個Runable執(zhí)行 run方法

 

然后還有就是也可能會執(zhí)行到這里來

 

            handleMessage(msg);


點(diǎn)擊進(jìn)去,

 

        /**
         * Subclasses must implement this to receive messages.
         */
        public void handleMessage(Message msg) {
        }


我們一般在主線程這樣寫接收消息

 

        public Handler mHandlerCToP = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch(msg.what) {
                    case 0:
                        break;
                    default:
                        break;
                }
            }
        };

也就意味著把handleMessage()方法重寫了,所以我們的代碼,有地方發(fā)送消息,loop()不斷分發(fā)消息,當(dāng)收到了,如果接收到了,我們重寫handleMessage就會掉到這個地方來,得到我需要的數(shù)據(jù)。

 
 
4、分析runOnUiThread方法和Handler.post方法和view的post方法
    1、分析runOnUiThread()方法

            我們一般在子線程調(diào)用這個方法也可以來更新UI

           

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
     
                }
            });

              點(diǎn)擊進(jìn)去

 

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

             再點(diǎn)擊mHandler.post(action) 方法

 

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

           點(diǎn)擊進(jìn)去

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

         看到了嗎?其實最后還是到了發(fā)送消息這里,一開始我們不是分析了Looper.loop()里面的dispatchMessage()方法嗎?

    我么知道m(xù)sg.tartget對象就是handler對象,我們點(diǎn)擊dispatchMessage(msg)函數(shù)
     
        /**
         * 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);
            }
        }

         很明顯程序,會走h(yuǎn)andleCallback(msg);所以會調(diào)到handler.java里面的這個方法

 
 

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

         這樣就執(zhí)行了這個Runnable

 
 
    2、分析handler.post()方法

          上面那個函數(shù)內(nèi)部有handler.post()這個方法,已分析

         
    3、分析view.post()方法

          點(diǎn)擊view.post()方法

 

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

         可以發(fā)現(xiàn)其調(diào)用的就是activity中默認(rèn)保存的handler對象的post方法
              

 


 



  作者:chen.yu
深信服三年半工作經(jīng)驗,目前就職游戲廠商,希望能和大家交流和學(xué)習(xí),
微信公眾號:編程入門到禿頭 或掃描下面二維碼
零基礎(chǔ)入門進(jìn)階人工智能(鏈接)