Android中的Looper,MessageQueue,Handler的理解

Looper中的ThreadLocal對象sThreadLocal保存有Looper對象,在其構造方法中會獲取當前的線程並且創建一個消息隊列mQueue

private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
 }
prepare方法(一個靜態方法)中會創建一個Looper實例保存到sThreadLocal中,這個實例裏有一個mQueue
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));
    }

因爲Looper.prepare()在一個線程中只能調用一次,所以MessageQueue在一個線程中只會存在一個。否則就會報RuntimeException異常。

然後Looper.loop()會讓當前線程進入一個無限循環,不端從MessageQueue的實例中讀取消息,然後回調msg.target.dispatchMessage(msg)方法。在Activity的啓動代碼中,已經在當前UI線程調用了Looper.prepare()和Looper.loop()方法。

public static void loop() {
        final Looper me = myLooper();//myLooper方法獲得Looper實例
        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);//<span style="color: rgb(51, 51, 51); font-family: Arial; font-size: 14px; line-height: 26px;">msg.target.dispatchMessage(msg)最終調用</span><span style="font-family: Arial;">Handler實例的handleMessage方法</span>

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

問題:Looper如何綁定當前線程?Looper裏有ThreadLocal變量,ThreadLocal爲每一個線程維護變量的副本,在ThreadLocal類中有一個Map,用於存儲每一個線程的變量副本

2.Handler‘

可以看到msg.target是一個Handler實例,下面看看他的dispatchMessage方法

public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }
如果不設置Callback就會調用我們自己重寫的handleMessage方法

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();//得到當前線程的Looper
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;<span style="font-family: Arial, Helvetica, sans-serif;">//得到Looper實例中保存的消息隊列</span>
        mCallback = callback;
        mAsynchronous = async;
    }

通過得到Looper和MessageQueue,就保證了handler的實例與我們Looper實例中MessageQueue關聯上了。

我們常用的Message的sendToTarget會調用handler的sendMessage方法。

public void sendToTarget() {
        target.sendMessage(this);
    }


下面看看Handler的sendMessage方法和

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

再看sendEmptyMessageDelayed

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

Handler發送消息的時候最後會調用dispatchMessage方法,下圖可以看出如果沒有給msg設置callback就會調用我們自己寫的handleMessage。

  1. public void dispatchMessage(Message msg) {  
  2.         if (msg.callback != null) {  
  3.             handleCallback(msg);  
  4.         } else {  
  5.             if (mCallback != null) {  
  6.                 if (mCallback.handleMessage(msg)) {  
  7.                     return;  
  8.                 }  
  9.             }  
  10.             handleMessage(msg);  
  11.         }  
  12.     }
總結:Looper.prepare()創建一個Looper,並且放到這個線程的ThreadLocal裏保存。Looper創建一個MessageQueue。Looper.loop();進入一個循環不斷的從MessageQueue裏面讀取Message。Handler類中有MessageQueue和Looper對象作爲其成員變量,在其構造方法中通過Looper的myLooper()方法獲得Looper對象,從而獲得MessageQueue。即Handler中有Looper,Looper中有MessageQueue,MessageQueue中有Handler。






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