Handler源碼解析

  • 我們一般使用Handler流程是這樣,handel分析版本6.0.1:
 Handler     h =new Handler(){
            @Override public void handleMessage(Message msg) {
                super.handleMessage(msg);
            }
        };
        Message message = new Message();
        message.obj="xxx";
        h.sendMessage(message);
  • 那我們就從構(gòu)造看起
public Handler() {
      this(null, false);
 }
public Handler(Callback callback, boolean async) {
       if (FIND_POTENTIAL_LEAKS) {
          final Class<? extends Handler> klass = getClass();
           if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
             Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                klass.getCanonicalName());
       }
     }
   //這里開(kāi)始獲取looper,由于我們的looper在主線程已經(jīng)給我初始化了一個(gè),所以如果我們?cè)谥骶€創(chuàng)建handler這個(gè)looper就是ManLooer
    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;
    }
  public Handler(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
      mQueue = looper.mQueue;
       mCallback = callback;
       mAsynchronous = async;
  }

這里我們可以看到他最終調(diào)用到了三個(gè)參數(shù)的構(gòu)造方法。

  • 二接下來(lái)我們分析發(fā)送方法:
 public final boolean sendMessage(Message msg)
   {
       return sendMessageDelayed(msg, 0);
   }

sendmessage最終調(diào)用的方法是sendMessageAtTime

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

最終在enqueueMessage方法中將此條消息添加到消息隊(duì)列,等待Looper取出分發(fā),我們看看MessageQueue的enqueueMessage方法,注意這里 msg.target = this;就是handler在enqueueMessage中賦值了

 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ìn)隊(duì)列

  • 三現(xiàn)在我們消息也有是不是需要取出消息發(fā)送了,取出分發(fā)消息就是looper干的事情,我們看看

我前面也說(shuō)了,Looper的looper方法是分發(fā)消息的,那么他是在什么時(shí)候被調(diào)用的呢,還記得我們?yōu)槭裁丛谥骶€程不用手動(dòng)調(diào)用looper嗎?那是因?yàn)锳ctivityThread的Man方法中已經(jīng)調(diào)用了

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

看到了吧, 在這創(chuàng)建了looper并且開(kāi)啟了輪訓(xùn),所以

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

我們清楚可以看到 msg.target.dispatchMessage(msg);這個(gè)方法,之前也說(shuō)過(guò)msg.target值的就是handler所以他就有回調(diào)到handleMessage方法了

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

以上就是Handler的一個(gè)正常的分發(fā)流程,相信看完了,你也明白了,為什么我們?nèi)绻谧泳€程需要手動(dòng)創(chuàng)建looper,以及他們之前的關(guān)系.

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

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

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