Handler 機制分析

samay發表於2017-09-25

android 子執行緒和UI執行緒的互動主要使用Handler的方法進行通訊。本文分析Handler機制

Handler 如何使用?

Handler的使用比較簡單

    public class MainActivity extends Activity{
        private Handler handler = new Handler() {  
             public void handleMessage(Message msg) {   
                  switch (msg.what) {   
                    case 0x01:
                        //do somethings
                  }
             }
          };

        @Override  
         protected void onCreate(Bundle savedInstanceState) {  
             super.onCreate(savedInstanceState);  
             setContentView(R.layout.activity_main);  
             handler = new Handler();
             new Thread(new Runnable(){
                 @Override
                 public void run(){
                      Message message = new Message();   
                      message.what = 0x01;   
                      handler.sendMessage(message);
                 }
             }).start();
         }
    }複製程式碼

如程式碼就是一個簡單的Handler的使用Demo,有如下幾個問題

  1. Handler 是否可以在子執行緒中初始化。可以,但是如下程式碼執行的話會丟擲該錯誤"Can't create handler inside thread that has not called Looper.prepare() ".說
    是不能再沒有呼叫Looper.prepare()的執行緒中建立Handler。因此如果需要線上程中建立Handler首先呼叫一下Looper.prepare
    new Thread(new Runnable() {  
        @Override  
        public void run() {  
            Handler handler = new Handler();  
        }  
    }).start();複製程式碼

這樣呼叫將不會丟擲異常。

    new Thread(new Runnable() {  
        @Override  
        public void run() {
            Looper.prepare();
            Handler handler = new Handler();  
            Looper.loop();
        }  
    }).start();複製程式碼

Looper和Handler的聯絡是什麼樣的呢?

我們看一下Handler初始化的程式碼

    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;
    }複製程式碼

可以看到如果mLooper是通過Looper.myLooper獲得一個Looper物件,如果Looper物件為空,則丟擲上述異常。那Looper.myLooper是如何定義的呢?

     public static @Nullable Looper myLooper() {
            return sThreadLocal.get();
    }複製程式碼

該方法很簡單就是從sThreadLocal物件中獲得Looper物件。如果sThreadLocal中存在就返回Looper,如果沒有就返回null。那Looper是如何存放在sThreadLocal中,
不錯就是Looper.prepare。

      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物件,如果已經存在,那麼如果還有prepare Looper則丟擲異常;否則就新建一個Looper存放到sThreadLocal中。
該程式碼同時說明每個執行緒最多一個Looper物件。

Looper採用ThreadLocal來維護各個執行緒的Looper物件。ThreadLocal是什麼呢?官方定義是:ThreadLocal實現了執行緒本地儲存。所有執行緒共享同一個ThreadLocal物件,但不同執行緒僅能訪問與其執行緒相關聯的值,一個執行緒修改ThreadLocal物件對其他執行緒沒有影響。
我們可以將ThreadLocal理解為一塊儲存區,將這一大塊儲存區分割為多塊小的儲存區,每一個執行緒擁有一塊屬於自己的儲存區,那麼對自己的儲存區操作就不會影響其他執行緒。對於ThreadLocal,則每一小塊儲存區中就儲存了與特定執行緒關聯的Looper。

主執行緒中使用Handler時為什麼沒有執行Looper.prepare()也可以使用Handler呢?其實在程式啟動的時候我們已經建立了主執行緒也依賴的Looper,程式碼在ActivityThread中main方法中。

     public static void main(String[] args) {
        ....
        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"));
        }

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
     }複製程式碼

可以看到該方法執行的是Looper.prepareMainLooper方法,可看到歸根到底還是執行prepare方法

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

Message又是如何引入到Handler機制的?

眾所周知,我們都知道Handler,Message,Looper是Handler機制不可或缺的要素。那麼Message都是如何引入到Handler.我們看一下上述例子Message是通過handler.sendMessage(message)引入到Handler中。

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

      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);
      }
      private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
             msg.target = this;
             if (mAsynchronous) {
                 msg.setAsynchronous(true);
             }
             return queue.enqueueMessage(msg, uptimeMillis);
      }複製程式碼

可以看到sendMessage最終呼叫MessageQueue中enqueueMessage

    boolean enqueueMessage(Message msg, long when) {
             ....
            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並沒有使用一個集合把資訊儲存,它只是通過使用mMessage物件表示當前需要處理訊息,然後根據時間把msg進行排序。具體方法是根據時間順序呼叫msg.next。從而為每一個訊息指定它
的下一個訊息是什麼。如果需要將msg作為隊頭插入到MessageQueue中可以呼叫sendMessageAtFrontOfQueue實現。

這樣訊息就進入到MessageQueue中,那如何從MessageQueue中將訊息取出來呢?
大家有沒有注意到Loop.prepare一般和Looper.loop對應使用。其實Looper.loop就是用來從MessageQueue中取出message。

    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 traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            try {
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            ....
        }
    }複製程式碼

上文我們知道每個Thread都有一個Looper,其實每個Looper都對應一個MessageQueue。loop方法我們獲得對應looper中的MessageQueue不斷取出msg,並傳入到dispatchMessage.
dispatchMessage方法將取出的msg傳遞到定義Handler時重寫的handleMessage方法。

    public void dispatchMessage(Message msg) {
            if (msg.callback != null) {
                handleCallback(msg);
            } else {
                if (mCallback != null) {
                    if (mCallback.handleMessage(msg)) {
                        return;
                    }
                }
                handleMessage(msg);
            }
        }複製程式碼

Handler,Message,MessageQueue,Looper流程示意圖如下:

相關文章