Looper、MessageQueue、Handler三者關係理解

1.Looper有兩個關鍵的放perpare(),loop()方法,在prepare方法會創建一個Looper對象,然後保存在ThreadLocal中,該方法只能被調用一次,否則會拋出異常,這樣保證了一個線程只有一個looper,Looper構造器中創建MessageQueue對象

  1. public static final void prepare() {  
  2.         if (sThreadLocal.get() != null) {  
  3.             throw new RuntimeException("Only one Looper may be created per thread");  
  4.         }  
  5.         sThreadLocal.set(new Looper(true));  
  6. }  

  7. private Looper(boolean quitAllowed) {
            mQueue = new MessageQueue(quitAllowed);
            mRun = true;
            mThread = Thread.currentThread();
    }
2.loop方法,獲取looper對象,創建一個死循環,不斷的從MessageQueue中取消息,然後調用msg.target.dispacherMessager(msg)處理消息,如果沒有消息則阻塞


  1. public static void loop() {  
  2.         final Looper me = myLooper();  
  3.         if (me == null) {  
  4.             throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");  
  5.         }  
  6.         final MessageQueue queue = me.mQueue;  
  7.   
  8.         // Make sure the identity of this thread is that of the local process,  
  9.         // and keep track of what that identity token actually is.  
  10.         Binder.clearCallingIdentity();  
  11.         final long ident = Binder.clearCallingIdentity();  
  12.   
  13.         for (;;) {  
  14.             Message msg = queue.next(); // might block  
  15.             if (msg == null) {  
  16.                 // No message indicates that the message queue is quitting.  
  17.                 return;  
  18.             }  
  19.   
  20.             // This must be in a local variable, in case a UI event sets the logger  
  21.             Printer logging = me.mLogging;  
  22.             if (logging != null) {  
  23.                 logging.println(">>>>> Dispatching to " + msg.target + " " +  
  24.                         msg.callback + ": " + msg.what);  
  25.             }  
  26.   
  27.             msg.target.dispatchMessage(msg);  
  28.   
  29.             if (logging != null) {  
  30.                 logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);  
  31.             }  
  32.   
  33.             // Make sure that during the course of dispatching the  
  34.             // identity of the thread wasn't corrupted.  
  35.             final long newIdent = Binder.clearCallingIdentity();  
  36.             if (ident != newIdent) {  
  37.                 Log.wtf(TAG, "Thread identity changed from 0x"  
  38.                         + Long.toHexString(ident) + " to 0x"  
  39.                         + Long.toHexString(newIdent) + " while dispatching to "  
  40.                         + msg.target.getClass().getName() + " "  
  41.                         + msg.callback + " what=" + msg.what);  
  42.             }  
  43.   
  44.             msg.recycle();  
  45.         }  
  46. }  
3.Handler  handler構造方法會與Looper進行關聯,然後獲取Looper中mQueue

  1. public Handler() {  
  2.         this(nullfalse);  
  3. }  
  4. public Handler(Callback callback, boolean async) {  
  5.         if (FIND_POTENTIAL_LEAKS) {  
  6.             final Class<? extends Handler> klass = getClass();  
  7.             if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&  
  8.                     (klass.getModifiers() & Modifier.STATIC) == 0) {  
  9.                 Log.w(TAG, "The following Handler class should be static or leaks might occur: " +  
  10.                     klass.getCanonicalName());  
  11.             }  
  12.         }  
  13.   
  14.         mLooper = Looper.myLooper();  
  15.         if (mLooper == null) {  
  16.             throw new RuntimeException(  
  17.                 "Can't create handler inside thread that has not called Looper.prepare()");  
  18.         }  
  19.         mQueue = mLooper.mQueue;  
  20.         mCallback = callback;  
  21.         mAsynchronous = async;  
  22.     }  

4.handler.sendMessage(msg) 會調用sendMessageAtTime,將自身對象保存在msg中 msg.target=this, 保存msg消息到隊列中queue.enqueueMessage(msg, uptimeMillis);  


5.hanler.dispacherMessager(msg) 會最終調用我複寫的handler方法

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

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