Android Handler异步通信:深入详解Handler机制源码

<div id="article_content" class="article_content clearfix csdn-tracking-statistics" data-pid="blog" data-mod="popu_307" data-dsm="post">
                    <div class="markdown_views">
                <h1 id="前言"><a name="t0"></a>前言</h1>


<ul>
<li>在<code>Android</code>开发的<strong>多线程应用场景</strong>中,<code>Handler</code>机制十分常用</li>
<li>今天,我将手把手带你深入分析 <code>Handler</code>机制的源码,希望你们会喜欢</li>
</ul>


<hr>






<h1 id="目录"><a name="t1"></a>目录</h1>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-4450ea6a59b6b183.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<hr>






<h1 id="1-handler-机制简介"><a name="t2"></a>1. Handler 机制简介</h1>


<ul>
<li><p>定义 <br>
一套 <code>Android</code> 消息传递机制</p></li>
<li><p>作用</p></li>
</ul>


<p>在多线程的应用场景中,<strong>将工作线程中需更新<code>UI</code>的操作信息 传递到 <code>UI</code>主线程</strong>,从而实现 工作线程对<code>UI</code>的更新处理,最终实现异步消息的处理 <br>
<img src="http://upload-images.jianshu.io/upload_images/944365-4a64038632c4c88f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<ul>
<li>为什么要用 <code>Handler</code>消息传递机制 <br>
答:<strong>多个线程并发更新UI的同时 保证线程安全</strong>。具体描述如下</li>
</ul>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-7479b4a8b8fe48bf.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<ul>
<li>总结 <br>
使用<code>Handler</code>的原因:将工作线程需操作<code>UI</code>的消息 传递 到主线程,使得主线程可根据工作线程的需求 更新<code>UI</code>,<strong>从而避免线程操作不安全的问题</strong></li>
</ul>


<hr>






<h1 id="2-储备知识"><a name="t3"></a>2. 储备知识</h1>


<p>在阅读<code>Handler</code>机制的源码分析前,请务必了解<code>Handler</code>的一些储备知识:<strong>相关概念、使用方式 &amp; 工作原理</strong></p>






<h3 id="21-相关概念"><a name="t4"></a>2.1 相关概念</h3>


<p>关于 <code>Handler</code> 机制中的相关概念如下:</p>


<blockquote>
  <p>在下面的讲解中,我将直接使用英文名讲解,即 <code>Handler</code>、<code>Message</code>、<code>Message Queue</code>、<code>Looper</code>,希望大家先熟悉相关概念</p>
</blockquote>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-d08903087cb575d9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>






<h3 id="22-使用方式"><a name="t5"></a>2.2 使用方式</h3>


<p></p><ul> <br>
<li><code>Handler</code>使用方式 因<strong>发送消息到消息队列的方式不同而不同</strong>,共分为2种:使用<code>Handler.sendMessage()</code>、使用<code>Handler.post()</code></li>
<li>下面的源码分析将依据使用步骤讲解 <br></li></ul><p></p>


<blockquote>
  <p>若还不了解,请务必阅读文章:<a href="https://blog.csdn.net/carson_ho/article/details/80305411" target="_blank">Android:这是一份Handler消息传递机制 的使用教程</a>
  </p>
</blockquote>


<h3 id="23-工作原理"><a name="t6"></a>2.3 工作原理</h3>


<ul>
<li>理解<code>Handler</code>机制的工作原理,能很大程序帮助理解其源码</li>
<li>具体请看文章:<a href="https://blog.csdn.net/carson_ho/article/details/80175876" target="_blank">Android Handler:图文解析 Handler通信机制 的工作原理</a></li>
</ul>


<hr>


<h1 id="3-handler机制的核心类"><a name="t7"></a>3. Handler机制的核心类</h1>


<p>在源码分析前,先来了解<code>Handler</code>机制中的核心类</p>






<h3 id="31-类说明"><a name="t8"></a>3.1 类说明</h3>


<p><code>Handler</code>机制 中有3个重要的类:</p>


<ul>
<li>处理器 类<code>(Handler)</code></li>
<li>消息队列 类<code>(MessageQueue)</code></li>
<li>循环器 类<code>(Looper)</code></li>
</ul>


<h3 id="32-类图"><a name="t9"></a>3.2 类图</h3>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-868877030acf2e45.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>






<h3 id="33-具体介绍"><a name="t10"></a>3.3 具体介绍</h3>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-a6a41fa7961184e2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<hr>






<h1 id="4-源码分析"><a name="t11"></a>4. 源码分析</h1>


<p></p><ul> <br>
<li>下面的源码分析将根据 <code>Handler</code>的使用步骤进行</li>
<li><code>Handler</code>使用方式 因<strong>发送消息到消息队列的方式不同而不同</strong>,共分为2种:使用<code>Handler.sendMessage()</code>、使用<code>Handler.post()</code> <br></li></ul><p></p>


<blockquote>
  <p>若还不了解,请务必阅读文章:<a href="https://blog.csdn.net/carson_ho/article/details/80305411" target="_blank">Android:这是一份Handler消息传递机制 的使用教程</a>
  </p><li>下面的源码分析将依据上述2种使用方式进行</li>
  <p></p>
</blockquote>




<h3 id="方式1使用-handlersendmessage"><a name="t12"></a>方式1:使用 Handler.sendMessage()</h3>


<ul>
<li>使用步骤</li>
</ul>






<pre class="prettyprint" name="code"><code class="hljs java has-numbering"><span class="hljs-javadoc">/** 
  * 此处以 匿名内部类 的使用方式为例
  */</span>
  <span class="hljs-comment">// 步骤1:在主线程中 通过匿名内部类 创建Handler类对象</span>
            <span class="hljs-keyword">private</span> Handler mhandler = <span class="hljs-keyword">new</span>  Handler(){
                <span class="hljs-comment">// 通过复写handlerMessage()从而确定更新UI的操作</span>
                <span class="hljs-annotation">@Override</span>
                <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">handleMessage</span>(Message msg) {
                        ...<span class="hljs-comment">// 需执行的UI操作</span>
                    }
            };


  <span class="hljs-comment">// 步骤2:创建消息对象</span>
    Message msg = Message.obtain(); <span class="hljs-comment">// 实例化消息对象</span>
    msg.what = <span class="hljs-number">1</span>; <span class="hljs-comment">// 消息标识</span>
    msg.obj = <span class="hljs-string">"AA"</span>; <span class="hljs-comment">// 消息内容存放</span>


  <span class="hljs-comment">// 步骤3:在工作线程中 通过Handler发送消息到消息队列中</span>
  <span class="hljs-comment">// 多线程可采用AsyncTask、继承Thread类、实现Runnable</span>
   mHandler.sendMessage(msg);


  <span class="hljs-comment">// 步骤4:开启工作线程(同时启动了Handler)</span>
  <span class="hljs-comment">// 多线程可采用AsyncTask、继承Thread类、实现Runnable</span></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li><li style="color: rgb(153, 153, 153);">17</li><li style="color: rgb(153, 153, 153);">18</li><li style="color: rgb(153, 153, 153);">19</li><li style="color: rgb(153, 153, 153);">20</li><li style="color: rgb(153, 153, 153);">21</li><li style="color: rgb(153, 153, 153);">22</li><li style="color: rgb(153, 153, 153);">23</li></ul></pre>


<ul>
<li>源码分析 <br>
下面,我将根据上述每个步骤进行源码分析</li>
</ul>






<h3 id="步骤1在主线程中-通过匿名内部类-创建handler类对象"><a name="t13"></a>步骤1:在主线程中 通过匿名内部类 创建Handler类对象</h3>






<pre class="prettyprint" name="code"><code class="hljs java has-numbering"><span class="hljs-javadoc">/** 
  * 具体使用
  */</span>
    <span class="hljs-keyword">private</span> Handler mhandler = <span class="hljs-keyword">new</span>  Handler(){
        <span class="hljs-comment">// 通过复写handlerMessage()从而确定更新UI的操作</span>
        <span class="hljs-annotation">@Override</span>
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">handleMessage</span>(Message msg) {
                ...<span class="hljs-comment">// 需执行的UI操作</span>
            }
    };


<span class="hljs-javadoc">/** 
  * 源码分析:Handler的构造方法
  * 作用:初始化Handler对象 &amp; 绑定线程
  * 注:
  *   a. Handler需绑定 线程才能使用;绑定后,Handler的消息处理会在绑定的线程中执行
  *   b. 绑定方式 = 先指定Looper对象,从而绑定了 Looper对象所绑定的线程(因为Looper对象本已绑定了对应线程)
  *   c. 即:指定了Handler对象的 Looper对象 = 绑定到了Looper对象所在的线程
  */</span>
  <span class="hljs-keyword">public</span> <span class="hljs-title">Handler</span>() {


            <span class="hljs-keyword">this</span>(<span class="hljs-keyword">null</span>, <span class="hljs-keyword">false</span>);
            <span class="hljs-comment">// -&gt;&gt;分析1</span>


    }
<span class="hljs-javadoc">/** 
  * 分析1:this(null, false) = Handler(null,false)
  */</span>
  <span class="hljs-keyword">public</span> <span class="hljs-title">Handler</span>(Callback callback, <span class="hljs-keyword">boolean</span> async) {


            ...<span class="hljs-comment">// 仅贴出关键代码</span>


            <span class="hljs-comment">// 1. 指定Looper对象</span>
                mLooper = Looper.myLooper();
                <span class="hljs-keyword">if</span> (mLooper == <span class="hljs-keyword">null</span>) {
                    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(
                        <span class="hljs-string">"Can't create handler inside thread that has not called Looper.prepare()"</span>);
                }
                <span class="hljs-comment">// Looper.myLooper()作用:获取当前线程的Looper对象;若线程无Looper对象则抛出异常</span>
                <span class="hljs-comment">// 即 :若线程中无创建Looper对象,则也无法创建Handler对象</span>
                <span class="hljs-comment">// 故 若需在子线程中创建Handler对象,则需先创建Looper对象</span>
                <span class="hljs-comment">// 注:可通过Loop.getMainLooper()可以获得当前进程的主线程的Looper对象</span>


            <span class="hljs-comment">// 2. 绑定消息队列对象(MessageQueue)</span>
                mQueue = mLooper.mQueue;
                <span class="hljs-comment">// 获取该Looper对象中保存的消息队列对象(MessageQueue)</span>
                <span class="hljs-comment">// 至此,保证了handler对象 关联上 Looper对象中MessageQueue</span>
    }</code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li><li style="color: rgb(153, 153, 153);">17</li><li style="color: rgb(153, 153, 153);">18</li><li style="color: rgb(153, 153, 153);">19</li><li style="color: rgb(153, 153, 153);">20</li><li style="color: rgb(153, 153, 153);">21</li><li style="color: rgb(153, 153, 153);">22</li><li style="color: rgb(153, 153, 153);">23</li><li style="color: rgb(153, 153, 153);">24</li><li style="color: rgb(153, 153, 153);">25</li><li style="color: rgb(153, 153, 153);">26</li><li style="color: rgb(153, 153, 153);">27</li><li style="color: rgb(153, 153, 153);">28</li><li style="color: rgb(153, 153, 153);">29</li><li style="color: rgb(153, 153, 153);">30</li><li style="color: rgb(153, 153, 153);">31</li><li style="color: rgb(153, 153, 153);">32</li><li style="color: rgb(153, 153, 153);">33</li><li style="color: rgb(153, 153, 153);">34</li><li style="color: rgb(153, 153, 153);">35</li><li style="color: rgb(153, 153, 153);">36</li><li style="color: rgb(153, 153, 153);">37</li><li style="color: rgb(153, 153, 153);">38</li><li style="color: rgb(153, 153, 153);">39</li><li style="color: rgb(153, 153, 153);">40</li><li style="color: rgb(153, 153, 153);">41</li><li style="color: rgb(153, 153, 153);">42</li><li style="color: rgb(153, 153, 153);">43</li><li style="color: rgb(153, 153, 153);">44</li><li style="color: rgb(153, 153, 153);">45</li><li style="color: rgb(153, 153, 153);">46</li><li style="color: rgb(153, 153, 153);">47</li><li style="color: rgb(153, 153, 153);">48</li></ul></pre>


<ul>
<li><p>从上面可看出: <br>
当创建<code>Handler</code>对象时,则通过 构造方法 自动关联当前线程的<code>Looper</code>对象 &amp; 对应的消息队列对象<code>(MessageQueue)</code>,从而 自动绑定了 实现创建<code>Handler</code>对象操作的线程</p></li>
<li><p>那么,当前线程的<code>Looper</code>对象 &amp; 对应的消息队列对象<code>(MessageQueue)</code> 是什么时候创建的呢?</p>


<blockquote>
  <p>在上述使用步骤中,并无 创建<code>Looper</code>对象 &amp; 对应的消息队列对象<code>(MessageQueue)</code>这1步</p>
</blockquote></li>
</ul>






<h3 id="步骤1前的隐式操作1创建循环器对象looper-消息队列对象messagequeue"><a name="t14"></a>步骤1前的隐式操作1:创建循环器对象(Looper) &amp; 消息队列对象(MessageQueue)</h3>


<ul>
<li>步骤介绍</li>
</ul>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-d261c6a482b61e02.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<ul>
<li>源码分析</li>
</ul>






<pre class="prettyprint" name="code"><code class="hljs java has-numbering"><span class="hljs-javadoc">/** 
  * 源码分析1:Looper.prepare()
  * 作用:为当前线程(子线程) 创建1个循环器对象(Looper),同时也生成了1个消息队列对象(MessageQueue)
  * 注:需在子线程中手动调用该方法
  */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">void</span> <span class="hljs-title">prepare</span>() {


        <span class="hljs-keyword">if</span> (sThreadLocal.get() != <span class="hljs-keyword">null</span>) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(<span class="hljs-string">"Only one Looper may be created per thread"</span>);
        }
        <span class="hljs-comment">// 1. 判断sThreadLocal是否为null,否则抛出异常</span>
        <span class="hljs-comment">//即 Looper.prepare()方法不能被调用两次 = 1个线程中只能对应1个Looper实例</span>
        <span class="hljs-comment">// 注:sThreadLocal = 1个ThreadLocal对象,用于存储线程的变量</span>


        sThreadLocal.set(<span class="hljs-keyword">new</span> Looper(<span class="hljs-keyword">true</span>));
        <span class="hljs-comment">// 2. 若为初次Looper.prepare(),则创建Looper对象 &amp; 存放在ThreadLocal变量中</span>
        <span class="hljs-comment">// 注:Looper对象是存放在Thread线程里的</span>
        <span class="hljs-comment">// 源码分析Looper的构造方法-&gt;&gt;分析a</span>
    }


  <span class="hljs-javadoc">/** 
    * 分析a:Looper的构造方法
    **/</span>


        <span class="hljs-keyword">private</span> <span class="hljs-title">Looper</span>(<span class="hljs-keyword">boolean</span> quitAllowed) {


            mQueue = <span class="hljs-keyword">new</span> MessageQueue(quitAllowed);
            <span class="hljs-comment">// 1. 创建1个消息队列对象(MessageQueue)</span>
            <span class="hljs-comment">// 即 当创建1个Looper实例时,会自动创建一个与之配对的消息队列对象(MessageQueue)</span>


            mRun = <span class="hljs-keyword">true</span>;
            mThread = Thread.currentThread();
        }


<span class="hljs-javadoc">/** 
  * 源码分析2:Looper.prepareMainLooper()
  * 作用:为 主线程(UI线程) 创建1个循环器对象(Looper),同时也生成了1个消息队列对象(MessageQueue)
  * 注:该方法在主线程(UI线程)创建时自动调用,即 主线程的Looper对象自动生成,不需手动生成
  */</span>
    <span class="hljs-comment">// 在Android应用进程启动时,会默认创建1个主线程(ActivityThread,也叫UI线程)</span>
    <span class="hljs-comment">// 创建时,会自动调用ActivityThread的1个静态的main()方法 = 应用程序的入口</span>
    <span class="hljs-comment">// main()内则会调用Looper.prepareMainLooper()为主线程生成1个Looper对象</span>


      <span class="hljs-javadoc">/** 
        * 源码分析:main()
        **/</span>
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span>(String[] args) {
            ... <span class="hljs-comment">// 仅贴出关键代码</span>


            Looper.prepareMainLooper(); 
            <span class="hljs-comment">// 1. 为主线程创建1个Looper对象,同时生成1个消息队列对象(MessageQueue)</span>
            <span class="hljs-comment">// 方法逻辑类似Looper.prepare()</span>
            <span class="hljs-comment">// 注:prepare():为子线程中创建1个Looper对象</span>




            ActivityThread thread = <span class="hljs-keyword">new</span> ActivityThread(); 
            <span class="hljs-comment">// 2. 创建主线程</span>


            Looper.loop(); 
            <span class="hljs-comment">// 3. 自动开启 消息循环 -&gt;&gt;下面将详细分析</span>


        }</code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li><li style="color: rgb(153, 153, 153);">17</li><li style="color: rgb(153, 153, 153);">18</li><li style="color: rgb(153, 153, 153);">19</li><li style="color: rgb(153, 153, 153);">20</li><li style="color: rgb(153, 153, 153);">21</li><li style="color: rgb(153, 153, 153);">22</li><li style="color: rgb(153, 153, 153);">23</li><li style="color: rgb(153, 153, 153);">24</li><li style="color: rgb(153, 153, 153);">25</li><li style="color: rgb(153, 153, 153);">26</li><li style="color: rgb(153, 153, 153);">27</li><li style="color: rgb(153, 153, 153);">28</li><li style="color: rgb(153, 153, 153);">29</li><li style="color: rgb(153, 153, 153);">30</li><li style="color: rgb(153, 153, 153);">31</li><li style="color: rgb(153, 153, 153);">32</li><li style="color: rgb(153, 153, 153);">33</li><li style="color: rgb(153, 153, 153);">34</li><li style="color: rgb(153, 153, 153);">35</li><li style="color: rgb(153, 153, 153);">36</li><li style="color: rgb(153, 153, 153);">37</li><li style="color: rgb(153, 153, 153);">38</li><li style="color: rgb(153, 153, 153);">39</li><li style="color: rgb(153, 153, 153);">40</li><li style="color: rgb(153, 153, 153);">41</li><li style="color: rgb(153, 153, 153);">42</li><li style="color: rgb(153, 153, 153);">43</li><li style="color: rgb(153, 153, 153);">44</li><li style="color: rgb(153, 153, 153);">45</li><li style="color: rgb(153, 153, 153);">46</li><li style="color: rgb(153, 153, 153);">47</li><li style="color: rgb(153, 153, 153);">48</li><li style="color: rgb(153, 153, 153);">49</li><li style="color: rgb(153, 153, 153);">50</li><li style="color: rgb(153, 153, 153);">51</li><li style="color: rgb(153, 153, 153);">52</li><li style="color: rgb(153, 153, 153);">53</li><li style="color: rgb(153, 153, 153);">54</li><li style="color: rgb(153, 153, 153);">55</li><li style="color: rgb(153, 153, 153);">56</li><li style="color: rgb(153, 153, 153);">57</li><li style="color: rgb(153, 153, 153);">58</li><li style="color: rgb(153, 153, 153);">59</li><li style="color: rgb(153, 153, 153);">60</li><li style="color: rgb(153, 153, 153);">61</li><li style="color: rgb(153, 153, 153);">62</li></ul></pre>


<p>总结:</p>


<p></p><ul> <br>
<li>创建主线程时,会自动调用<code>ActivityThread</code>的1个静态的<code>main()</code>;而<code>main()</code>内则会调用<code>Looper.prepareMainLooper()</code>为主线程生成1个<code>Looper</code>对象,同时也会生成其对应的<code>MessageQueue</code>对象 <br></li></ul><p></p>


<blockquote>
  <ol>
  <li>即 主线程的<code>Looper</code>对象自动生成,不需手动生成;而子线程的<code>Looper</code>对象则需手动通过<code>Looper.prepare()</code>创建 <br></li>
  <li>在子线程若不手动创建<code>Looper</code>对象 则无法生成<code>Handler</code>对象</li>
  <li><p>根据<code>Handler</code>的作用(在主线程更新<code>UI</code>),<strong>故<code>Handler</code>实例的创建场景 主要在主线程</strong></p></li>
  <li><p>生成<code>Looper</code> &amp; <code>MessageQueue</code>对象后,则会自动进入消息循环:<code>Looper.loop()</code>,即又是另外一个隐式操作。</p></li>
  
  </ol>
</blockquote>


<h3 id="步骤1前的隐式操作2消息循环"><a name="t15"></a>步骤1前的隐式操作2:消息循环</h3>


<p>此处主要分析的是<code>Looper</code>类中的<code>loop()</code>方法</p>






<pre class="prettyprint" name="code"><code class="hljs java has-numbering"><span class="hljs-javadoc">/** 
  * 源码分析: Looper.loop()
  * 作用:消息循环,即从消息队列中获取消息、分发消息到Handler
  * 特别注意:
  *       a. 主线程的消息循环不允许退出,即无限循环
  *       b. 子线程的消息循环允许退出:调用消息队列MessageQueue的quit()
  */</span>
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">loop</span>() {


        ...<span class="hljs-comment">// 仅贴出关键代码</span>


        <span class="hljs-comment">// 1. 获取当前Looper的消息队列</span>
            <span class="hljs-keyword">final</span> Looper me = myLooper();
            <span class="hljs-keyword">if</span> (me == <span class="hljs-keyword">null</span>) {
                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(<span class="hljs-string">"No Looper; Looper.prepare() wasn't called on this thread."</span>);
            }
            <span class="hljs-comment">// myLooper()作用:返回sThreadLocal存储的Looper实例;若me为null 则抛出异常</span>
            <span class="hljs-comment">// 即loop()执行前必须执行prepare(),从而创建1个Looper实例</span>


            <span class="hljs-keyword">final</span> MessageQueue queue = me.mQueue;
            <span class="hljs-comment">// 获取Looper实例中的消息队列对象(MessageQueue)</span>


        <span class="hljs-comment">// 2. 消息循环(通过for循环)</span>
            <span class="hljs-keyword">for</span> (;;) {


            <span class="hljs-comment">// 2.1 从消息队列中取出消息</span>
            Message msg = queue.next(); 
            <span class="hljs-keyword">if</span> (msg == <span class="hljs-keyword">null</span>) {
                <span class="hljs-keyword">return</span>;
            }
            <span class="hljs-comment">// next():取出消息队列里的消息</span>
            <span class="hljs-comment">// 若取出的消息为空,则线程阻塞</span>
            <span class="hljs-comment">// -&gt;&gt; 分析1 </span>


            <span class="hljs-comment">// 2.2 派发消息到对应的Handler</span>
            msg.target.dispatchMessage(msg);
            <span class="hljs-comment">// 把消息Message派发给消息对象msg的target属性</span>
            <span class="hljs-comment">// target属性实际是1个handler对象</span>
            <span class="hljs-comment">// -&gt;&gt;分析2</span>


        <span class="hljs-comment">// 3. 释放消息占据的资源</span>
        msg.recycle();
        }
}


<span class="hljs-javadoc">/** 
  * 分析1:queue.next()
  * 定义:属于消息队列类(MessageQueue)中的方法
  * 作用:出队消息,即从 消息队列中 移出该消息
  */</span>
  Message next() {


        ...<span class="hljs-comment">// 仅贴出关键代码</span>


        <span class="hljs-comment">// 该参数用于确定消息队列中是否还有消息</span>
        <span class="hljs-comment">// 从而决定消息队列应处于出队消息状态 or 等待状态</span>
        <span class="hljs-keyword">int</span> nextPollTimeoutMillis = <span class="hljs-number">0</span>;


        <span class="hljs-keyword">for</span> (;;) {
            <span class="hljs-keyword">if</span> (nextPollTimeoutMillis != <span class="hljs-number">0</span>) {
                Binder.flushPendingCommands();
            }


        <span class="hljs-comment">// nativePollOnce方法在native层,若是nextPollTimeoutMillis为-1,此时消息队列处于等待状态 </span>
        nativePollOnce(ptr, nextPollTimeoutMillis);


        <span class="hljs-keyword">synchronized</span> (<span class="hljs-keyword">this</span>) {


            <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> now = SystemClock.uptimeMillis();
            Message prevMsg = <span class="hljs-keyword">null</span>;
            Message msg = mMessages;


            <span class="hljs-comment">// 出队消息,即 从消息队列中取出消息:按创建Message对象的时间顺序</span>
            <span class="hljs-keyword">if</span> (msg != <span class="hljs-keyword">null</span>) {
                <span class="hljs-keyword">if</span> (now &lt; msg.when) {
                    nextPollTimeoutMillis = (<span class="hljs-keyword">int</span>) Math.min(msg.when - now, Integer.MAX_VALUE);
                } <span class="hljs-keyword">else</span> {
                    <span class="hljs-comment">// 取出了消息</span>
                    mBlocked = <span class="hljs-keyword">false</span>;
                    <span class="hljs-keyword">if</span> (prevMsg != <span class="hljs-keyword">null</span>) {
                        prevMsg.next = msg.next;
                    } <span class="hljs-keyword">else</span> {
                        mMessages = msg.next;
                    }
                    msg.next = <span class="hljs-keyword">null</span>;
                    <span class="hljs-keyword">if</span> (DEBUG) Log.v(TAG, <span class="hljs-string">"Returning message: "</span> + msg);
                    msg.markInUse();
                    <span class="hljs-keyword">return</span> msg;
                }
            } <span class="hljs-keyword">else</span> {


                <span class="hljs-comment">// 若 消息队列中已无消息,则将nextPollTimeoutMillis参数设为-1</span>
                <span class="hljs-comment">// 下次循环时,消息队列则处于等待状态</span>
                nextPollTimeoutMillis = -<span class="hljs-number">1</span>;
            }


            ......
        }
           .....
       }
}<span class="hljs-comment">// 回到分析原处</span>


<span class="hljs-javadoc">/** 
  * 分析2:dispatchMessage(msg)
  * 定义:属于处理者类(Handler)中的方法
  * 作用:派发消息到对应的Handler实例 &amp; 根据传入的msg作出对应的操作
  */</span>
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">dispatchMessage</span>(Message msg) {


    <span class="hljs-comment">// 1. 若msg.callback属性不为空,则代表使用了post(Runnable r)发送消息</span>
    <span class="hljs-comment">// 则执行handleCallback(msg),即回调Runnable对象里复写的run()</span>
    <span class="hljs-comment">// 上述结论会在讲解使用“post(Runnable r)”方式时讲解</span>
        <span class="hljs-keyword">if</span> (msg.callback != <span class="hljs-keyword">null</span>) {
            handleCallback(msg);
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-keyword">if</span> (mCallback != <span class="hljs-keyword">null</span>) {
                <span class="hljs-keyword">if</span> (mCallback.handleMessage(msg)) {
                    <span class="hljs-keyword">return</span>;
                }
            }


            <span class="hljs-comment">// 2. 若msg.callback属性为空,则代表使用了sendMessage(Message msg)发送消息(即此处需讨论的)</span>
            <span class="hljs-comment">// 则执行handleMessage(msg),即回调复写的handleMessage(msg) -&gt;&gt; 分析3</span>
            handleMessage(msg);


        }
    }


  <span class="hljs-javadoc">/** 
   * 分析3:handleMessage(msg)
   * 注:该方法 = 空方法,在创建Handler实例时复写 = 自定义消息处理方式
   **/</span>
   <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">handleMessage</span>(Message msg) {  
          ... <span class="hljs-comment">// 创建Handler实例时复写</span>
   } </code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li><li style="color: rgb(153, 153, 153);">17</li><li style="color: rgb(153, 153, 153);">18</li><li style="color: rgb(153, 153, 153);">19</li><li style="color: rgb(153, 153, 153);">20</li><li style="color: rgb(153, 153, 153);">21</li><li style="color: rgb(153, 153, 153);">22</li><li style="color: rgb(153, 153, 153);">23</li><li style="color: rgb(153, 153, 153);">24</li><li style="color: rgb(153, 153, 153);">25</li><li style="color: rgb(153, 153, 153);">26</li><li style="color: rgb(153, 153, 153);">27</li><li style="color: rgb(153, 153, 153);">28</li><li style="color: rgb(153, 153, 153);">29</li><li style="color: rgb(153, 153, 153);">30</li><li style="color: rgb(153, 153, 153);">31</li><li style="color: rgb(153, 153, 153);">32</li><li style="color: rgb(153, 153, 153);">33</li><li style="color: rgb(153, 153, 153);">34</li><li style="color: rgb(153, 153, 153);">35</li><li style="color: rgb(153, 153, 153);">36</li><li style="color: rgb(153, 153, 153);">37</li><li style="color: rgb(153, 153, 153);">38</li><li style="color: rgb(153, 153, 153);">39</li><li style="color: rgb(153, 153, 153);">40</li><li style="color: rgb(153, 153, 153);">41</li><li style="color: rgb(153, 153, 153);">42</li><li style="color: rgb(153, 153, 153);">43</li><li style="color: rgb(153, 153, 153);">44</li><li style="color: rgb(153, 153, 153);">45</li><li style="color: rgb(153, 153, 153);">46</li><li style="color: rgb(153, 153, 153);">47</li><li style="color: rgb(153, 153, 153);">48</li><li style="color: rgb(153, 153, 153);">49</li><li style="color: rgb(153, 153, 153);">50</li><li style="color: rgb(153, 153, 153);">51</li><li style="color: rgb(153, 153, 153);">52</li><li style="color: rgb(153, 153, 153);">53</li><li style="color: rgb(153, 153, 153);">54</li><li style="color: rgb(153, 153, 153);">55</li><li style="color: rgb(153, 153, 153);">56</li><li style="color: rgb(153, 153, 153);">57</li><li style="color: rgb(153, 153, 153);">58</li><li style="color: rgb(153, 153, 153);">59</li><li style="color: rgb(153, 153, 153);">60</li><li style="color: rgb(153, 153, 153);">61</li><li style="color: rgb(153, 153, 153);">62</li><li style="color: rgb(153, 153, 153);">63</li><li style="color: rgb(153, 153, 153);">64</li><li style="color: rgb(153, 153, 153);">65</li><li style="color: rgb(153, 153, 153);">66</li><li style="color: rgb(153, 153, 153);">67</li><li style="color: rgb(153, 153, 153);">68</li><li style="color: rgb(153, 153, 153);">69</li><li style="color: rgb(153, 153, 153);">70</li><li style="color: rgb(153, 153, 153);">71</li><li style="color: rgb(153, 153, 153);">72</li><li style="color: rgb(153, 153, 153);">73</li><li style="color: rgb(153, 153, 153);">74</li><li style="color: rgb(153, 153, 153);">75</li><li style="color: rgb(153, 153, 153);">76</li><li style="color: rgb(153, 153, 153);">77</li><li style="color: rgb(153, 153, 153);">78</li><li style="color: rgb(153, 153, 153);">79</li><li style="color: rgb(153, 153, 153);">80</li><li style="color: rgb(153, 153, 153);">81</li><li style="color: rgb(153, 153, 153);">82</li><li style="color: rgb(153, 153, 153);">83</li><li style="color: rgb(153, 153, 153);">84</li><li style="color: rgb(153, 153, 153);">85</li><li style="color: rgb(153, 153, 153);">86</li><li style="color: rgb(153, 153, 153);">87</li><li style="color: rgb(153, 153, 153);">88</li><li style="color: rgb(153, 153, 153);">89</li><li style="color: rgb(153, 153, 153);">90</li><li style="color: rgb(153, 153, 153);">91</li><li style="color: rgb(153, 153, 153);">92</li><li style="color: rgb(153, 153, 153);">93</li><li style="color: rgb(153, 153, 153);">94</li><li style="color: rgb(153, 153, 153);">95</li><li style="color: rgb(153, 153, 153);">96</li><li style="color: rgb(153, 153, 153);">97</li><li style="color: rgb(153, 153, 153);">98</li><li style="color: rgb(153, 153, 153);">99</li><li style="color: rgb(153, 153, 153);">100</li><li style="color: rgb(153, 153, 153);">101</li><li style="color: rgb(153, 153, 153);">102</li><li style="color: rgb(153, 153, 153);">103</li><li style="color: rgb(153, 153, 153);">104</li><li style="color: rgb(153, 153, 153);">105</li><li style="color: rgb(153, 153, 153);">106</li><li style="color: rgb(153, 153, 153);">107</li><li style="color: rgb(153, 153, 153);">108</li><li style="color: rgb(153, 153, 153);">109</li><li style="color: rgb(153, 153, 153);">110</li><li style="color: rgb(153, 153, 153);">111</li><li style="color: rgb(153, 153, 153);">112</li><li style="color: rgb(153, 153, 153);">113</li><li style="color: rgb(153, 153, 153);">114</li><li style="color: rgb(153, 153, 153);">115</li><li style="color: rgb(153, 153, 153);">116</li><li style="color: rgb(153, 153, 153);">117</li><li style="color: rgb(153, 153, 153);">118</li><li style="color: rgb(153, 153, 153);">119</li><li style="color: rgb(153, 153, 153);">120</li><li style="color: rgb(153, 153, 153);">121</li><li style="color: rgb(153, 153, 153);">122</li><li style="color: rgb(153, 153, 153);">123</li><li style="color: rgb(153, 153, 153);">124</li><li style="color: rgb(153, 153, 153);">125</li><li style="color: rgb(153, 153, 153);">126</li><li style="color: rgb(153, 153, 153);">127</li><li style="color: rgb(153, 153, 153);">128</li><li style="color: rgb(153, 153, 153);">129</li><li style="color: rgb(153, 153, 153);">130</li><li style="color: rgb(153, 153, 153);">131</li><li style="color: rgb(153, 153, 153);">132</li><li style="color: rgb(153, 153, 153);">133</li><li style="color: rgb(153, 153, 153);">134</li><li style="color: rgb(153, 153, 153);">135</li></ul></pre>


<p>总结:</p>


<ul>
<li>消息循环的操作 = 消息出队 + 分发给对应的<code>Handler</code>实例</li>
<li>分发给对应的<code>Handler</code>的过程:根据出队消息的归属者通过<code>dispatchMessage(msg)</code>进行分发,最终回调复写的<code>handleMessage(Message msg)</code>,从而实现 消息处理 的操作</li>
<li>特别注意:在进行消息分发时<code>(dispatchMessage(msg))</code>,会进行1次发送方式的判断: <br>
<ol><li>若<code>msg.callback</code>属性不为空,则代表使用了<code>post(Runnable r)</code>发送消息,则直接回调<code>Runnable</code>对象里复写的<code>run()</code></li>
<li>若<code>msg.callback</code>属性为空,则代表使用了<code>sendMessage(Message msg)</code>发送消息,则回调复写的<code>handleMessage(msg)</code></li></ol></li>
</ul>


<p><strong>至此,关于步骤1的源码分析讲解完毕</strong>。总结如下</p>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-c18fc8b78d4ec73c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<hr>


<h3 id="步骤2创建消息对象"><a name="t16"></a>步骤2:创建消息对象</h3>






<pre class="prettyprint" name="code"><code class="hljs java has-numbering"><span class="hljs-javadoc">/** 
  * 具体使用
  */</span>
    Message msg = Message.obtain(); <span class="hljs-comment">// 实例化消息对象</span>
    msg.what = <span class="hljs-number">1</span>; <span class="hljs-comment">// 消息标识</span>
    msg.obj = <span class="hljs-string">"AA"</span>; <span class="hljs-comment">// 消息内容存放</span>


<span class="hljs-javadoc">/** 
  * 源码分析:Message.obtain()
  * 作用:创建消息对象
  * 注:创建Message对象可用关键字new 或 Message.obtain()
  */</span>
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Message <span class="hljs-title">obtain</span>() {


        <span class="hljs-comment">// Message内部维护了1个Message池,用于Message消息对象的复用</span>
        <span class="hljs-comment">// 使用obtain()则是直接从池内获取</span>
        <span class="hljs-keyword">synchronized</span> (sPoolSync) {
            <span class="hljs-keyword">if</span> (sPool != <span class="hljs-keyword">null</span>) {
                Message m = sPool;
                sPool = m.next;
                m.next = <span class="hljs-keyword">null</span>;
                m.flags = <span class="hljs-number">0</span>; <span class="hljs-comment">// clear in-use flag</span>
                sPoolSize--;
                <span class="hljs-keyword">return</span> m;
            }
            <span class="hljs-comment">// 建议:使用obtain()”创建“消息对象,避免每次都使用new重新分配内存</span>
        }
        <span class="hljs-comment">// 若池内无消息对象可复用,则还是用关键字new创建</span>
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Message();


    }</code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li><li style="color: rgb(153, 153, 153);">17</li><li style="color: rgb(153, 153, 153);">18</li><li style="color: rgb(153, 153, 153);">19</li><li style="color: rgb(153, 153, 153);">20</li><li style="color: rgb(153, 153, 153);">21</li><li style="color: rgb(153, 153, 153);">22</li><li style="color: rgb(153, 153, 153);">23</li><li style="color: rgb(153, 153, 153);">24</li><li style="color: rgb(153, 153, 153);">25</li><li style="color: rgb(153, 153, 153);">26</li><li style="color: rgb(153, 153, 153);">27</li><li style="color: rgb(153, 153, 153);">28</li><li style="color: rgb(153, 153, 153);">29</li><li style="color: rgb(153, 153, 153);">30</li><li style="color: rgb(153, 153, 153);">31</li></ul></pre>


<ul>
<li>总结</li>
</ul>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-79f00f900b3471c0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>






<h3 id="步骤3在工作线程中-发送消息到消息队列中"><a name="t17"></a>步骤3:在工作线程中 发送消息到消息队列中</h3>


<blockquote>
  <p>多线程的实现方式:<code>AsyncTask</code>、继承<code>Thread</code>类、实现<code>Runnable</code> </p>
</blockquote>






<pre class="prettyprint" name="code"><code class="hljs java has-numbering"><span class="hljs-javadoc">/** 
  * 具体使用
  */</span>


    mHandler.sendMessage(msg);


<span class="hljs-javadoc">/** 
  * 源码分析:mHandler.sendMessage(msg)
  * 定义:属于处理器类(Handler)的方法
  * 作用:将消息 发送 到消息队列中(Message -&gt;&gt; MessageQueue)
  */</span>
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">sendMessage</span>(Message msg)
    {
        <span class="hljs-keyword">return</span> sendMessageDelayed(msg, <span class="hljs-number">0</span>);
        <span class="hljs-comment">// -&gt;&gt;分析1</span>
    }


         <span class="hljs-javadoc">/** 
           * 分析1:sendMessageDelayed(msg, 0)
           **/</span>
           <span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">sendMessageDelayed</span>(Message msg, <span class="hljs-keyword">long</span> delayMillis)
            {
                <span class="hljs-keyword">if</span> (delayMillis &lt; <span class="hljs-number">0</span>) {
                    delayMillis = <span class="hljs-number">0</span>;
                }


                <span class="hljs-keyword">return</span> sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
                <span class="hljs-comment">// -&gt;&gt; 分析2</span>
            }


         <span class="hljs-javadoc">/** 
           * 分析2:sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis)
           **/</span>
           <span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">sendMessageAtTime</span>(Message msg, <span class="hljs-keyword">long</span> uptimeMillis) {
                    <span class="hljs-comment">// 1. 获取对应的消息队列对象(MessageQueue)</span>
                    MessageQueue queue = mQueue;


                    <span class="hljs-comment">// 2. 调用了enqueueMessage方法 -&gt;&gt;分析3</span>
                    <span class="hljs-keyword">return</span> enqueueMessage(queue, msg, uptimeMillis);
                }


         <span class="hljs-javadoc">/** 
           * 分析3:enqueueMessage(queue, msg, uptimeMillis)
           **/</span>
            <span class="hljs-keyword">private</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">enqueueMessage</span>(MessageQueue queue, Message msg, <span class="hljs-keyword">long</span> uptimeMillis) {
                 <span class="hljs-comment">// 1. 将msg.target赋值为this</span>
                 <span class="hljs-comment">// 即 :把 当前的Handler实例对象作为msg的target属性</span>
                 msg.target = <span class="hljs-keyword">this</span>;
                 <span class="hljs-comment">// 请回忆起上面说的Looper的loop()中消息循环时,会从消息队列中取出每个消息msg,然后执行msg.target.dispatchMessage(msg)去处理消息</span>
                 <span class="hljs-comment">// 实际上则是将该消息派发给对应的Handler实例        </span>


                <span class="hljs-comment">// 2. 调用消息队列的enqueueMessage()</span>
                <span class="hljs-comment">// 即:Handler发送的消息,最终是保存到消息队列-&gt;&gt;分析4</span>
                <span class="hljs-keyword">return</span> queue.enqueueMessage(msg, uptimeMillis);
        }


        <span class="hljs-javadoc">/** 
          * 分析4:queue.enqueueMessage(msg, uptimeMillis)
          * 定义:属于消息队列类(MessageQueue)的方法
          * 作用:入队,即 将消息 根据时间 放入到消息队列中(Message -&gt;&gt; MessageQueue)
          * 采用单链表实现:提高插入消息、删除消息的效率
          */</span>
          <span class="hljs-keyword">boolean</span> enqueueMessage(Message msg, <span class="hljs-keyword">long</span> when) {


                ...<span class="hljs-comment">// 仅贴出关键代码</span>


                <span class="hljs-keyword">synchronized</span> (<span class="hljs-keyword">this</span>) {


                    msg.markInUse();
                    msg.when = when;
                    Message p = mMessages;
                    <span class="hljs-keyword">boolean</span> needWake;


                    <span class="hljs-comment">// 判断消息队列里有无消息</span>
                        <span class="hljs-comment">// a. 若无,则将当前插入的消息 作为队头 &amp; 若此时消息队列处于等待状态,则唤醒</span>
                        <span class="hljs-keyword">if</span> (p == <span class="hljs-keyword">null</span> || when == <span class="hljs-number">0</span> || when &lt; p.when) {
                            msg.next = p;
                            mMessages = msg;
                            needWake = mBlocked;
                        } <span class="hljs-keyword">else</span> {
                            needWake = mBlocked &amp;&amp; p.target == <span class="hljs-keyword">null</span> &amp;&amp; msg.isAsynchronous();
                            Message prev;


                        <span class="hljs-comment">// b. 判断消息队列里有消息,则根据 消息(Message)创建的时间 插入到队列中</span>
                            <span class="hljs-keyword">for</span> (;;) {
                                prev = p;
                                p = p.next;
                                <span class="hljs-keyword">if</span> (p == <span class="hljs-keyword">null</span> || when &lt; p.when) {
                                    <span class="hljs-keyword">break</span>;
                                }
                                <span class="hljs-keyword">if</span> (needWake &amp;&amp; p.isAsynchronous()) {
                                    needWake = <span class="hljs-keyword">false</span>;
                                }
                            }


                            msg.next = p; 
                            prev.next = msg;
                        }


                        <span class="hljs-keyword">if</span> (needWake) {
                            nativeWake(mPtr);
                        }
                    }
                    <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;
            }


<span class="hljs-comment">// 之后,随着Looper对象的无限消息循环</span>
<span class="hljs-comment">// 不断从消息队列中取出Handler发送的消息 &amp; 分发到对应Handler</span>
<span class="hljs-comment">// 最终回调Handler.handleMessage()处理消息</span></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li><li style="color: rgb(153, 153, 153);">17</li><li style="color: rgb(153, 153, 153);">18</li><li style="color: rgb(153, 153, 153);">19</li><li style="color: rgb(153, 153, 153);">20</li><li style="color: rgb(153, 153, 153);">21</li><li style="color: rgb(153, 153, 153);">22</li><li style="color: rgb(153, 153, 153);">23</li><li style="color: rgb(153, 153, 153);">24</li><li style="color: rgb(153, 153, 153);">25</li><li style="color: rgb(153, 153, 153);">26</li><li style="color: rgb(153, 153, 153);">27</li><li style="color: rgb(153, 153, 153);">28</li><li style="color: rgb(153, 153, 153);">29</li><li style="color: rgb(153, 153, 153);">30</li><li style="color: rgb(153, 153, 153);">31</li><li style="color: rgb(153, 153, 153);">32</li><li style="color: rgb(153, 153, 153);">33</li><li style="color: rgb(153, 153, 153);">34</li><li style="color: rgb(153, 153, 153);">35</li><li style="color: rgb(153, 153, 153);">36</li><li style="color: rgb(153, 153, 153);">37</li><li style="color: rgb(153, 153, 153);">38</li><li style="color: rgb(153, 153, 153);">39</li><li style="color: rgb(153, 153, 153);">40</li><li style="color: rgb(153, 153, 153);">41</li><li style="color: rgb(153, 153, 153);">42</li><li style="color: rgb(153, 153, 153);">43</li><li style="color: rgb(153, 153, 153);">44</li><li style="color: rgb(153, 153, 153);">45</li><li style="color: rgb(153, 153, 153);">46</li><li style="color: rgb(153, 153, 153);">47</li><li style="color: rgb(153, 153, 153);">48</li><li style="color: rgb(153, 153, 153);">49</li><li style="color: rgb(153, 153, 153);">50</li><li style="color: rgb(153, 153, 153);">51</li><li style="color: rgb(153, 153, 153);">52</li><li style="color: rgb(153, 153, 153);">53</li><li style="color: rgb(153, 153, 153);">54</li><li style="color: rgb(153, 153, 153);">55</li><li style="color: rgb(153, 153, 153);">56</li><li style="color: rgb(153, 153, 153);">57</li><li style="color: rgb(153, 153, 153);">58</li><li style="color: rgb(153, 153, 153);">59</li><li style="color: rgb(153, 153, 153);">60</li><li style="color: rgb(153, 153, 153);">61</li><li style="color: rgb(153, 153, 153);">62</li><li style="color: rgb(153, 153, 153);">63</li><li style="color: rgb(153, 153, 153);">64</li><li style="color: rgb(153, 153, 153);">65</li><li style="color: rgb(153, 153, 153);">66</li><li style="color: rgb(153, 153, 153);">67</li><li style="color: rgb(153, 153, 153);">68</li><li style="color: rgb(153, 153, 153);">69</li><li style="color: rgb(153, 153, 153);">70</li><li style="color: rgb(153, 153, 153);">71</li><li style="color: rgb(153, 153, 153);">72</li><li style="color: rgb(153, 153, 153);">73</li><li style="color: rgb(153, 153, 153);">74</li><li style="color: rgb(153, 153, 153);">75</li><li style="color: rgb(153, 153, 153);">76</li><li style="color: rgb(153, 153, 153);">77</li><li style="color: rgb(153, 153, 153);">78</li><li style="color: rgb(153, 153, 153);">79</li><li style="color: rgb(153, 153, 153);">80</li><li style="color: rgb(153, 153, 153);">81</li><li style="color: rgb(153, 153, 153);">82</li><li style="color: rgb(153, 153, 153);">83</li><li style="color: rgb(153, 153, 153);">84</li><li style="color: rgb(153, 153, 153);">85</li><li style="color: rgb(153, 153, 153);">86</li><li style="color: rgb(153, 153, 153);">87</li><li style="color: rgb(153, 153, 153);">88</li><li style="color: rgb(153, 153, 153);">89</li><li style="color: rgb(153, 153, 153);">90</li><li style="color: rgb(153, 153, 153);">91</li><li style="color: rgb(153, 153, 153);">92</li><li style="color: rgb(153, 153, 153);">93</li><li style="color: rgb(153, 153, 153);">94</li><li style="color: rgb(153, 153, 153);">95</li><li style="color: rgb(153, 153, 153);">96</li><li style="color: rgb(153, 153, 153);">97</li><li style="color: rgb(153, 153, 153);">98</li><li style="color: rgb(153, 153, 153);">99</li><li style="color: rgb(153, 153, 153);">100</li><li style="color: rgb(153, 153, 153);">101</li><li style="color: rgb(153, 153, 153);">102</li><li style="color: rgb(153, 153, 153);">103</li><li style="color: rgb(153, 153, 153);">104</li><li style="color: rgb(153, 153, 153);">105</li><li style="color: rgb(153, 153, 153);">106</li><li style="color: rgb(153, 153, 153);">107</li><li style="color: rgb(153, 153, 153);">108</li><li style="color: rgb(153, 153, 153);">109</li></ul></pre>


<ul>
<li>总结 <br>
<code>Handler</code>发送消息的本质 = 为该消息定义<code>target</code>属性(即本身实例对象) &amp; 将消息入队到绑定线程的消息队列中。具体如下:</li>
</ul>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-338542d6a7ced4a8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<p>至此,关于使用 <code>Handler.sendMessage()</code>的源码解析完毕</p>






<h3 id="总结"><a name="t18"></a>总结</h3>


<ul>
<li>根据操作步骤的源码分析总结</li>
</ul>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-6cf14c6dc05cbf66.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<ul>
<li>工作流程总结</li>
</ul>






<h1 id="下面将顺着文章工作流程再理一次"><a name="t19"></a>下面,将顺着文章:工作流程再理一次</h1>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-b649e05ecbf437c8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-0d7d6f8294f4f4d4.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<hr>






<h3 id="方式2使用-handlerpost"><a name="t20"></a>方式2:使用 Handler.post()</h3>


<ul>
<li>使用步骤</li>
</ul>






<pre class="prettyprint" name="code"><code class="hljs java has-numbering"><span class="hljs-comment">// 步骤1:在主线程中创建Handler实例</span>
    <span class="hljs-keyword">private</span> Handler mhandler = <span class="hljs-keyword">new</span> mHandler();


<span class="hljs-comment">// 步骤2:在工作线程中 发送消息到消息队列中 &amp; 指定操作UI内容</span>
<span class="hljs-comment">// 需传入1个Runnable对象</span>
    mHandler.post(<span class="hljs-keyword">new</span> Runnable() {
            <span class="hljs-annotation">@Override</span>
            <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span>() {
                ... <span class="hljs-comment">// 需执行的UI操作 </span>
            }


    });


<span class="hljs-comment">// 步骤3:开启工作线程(同时启动了Handler)</span>
<span class="hljs-comment">// 多线程可采用AsyncTask、继承Thread类、实现Runnable</span></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li></ul></pre>


<ul>
<li>源码分析 <br>
下面,我将根据上述每个步骤进行源码分析 <br>




<blockquote>
  实际上,该方式与方式1中的<code>Handler.sendMessage()</code>工作原理相同、源码分析类似,下面将主要讲解不同之处</blockquote></li>
  </ul>
  




<h3 id="步骤1在主线程中创建handler实例"><a name="t21"></a>步骤1:在主线程中创建Handler实例</h3>












<pre class="prettyprint" name="code"><code class="hljs java has-numbering"><span class="hljs-javadoc">/** 
  * 具体使用
  */</span>
    <span class="hljs-keyword">private</span> Handler mhandler = <span class="hljs-keyword">new</span>  Handler();
    <span class="hljs-comment">// 与方式1的使用不同:此处无复写Handler.handleMessage()</span>


<span class="hljs-javadoc">/** 
  * 源码分析:Handler的构造方法
  * 作用:
  *     a. 在此之前,主线程创建时隐式创建Looper对象、MessageQueue对象
  *     b. 初始化Handler对象、绑定线程 &amp; 进入消息循环
  * 此处的源码分析类似方式1,此处不作过多描述
  */</span></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li></ul></pre>


























<h3 id="步骤2在工作线程中-发送消息到消息队列中"><a name="t22"></a>步骤2:在工作线程中 发送消息到消息队列中</h3>






<pre class="prettyprint" name="code"><code class="hljs java has-numbering"><span class="hljs-javadoc">/** 
  * 具体使用
  * 需传入1个Runnable对象、复写run()从而指定UI操作
  */</span>
    mHandler.post(<span class="hljs-keyword">new</span> Runnable() {
            <span class="hljs-annotation">@Override</span>
            <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span>() {
                ... <span class="hljs-comment">// 需执行的UI操作 </span>
            }


    });


<span class="hljs-javadoc">/** 
  * 源码分析:Handler.post(Runnable r)
  * 定义:属于处理者类(Handler)中的方法
  * 作用:定义UI操作、将Runnable对象封装成消息对象 &amp; 发送 到消息队列中(Message -&gt;&gt; MessageQueue)
  * 注:
  *    a. 相比sendMessage(),post()最大的不同在于,更新的UI操作可直接在重写的run()中定义
  *    b. 实际上,Runnable并无创建新线程,而是发送 消息 到消息队列中
  */</span>
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">post</span>(Runnable r)
        {
           <span class="hljs-keyword">return</span>  sendMessageDelayed(getPostMessage(r), <span class="hljs-number">0</span>);
           <span class="hljs-comment">// getPostMessage(r) 的源码分析-&gt;&gt;分析1</span>
           <span class="hljs-comment">// sendMessageDelayed()的源码分析 -&gt;&gt;分析2</span>


        }
              <span class="hljs-javadoc">/** 
               * 分析1:getPostMessage(r)
               * 作用:将传入的Runable对象封装成1个消息对象
               **/</span>
              <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> Message <span class="hljs-title">getPostMessage</span>(Runnable r) {
                        <span class="hljs-comment">// 1. 创建1个消息对象(Message)</span>
                        Message m = Message.obtain();
                            <span class="hljs-comment">// 注:创建Message对象可用关键字new 或 Message.obtain()</span>
                            <span class="hljs-comment">// 建议:使用Message.obtain()创建,</span>
                            <span class="hljs-comment">// 原因:因为Message内部维护了1个Message池,用于Message的复用,使用obtain()直接从池内获取,从而避免使用new重新分配内存</span>


                        <span class="hljs-comment">// 2. 将 Runable对象 赋值给消息对象(message)的callback属性</span>
                        m.callback = r;


                        <span class="hljs-comment">// 3. 返回该消息对象</span>
                        <span class="hljs-keyword">return</span> m;
                    } <span class="hljs-comment">// 回到调用原处</span>


             <span class="hljs-javadoc">/** 
               * 分析2:sendMessageDelayed(msg, 0)
               * 作用:实际上,从此处开始,则类似方式1 = 将消息入队到消息队列,
               * 即 最终是调用MessageQueue.enqueueMessage()
               **/</span>
               <span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">sendMessageDelayed</span>(Message msg, <span class="hljs-keyword">long</span> delayMillis)
                {
                    <span class="hljs-keyword">if</span> (delayMillis &lt; <span class="hljs-number">0</span>) {
                        delayMillis = <span class="hljs-number">0</span>;
                    }


                    <span class="hljs-keyword">return</span> sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
                    <span class="hljs-comment">// 请看分析3</span>
                }


             <span class="hljs-javadoc">/** 
               * 分析3:sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis)
               **/</span>
               <span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">sendMessageAtTime</span>(Message msg, <span class="hljs-keyword">long</span> uptimeMillis) {
                        <span class="hljs-comment">// 1. 获取对应的消息队列对象(MessageQueue)</span>
                        MessageQueue queue = mQueue;


                        <span class="hljs-comment">// 2. 调用了enqueueMessage方法 -&gt;&gt;分析3</span>
                        <span class="hljs-keyword">return</span> enqueueMessage(queue, msg, uptimeMillis);
                    }


             <span class="hljs-javadoc">/** 
               * 分析4:enqueueMessage(queue, msg, uptimeMillis)
               **/</span>
                <span class="hljs-keyword">private</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">enqueueMessage</span>(MessageQueue queue, Message msg, <span class="hljs-keyword">long</span> uptimeMillis) {
                     <span class="hljs-comment">// 1. 将msg.target赋值为this</span>
                     <span class="hljs-comment">// 即 :把 当前的Handler实例对象作为msg的target属性</span>
                     msg.target = <span class="hljs-keyword">this</span>;
                     <span class="hljs-comment">// 请回忆起上面说的Looper的loop()中消息循环时,会从消息队列中取出每个消息msg,然后执行msg.target.dispatchMessage(msg)去处理消息</span>
                     <span class="hljs-comment">// 实际上则是将该消息派发给对应的Handler实例        </span>


                    <span class="hljs-comment">// 2. 调用消息队列的enqueueMessage()</span>
                    <span class="hljs-comment">// 即:Handler发送的消息,最终是保存到消息队列</span>
                    <span class="hljs-keyword">return</span> queue.enqueueMessage(msg, uptimeMillis);
            }


            <span class="hljs-comment">// 注:实际上从分析2开始,源码 与 sendMessage(Message msg)发送方式相同</span>
</code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li><li style="color: rgb(153, 153, 153);">17</li><li style="color: rgb(153, 153, 153);">18</li><li style="color: rgb(153, 153, 153);">19</li><li style="color: rgb(153, 153, 153);">20</li><li style="color: rgb(153, 153, 153);">21</li><li style="color: rgb(153, 153, 153);">22</li><li style="color: rgb(153, 153, 153);">23</li><li style="color: rgb(153, 153, 153);">24</li><li style="color: rgb(153, 153, 153);">25</li><li style="color: rgb(153, 153, 153);">26</li><li style="color: rgb(153, 153, 153);">27</li><li style="color: rgb(153, 153, 153);">28</li><li style="color: rgb(153, 153, 153);">29</li><li style="color: rgb(153, 153, 153);">30</li><li style="color: rgb(153, 153, 153);">31</li><li style="color: rgb(153, 153, 153);">32</li><li style="color: rgb(153, 153, 153);">33</li><li style="color: rgb(153, 153, 153);">34</li><li style="color: rgb(153, 153, 153);">35</li><li style="color: rgb(153, 153, 153);">36</li><li style="color: rgb(153, 153, 153);">37</li><li style="color: rgb(153, 153, 153);">38</li><li style="color: rgb(153, 153, 153);">39</li><li style="color: rgb(153, 153, 153);">40</li><li style="color: rgb(153, 153, 153);">41</li><li style="color: rgb(153, 153, 153);">42</li><li style="color: rgb(153, 153, 153);">43</li><li style="color: rgb(153, 153, 153);">44</li><li style="color: rgb(153, 153, 153);">45</li><li style="color: rgb(153, 153, 153);">46</li><li style="color: rgb(153, 153, 153);">47</li><li style="color: rgb(153, 153, 153);">48</li><li style="color: rgb(153, 153, 153);">49</li><li style="color: rgb(153, 153, 153);">50</li><li style="color: rgb(153, 153, 153);">51</li><li style="color: rgb(153, 153, 153);">52</li><li style="color: rgb(153, 153, 153);">53</li><li style="color: rgb(153, 153, 153);">54</li><li style="color: rgb(153, 153, 153);">55</li><li style="color: rgb(153, 153, 153);">56</li><li style="color: rgb(153, 153, 153);">57</li><li style="color: rgb(153, 153, 153);">58</li><li style="color: rgb(153, 153, 153);">59</li><li style="color: rgb(153, 153, 153);">60</li><li style="color: rgb(153, 153, 153);">61</li><li style="color: rgb(153, 153, 153);">62</li><li style="color: rgb(153, 153, 153);">63</li><li style="color: rgb(153, 153, 153);">64</li><li style="color: rgb(153, 153, 153);">65</li><li style="color: rgb(153, 153, 153);">66</li><li style="color: rgb(153, 153, 153);">67</li><li style="color: rgb(153, 153, 153);">68</li><li style="color: rgb(153, 153, 153);">69</li><li style="color: rgb(153, 153, 153);">70</li><li style="color: rgb(153, 153, 153);">71</li><li style="color: rgb(153, 153, 153);">72</li><li style="color: rgb(153, 153, 153);">73</li><li style="color: rgb(153, 153, 153);">74</li><li style="color: rgb(153, 153, 153);">75</li><li style="color: rgb(153, 153, 153);">76</li><li style="color: rgb(153, 153, 153);">77</li><li style="color: rgb(153, 153, 153);">78</li><li style="color: rgb(153, 153, 153);">79</li><li style="color: rgb(153, 153, 153);">80</li><li style="color: rgb(153, 153, 153);">81</li><li style="color: rgb(153, 153, 153);">82</li><li style="color: rgb(153, 153, 153);">83</li><li style="color: rgb(153, 153, 153);">84</li><li style="color: rgb(153, 153, 153);">85</li><li style="color: rgb(153, 153, 153);">86</li><li style="color: rgb(153, 153, 153);">87</li><li style="color: rgb(153, 153, 153);">88</li></ul></pre>


<p>从上面的分析可看出:</p>


<ol>
<li>消息对象的创建 = 内部 根据<code>Runnable</code>对象而封装</li>
<li>发送到消息队列的逻辑 = 方式1中<code>sendMessage(Message msg)</code></li>
</ol>


<p>下面,我们重新回到步骤1前的隐式操作2:消息循环,即<code>Looper</code>类中的<code>loop()</code>方法</p>


<pre class="prettyprint" name="code"><code class="hljs java has-numbering"><span class="hljs-javadoc">/** 
  * 源码分析: Looper.loop()
  * 作用:消息循环,即从消息队列中获取消息、分发消息到Handler
  * 特别注意:
  *       a. 主线程的消息循环不允许退出,即无限循环
  *       b. 子线程的消息循环允许退出:调用消息队列MessageQueue的quit()
  */</span>
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">loop</span>() {


        ...<span class="hljs-comment">// 仅贴出关键代码</span>


        <span class="hljs-comment">// 1. 获取当前Looper的消息队列</span>
            <span class="hljs-keyword">final</span> Looper me = myLooper();
            <span class="hljs-keyword">if</span> (me == <span class="hljs-keyword">null</span>) {
                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(<span class="hljs-string">"No Looper; Looper.prepare() wasn't called on this thread."</span>);
            }
            <span class="hljs-comment">// myLooper()作用:返回sThreadLocal存储的Looper实例;若me为null 则抛出异常</span>
            <span class="hljs-comment">// 即loop()执行前必须执行prepare(),从而创建1个Looper实例</span>


            <span class="hljs-keyword">final</span> MessageQueue queue = me.mQueue;
            <span class="hljs-comment">// 获取Looper实例中的消息队列对象(MessageQueue)</span>


        <span class="hljs-comment">// 2. 消息循环(通过for循环)</span>
            <span class="hljs-keyword">for</span> (;;) {


            <span class="hljs-comment">// 2.1 从消息队列中取出消息</span>
            Message msg = queue.next(); 
            <span class="hljs-keyword">if</span> (msg == <span class="hljs-keyword">null</span>) {
                <span class="hljs-keyword">return</span>;
            }
            <span class="hljs-comment">// next():取出消息队列里的消息</span>
            <span class="hljs-comment">// 若取出的消息为空,则线程阻塞</span>


            <span class="hljs-comment">// 2.2 派发消息到对应的Handler</span>
            msg.target.dispatchMessage(msg);
            <span class="hljs-comment">// 把消息Message派发给消息对象msg的target属性</span>
            <span class="hljs-comment">// target属性实际是1个handler对象</span>
            <span class="hljs-comment">// -&gt;&gt;分析1</span>


        <span class="hljs-comment">// 3. 释放消息占据的资源</span>
        msg.recycle();
        }
}


<span class="hljs-javadoc">/** 
  * 分析1:dispatchMessage(msg)
  * 定义:属于处理者类(Handler)中的方法
  * 作用:派发消息到对应的Handler实例 &amp; 根据传入的msg作出对应的操作
  */</span>
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">dispatchMessage</span>(Message msg) {


    <span class="hljs-comment">// 1. 若msg.callback属性不为空,则代表使用了post(Runnable r)发送消息(即此处需讨论的)</span>
    <span class="hljs-comment">// 则执行handleCallback(msg),即回调Runnable对象里复写的run()-&gt;&gt; 分析2</span>
        <span class="hljs-keyword">if</span> (msg.callback != <span class="hljs-keyword">null</span>) {
            handleCallback(msg);
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-keyword">if</span> (mCallback != <span class="hljs-keyword">null</span>) {
                <span class="hljs-keyword">if</span> (mCallback.handleMessage(msg)) {
                    <span class="hljs-keyword">return</span>;
                }
            }


            <span class="hljs-comment">// 2. 若msg.callback属性为空,则代表使用了sendMessage(Message msg)发送消息(即此处需讨论的)</span>
            <span class="hljs-comment">// 则执行handleMessage(msg),即回调复写的handleMessage(msg) </span>
            handleMessage(msg);


        }
    }


  <span class="hljs-javadoc">/** 
    * 分析2:handleCallback(msg)
    **/</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">handleCallback</span>(Message message) {
        message.callback.run();
        <span class="hljs-comment">//  Message对象的callback属性 = 传入的Runnable对象</span>
        <span class="hljs-comment">// 即回调Runnable对象里复写的run()</span>
    }</code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li><li style="color: rgb(153, 153, 153);">17</li><li style="color: rgb(153, 153, 153);">18</li><li style="color: rgb(153, 153, 153);">19</li><li style="color: rgb(153, 153, 153);">20</li><li style="color: rgb(153, 153, 153);">21</li><li style="color: rgb(153, 153, 153);">22</li><li style="color: rgb(153, 153, 153);">23</li><li style="color: rgb(153, 153, 153);">24</li><li style="color: rgb(153, 153, 153);">25</li><li style="color: rgb(153, 153, 153);">26</li><li style="color: rgb(153, 153, 153);">27</li><li style="color: rgb(153, 153, 153);">28</li><li style="color: rgb(153, 153, 153);">29</li><li style="color: rgb(153, 153, 153);">30</li><li style="color: rgb(153, 153, 153);">31</li><li style="color: rgb(153, 153, 153);">32</li><li style="color: rgb(153, 153, 153);">33</li><li style="color: rgb(153, 153, 153);">34</li><li style="color: rgb(153, 153, 153);">35</li><li style="color: rgb(153, 153, 153);">36</li><li style="color: rgb(153, 153, 153);">37</li><li style="color: rgb(153, 153, 153);">38</li><li style="color: rgb(153, 153, 153);">39</li><li style="color: rgb(153, 153, 153);">40</li><li style="color: rgb(153, 153, 153);">41</li><li style="color: rgb(153, 153, 153);">42</li><li style="color: rgb(153, 153, 153);">43</li><li style="color: rgb(153, 153, 153);">44</li><li style="color: rgb(153, 153, 153);">45</li><li style="color: rgb(153, 153, 153);">46</li><li style="color: rgb(153, 153, 153);">47</li><li style="color: rgb(153, 153, 153);">48</li><li style="color: rgb(153, 153, 153);">49</li><li style="color: rgb(153, 153, 153);">50</li><li style="color: rgb(153, 153, 153);">51</li><li style="color: rgb(153, 153, 153);">52</li><li style="color: rgb(153, 153, 153);">53</li><li style="color: rgb(153, 153, 153);">54</li><li style="color: rgb(153, 153, 153);">55</li><li style="color: rgb(153, 153, 153);">56</li><li style="color: rgb(153, 153, 153);">57</li><li style="color: rgb(153, 153, 153);">58</li><li style="color: rgb(153, 153, 153);">59</li><li style="color: rgb(153, 153, 153);">60</li><li style="color: rgb(153, 153, 153);">61</li><li style="color: rgb(153, 153, 153);">62</li><li style="color: rgb(153, 153, 153);">63</li><li style="color: rgb(153, 153, 153);">64</li><li style="color: rgb(153, 153, 153);">65</li><li style="color: rgb(153, 153, 153);">66</li><li style="color: rgb(153, 153, 153);">67</li><li style="color: rgb(153, 153, 153);">68</li><li style="color: rgb(153, 153, 153);">69</li><li style="color: rgb(153, 153, 153);">70</li><li style="color: rgb(153, 153, 153);">71</li><li style="color: rgb(153, 153, 153);">72</li><li style="color: rgb(153, 153, 153);">73</li><li style="color: rgb(153, 153, 153);">74</li><li style="color: rgb(153, 153, 153);">75</li><li style="color: rgb(153, 153, 153);">76</li><li style="color: rgb(153, 153, 153);">77</li></ul></pre>


<p>至此,你应该明白使用 <code>Handler.post()</code>的工作流程:与方式1<code>(Handler.sendMessage())</code>类似,区别在于:</p>


<ol>
<li>不需外部创建消息对象,而是内部根据传入的<code>Runnable</code>对象 封装消息对象</li>
<li>回调的消息处理方法是:复写<code>Runnable</code>对象的<code>run()</code></li>
</ol>


<p>二者的具体异同如下:</p>


<p><img src="https://upload-images.jianshu.io/upload_images/944365-29fc8832f4a8b399.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<p>至此,关于使用 <code>Handler.post()</code>的源码解析完毕</p>






<h3 id="总结-1"><a name="t23"></a>总结</h3>


<ul>
<li><p>根据操作步骤的源码分析总结 <br>
<img src="http://upload-images.jianshu.io/upload_images/944365-62eb790fbcdff4cd.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p></li>
<li><p>工作流程总结</p></li>
</ul>






<h1 id="下面将顺着文章工作流程再理一次-1"><a name="t24"></a>下面,将顺着文章:工作流程再理一次</h1>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-b649e05ecbf437c8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-58a275152eb5099a.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<p><strong>至此,关于<code>Handler</code>机制的源码全部分析完毕。</strong></p>


<hr>






<h1 id="5-总结"><a name="t25"></a>5. 总结</h1>


<ul>
<li>本文详细分析了<code>Handler</code>机制的源码,文字总结 &amp; 流程图如下:</li>
</ul>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-4c1a4fb4b228c48e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-184ea94ec1b5ce05.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-494e0b26a2724087.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-ab8502405221b5c6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<ul>
<li>下面我将继续深入讲解 <code>Android</code>中的<code>Handler</code>异步通信传递机制的相关知识,如 工作机制流程、源码解析等,有兴趣可以继续关注<a href="https://blog.csdn.net/carson_ho" target="_blank">Carson_Ho的安卓开发笔记</a></li>
</ul>


<hr>


<h1 id="请帮顶-评论点赞因为你的鼓励是我写作的最大动力"><a name="t26"></a>请帮顶 / 评论点赞!因为你的鼓励是我写作的最大动力!</h1>            </div>
            <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/markdown_views-ea0013b516.css">
                </div><div id="article_content" class="article_content clearfix csdn-tracking-statistics" data-pid="blog" data-mod="popu_307" data-dsm="post">
                    <div class="markdown_views">
                <h1 id="前言"><a name="t0"></a>前言</h1>


<ul>
<li>在<code>Android</code>开发的<strong>多线程应用场景</strong>中,<code>Handler</code>机制十分常用</li>
<li>今天,我将手把手带你深入分析 <code>Handler</code>机制的源码,希望你们会喜欢</li>
</ul>


<hr>






<h1 id="目录"><a name="t1"></a>目录</h1>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-4450ea6a59b6b183.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<hr>






<h1 id="1-handler-机制简介"><a name="t2"></a>1. Handler 机制简介</h1>


<ul>
<li><p>定义 <br>
一套 <code>Android</code> 消息传递机制</p></li>
<li><p>作用</p></li>
</ul>


<p>在多线程的应用场景中,<strong>将工作线程中需更新<code>UI</code>的操作信息 传递到 <code>UI</code>主线程</strong>,从而实现 工作线程对<code>UI</code>的更新处理,最终实现异步消息的处理 <br>
<img src="http://upload-images.jianshu.io/upload_images/944365-4a64038632c4c88f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<ul>
<li>为什么要用 <code>Handler</code>消息传递机制 <br>
答:<strong>多个线程并发更新UI的同时 保证线程安全</strong>。具体描述如下</li>
</ul>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-7479b4a8b8fe48bf.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<ul>
<li>总结 <br>
使用<code>Handler</code>的原因:将工作线程需操作<code>UI</code>的消息 传递 到主线程,使得主线程可根据工作线程的需求 更新<code>UI</code>,<strong>从而避免线程操作不安全的问题</strong></li>
</ul>


<hr>






<h1 id="2-储备知识"><a name="t3"></a>2. 储备知识</h1>


<p>在阅读<code>Handler</code>机制的源码分析前,请务必了解<code>Handler</code>的一些储备知识:<strong>相关概念、使用方式 &amp; 工作原理</strong></p>






<h3 id="21-相关概念"><a name="t4"></a>2.1 相关概念</h3>


<p>关于 <code>Handler</code> 机制中的相关概念如下:</p>


<blockquote>
  <p>在下面的讲解中,我将直接使用英文名讲解,即 <code>Handler</code>、<code>Message</code>、<code>Message Queue</code>、<code>Looper</code>,希望大家先熟悉相关概念</p>
</blockquote>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-d08903087cb575d9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>






<h3 id="22-使用方式"><a name="t5"></a>2.2 使用方式</h3>


<p></p><ul> <br>
<li><code>Handler</code>使用方式 因<strong>发送消息到消息队列的方式不同而不同</strong>,共分为2种:使用<code>Handler.sendMessage()</code>、使用<code>Handler.post()</code></li>
<li>下面的源码分析将依据使用步骤讲解 <br></li></ul><p></p>


<blockquote>
  <p>若还不了解,请务必阅读文章:<a href="https://blog.csdn.net/carson_ho/article/details/80305411" target="_blank">Android:这是一份Handler消息传递机制 的使用教程</a>
  </p>
</blockquote>


<h3 id="23-工作原理"><a name="t6"></a>2.3 工作原理</h3>


<ul>
<li>理解<code>Handler</code>机制的工作原理,能很大程序帮助理解其源码</li>
<li>具体请看文章:<a href="https://blog.csdn.net/carson_ho/article/details/80175876" target="_blank">Android Handler:图文解析 Handler通信机制 的工作原理</a></li>
</ul>


<hr>


<h1 id="3-handler机制的核心类"><a name="t7"></a>3. Handler机制的核心类</h1>


<p>在源码分析前,先来了解<code>Handler</code>机制中的核心类</p>






<h3 id="31-类说明"><a name="t8"></a>3.1 类说明</h3>


<p><code>Handler</code>机制 中有3个重要的类:</p>


<ul>
<li>处理器 类<code>(Handler)</code></li>
<li>消息队列 类<code>(MessageQueue)</code></li>
<li>循环器 类<code>(Looper)</code></li>
</ul>


<h3 id="32-类图"><a name="t9"></a>3.2 类图</h3>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-868877030acf2e45.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>






<h3 id="33-具体介绍"><a name="t10"></a>3.3 具体介绍</h3>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-a6a41fa7961184e2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<hr>






<h1 id="4-源码分析"><a name="t11"></a>4. 源码分析</h1>


<p></p><ul> <br>
<li>下面的源码分析将根据 <code>Handler</code>的使用步骤进行</li>
<li><code>Handler</code>使用方式 因<strong>发送消息到消息队列的方式不同而不同</strong>,共分为2种:使用<code>Handler.sendMessage()</code>、使用<code>Handler.post()</code> <br></li></ul><p></p>


<blockquote>
  <p>若还不了解,请务必阅读文章:<a href="https://blog.csdn.net/carson_ho/article/details/80305411" target="_blank">Android:这是一份Handler消息传递机制 的使用教程</a>
  </p><li>下面的源码分析将依据上述2种使用方式进行</li>
  <p></p>
</blockquote>




<h3 id="方式1使用-handlersendmessage"><a name="t12"></a>方式1:使用 Handler.sendMessage()</h3>


<ul>
<li>使用步骤</li>
</ul>






<pre class="prettyprint" name="code"><code class="hljs java has-numbering"><span class="hljs-javadoc">/** 
  * 此处以 匿名内部类 的使用方式为例
  */</span>
  <span class="hljs-comment">// 步骤1:在主线程中 通过匿名内部类 创建Handler类对象</span>
            <span class="hljs-keyword">private</span> Handler mhandler = <span class="hljs-keyword">new</span>  Handler(){
                <span class="hljs-comment">// 通过复写handlerMessage()从而确定更新UI的操作</span>
                <span class="hljs-annotation">@Override</span>
                <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">handleMessage</span>(Message msg) {
                        ...<span class="hljs-comment">// 需执行的UI操作</span>
                    }
            };


  <span class="hljs-comment">// 步骤2:创建消息对象</span>
    Message msg = Message.obtain(); <span class="hljs-comment">// 实例化消息对象</span>
    msg.what = <span class="hljs-number">1</span>; <span class="hljs-comment">// 消息标识</span>
    msg.obj = <span class="hljs-string">"AA"</span>; <span class="hljs-comment">// 消息内容存放</span>


  <span class="hljs-comment">// 步骤3:在工作线程中 通过Handler发送消息到消息队列中</span>
  <span class="hljs-comment">// 多线程可采用AsyncTask、继承Thread类、实现Runnable</span>
   mHandler.sendMessage(msg);


  <span class="hljs-comment">// 步骤4:开启工作线程(同时启动了Handler)</span>
  <span class="hljs-comment">// 多线程可采用AsyncTask、继承Thread类、实现Runnable</span></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li><li style="color: rgb(153, 153, 153);">17</li><li style="color: rgb(153, 153, 153);">18</li><li style="color: rgb(153, 153, 153);">19</li><li style="color: rgb(153, 153, 153);">20</li><li style="color: rgb(153, 153, 153);">21</li><li style="color: rgb(153, 153, 153);">22</li><li style="color: rgb(153, 153, 153);">23</li></ul></pre>


<ul>
<li>源码分析 <br>
下面,我将根据上述每个步骤进行源码分析</li>
</ul>






<h3 id="步骤1在主线程中-通过匿名内部类-创建handler类对象"><a name="t13"></a>步骤1:在主线程中 通过匿名内部类 创建Handler类对象</h3>






<pre class="prettyprint" name="code"><code class="hljs java has-numbering"><span class="hljs-javadoc">/** 
  * 具体使用
  */</span>
    <span class="hljs-keyword">private</span> Handler mhandler = <span class="hljs-keyword">new</span>  Handler(){
        <span class="hljs-comment">// 通过复写handlerMessage()从而确定更新UI的操作</span>
        <span class="hljs-annotation">@Override</span>
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">handleMessage</span>(Message msg) {
                ...<span class="hljs-comment">// 需执行的UI操作</span>
            }
    };


<span class="hljs-javadoc">/** 
  * 源码分析:Handler的构造方法
  * 作用:初始化Handler对象 &amp; 绑定线程
  * 注:
  *   a. Handler需绑定 线程才能使用;绑定后,Handler的消息处理会在绑定的线程中执行
  *   b. 绑定方式 = 先指定Looper对象,从而绑定了 Looper对象所绑定的线程(因为Looper对象本已绑定了对应线程)
  *   c. 即:指定了Handler对象的 Looper对象 = 绑定到了Looper对象所在的线程
  */</span>
  <span class="hljs-keyword">public</span> <span class="hljs-title">Handler</span>() {


            <span class="hljs-keyword">this</span>(<span class="hljs-keyword">null</span>, <span class="hljs-keyword">false</span>);
            <span class="hljs-comment">// -&gt;&gt;分析1</span>


    }
<span class="hljs-javadoc">/** 
  * 分析1:this(null, false) = Handler(null,false)
  */</span>
  <span class="hljs-keyword">public</span> <span class="hljs-title">Handler</span>(Callback callback, <span class="hljs-keyword">boolean</span> async) {


            ...<span class="hljs-comment">// 仅贴出关键代码</span>


            <span class="hljs-comment">// 1. 指定Looper对象</span>
                mLooper = Looper.myLooper();
                <span class="hljs-keyword">if</span> (mLooper == <span class="hljs-keyword">null</span>) {
                    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(
                        <span class="hljs-string">"Can't create handler inside thread that has not called Looper.prepare()"</span>);
                }
                <span class="hljs-comment">// Looper.myLooper()作用:获取当前线程的Looper对象;若线程无Looper对象则抛出异常</span>
                <span class="hljs-comment">// 即 :若线程中无创建Looper对象,则也无法创建Handler对象</span>
                <span class="hljs-comment">// 故 若需在子线程中创建Handler对象,则需先创建Looper对象</span>
                <span class="hljs-comment">// 注:可通过Loop.getMainLooper()可以获得当前进程的主线程的Looper对象</span>


            <span class="hljs-comment">// 2. 绑定消息队列对象(MessageQueue)</span>
                mQueue = mLooper.mQueue;
                <span class="hljs-comment">// 获取该Looper对象中保存的消息队列对象(MessageQueue)</span>
                <span class="hljs-comment">// 至此,保证了handler对象 关联上 Looper对象中MessageQueue</span>
    }</code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li><li style="color: rgb(153, 153, 153);">17</li><li style="color: rgb(153, 153, 153);">18</li><li style="color: rgb(153, 153, 153);">19</li><li style="color: rgb(153, 153, 153);">20</li><li style="color: rgb(153, 153, 153);">21</li><li style="color: rgb(153, 153, 153);">22</li><li style="color: rgb(153, 153, 153);">23</li><li style="color: rgb(153, 153, 153);">24</li><li style="color: rgb(153, 153, 153);">25</li><li style="color: rgb(153, 153, 153);">26</li><li style="color: rgb(153, 153, 153);">27</li><li style="color: rgb(153, 153, 153);">28</li><li style="color: rgb(153, 153, 153);">29</li><li style="color: rgb(153, 153, 153);">30</li><li style="color: rgb(153, 153, 153);">31</li><li style="color: rgb(153, 153, 153);">32</li><li style="color: rgb(153, 153, 153);">33</li><li style="color: rgb(153, 153, 153);">34</li><li style="color: rgb(153, 153, 153);">35</li><li style="color: rgb(153, 153, 153);">36</li><li style="color: rgb(153, 153, 153);">37</li><li style="color: rgb(153, 153, 153);">38</li><li style="color: rgb(153, 153, 153);">39</li><li style="color: rgb(153, 153, 153);">40</li><li style="color: rgb(153, 153, 153);">41</li><li style="color: rgb(153, 153, 153);">42</li><li style="color: rgb(153, 153, 153);">43</li><li style="color: rgb(153, 153, 153);">44</li><li style="color: rgb(153, 153, 153);">45</li><li style="color: rgb(153, 153, 153);">46</li><li style="color: rgb(153, 153, 153);">47</li><li style="color: rgb(153, 153, 153);">48</li></ul></pre>


<ul>
<li><p>从上面可看出: <br>
当创建<code>Handler</code>对象时,则通过 构造方法 自动关联当前线程的<code>Looper</code>对象 &amp; 对应的消息队列对象<code>(MessageQueue)</code>,从而 自动绑定了 实现创建<code>Handler</code>对象操作的线程</p></li>
<li><p>那么,当前线程的<code>Looper</code>对象 &amp; 对应的消息队列对象<code>(MessageQueue)</code> 是什么时候创建的呢?</p>


<blockquote>
  <p>在上述使用步骤中,并无 创建<code>Looper</code>对象 &amp; 对应的消息队列对象<code>(MessageQueue)</code>这1步</p>
</blockquote></li>
</ul>






<h3 id="步骤1前的隐式操作1创建循环器对象looper-消息队列对象messagequeue"><a name="t14"></a>步骤1前的隐式操作1:创建循环器对象(Looper) &amp; 消息队列对象(MessageQueue)</h3>


<ul>
<li>步骤介绍</li>
</ul>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-d261c6a482b61e02.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<ul>
<li>源码分析</li>
</ul>






<pre class="prettyprint" name="code"><code class="hljs java has-numbering"><span class="hljs-javadoc">/** 
  * 源码分析1:Looper.prepare()
  * 作用:为当前线程(子线程) 创建1个循环器对象(Looper),同时也生成了1个消息队列对象(MessageQueue)
  * 注:需在子线程中手动调用该方法
  */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">void</span> <span class="hljs-title">prepare</span>() {


        <span class="hljs-keyword">if</span> (sThreadLocal.get() != <span class="hljs-keyword">null</span>) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(<span class="hljs-string">"Only one Looper may be created per thread"</span>);
        }
        <span class="hljs-comment">// 1. 判断sThreadLocal是否为null,否则抛出异常</span>
        <span class="hljs-comment">//即 Looper.prepare()方法不能被调用两次 = 1个线程中只能对应1个Looper实例</span>
        <span class="hljs-comment">// 注:sThreadLocal = 1个ThreadLocal对象,用于存储线程的变量</span>


        sThreadLocal.set(<span class="hljs-keyword">new</span> Looper(<span class="hljs-keyword">true</span>));
        <span class="hljs-comment">// 2. 若为初次Looper.prepare(),则创建Looper对象 &amp; 存放在ThreadLocal变量中</span>
        <span class="hljs-comment">// 注:Looper对象是存放在Thread线程里的</span>
        <span class="hljs-comment">// 源码分析Looper的构造方法-&gt;&gt;分析a</span>
    }


  <span class="hljs-javadoc">/** 
    * 分析a:Looper的构造方法
    **/</span>


        <span class="hljs-keyword">private</span> <span class="hljs-title">Looper</span>(<span class="hljs-keyword">boolean</span> quitAllowed) {


            mQueue = <span class="hljs-keyword">new</span> MessageQueue(quitAllowed);
            <span class="hljs-comment">// 1. 创建1个消息队列对象(MessageQueue)</span>
            <span class="hljs-comment">// 即 当创建1个Looper实例时,会自动创建一个与之配对的消息队列对象(MessageQueue)</span>


            mRun = <span class="hljs-keyword">true</span>;
            mThread = Thread.currentThread();
        }


<span class="hljs-javadoc">/** 
  * 源码分析2:Looper.prepareMainLooper()
  * 作用:为 主线程(UI线程) 创建1个循环器对象(Looper),同时也生成了1个消息队列对象(MessageQueue)
  * 注:该方法在主线程(UI线程)创建时自动调用,即 主线程的Looper对象自动生成,不需手动生成
  */</span>
    <span class="hljs-comment">// 在Android应用进程启动时,会默认创建1个主线程(ActivityThread,也叫UI线程)</span>
    <span class="hljs-comment">// 创建时,会自动调用ActivityThread的1个静态的main()方法 = 应用程序的入口</span>
    <span class="hljs-comment">// main()内则会调用Looper.prepareMainLooper()为主线程生成1个Looper对象</span>


      <span class="hljs-javadoc">/** 
        * 源码分析:main()
        **/</span>
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span>(String[] args) {
            ... <span class="hljs-comment">// 仅贴出关键代码</span>


            Looper.prepareMainLooper(); 
            <span class="hljs-comment">// 1. 为主线程创建1个Looper对象,同时生成1个消息队列对象(MessageQueue)</span>
            <span class="hljs-comment">// 方法逻辑类似Looper.prepare()</span>
            <span class="hljs-comment">// 注:prepare():为子线程中创建1个Looper对象</span>




            ActivityThread thread = <span class="hljs-keyword">new</span> ActivityThread(); 
            <span class="hljs-comment">// 2. 创建主线程</span>


            Looper.loop(); 
            <span class="hljs-comment">// 3. 自动开启 消息循环 -&gt;&gt;下面将详细分析</span>


        }</code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li><li style="color: rgb(153, 153, 153);">17</li><li style="color: rgb(153, 153, 153);">18</li><li style="color: rgb(153, 153, 153);">19</li><li style="color: rgb(153, 153, 153);">20</li><li style="color: rgb(153, 153, 153);">21</li><li style="color: rgb(153, 153, 153);">22</li><li style="color: rgb(153, 153, 153);">23</li><li style="color: rgb(153, 153, 153);">24</li><li style="color: rgb(153, 153, 153);">25</li><li style="color: rgb(153, 153, 153);">26</li><li style="color: rgb(153, 153, 153);">27</li><li style="color: rgb(153, 153, 153);">28</li><li style="color: rgb(153, 153, 153);">29</li><li style="color: rgb(153, 153, 153);">30</li><li style="color: rgb(153, 153, 153);">31</li><li style="color: rgb(153, 153, 153);">32</li><li style="color: rgb(153, 153, 153);">33</li><li style="color: rgb(153, 153, 153);">34</li><li style="color: rgb(153, 153, 153);">35</li><li style="color: rgb(153, 153, 153);">36</li><li style="color: rgb(153, 153, 153);">37</li><li style="color: rgb(153, 153, 153);">38</li><li style="color: rgb(153, 153, 153);">39</li><li style="color: rgb(153, 153, 153);">40</li><li style="color: rgb(153, 153, 153);">41</li><li style="color: rgb(153, 153, 153);">42</li><li style="color: rgb(153, 153, 153);">43</li><li style="color: rgb(153, 153, 153);">44</li><li style="color: rgb(153, 153, 153);">45</li><li style="color: rgb(153, 153, 153);">46</li><li style="color: rgb(153, 153, 153);">47</li><li style="color: rgb(153, 153, 153);">48</li><li style="color: rgb(153, 153, 153);">49</li><li style="color: rgb(153, 153, 153);">50</li><li style="color: rgb(153, 153, 153);">51</li><li style="color: rgb(153, 153, 153);">52</li><li style="color: rgb(153, 153, 153);">53</li><li style="color: rgb(153, 153, 153);">54</li><li style="color: rgb(153, 153, 153);">55</li><li style="color: rgb(153, 153, 153);">56</li><li style="color: rgb(153, 153, 153);">57</li><li style="color: rgb(153, 153, 153);">58</li><li style="color: rgb(153, 153, 153);">59</li><li style="color: rgb(153, 153, 153);">60</li><li style="color: rgb(153, 153, 153);">61</li><li style="color: rgb(153, 153, 153);">62</li></ul></pre>


<p>总结:</p>


<p></p><ul> <br>
<li>创建主线程时,会自动调用<code>ActivityThread</code>的1个静态的<code>main()</code>;而<code>main()</code>内则会调用<code>Looper.prepareMainLooper()</code>为主线程生成1个<code>Looper</code>对象,同时也会生成其对应的<code>MessageQueue</code>对象 <br></li></ul><p></p>


<blockquote>
  <ol>
  <li>即 主线程的<code>Looper</code>对象自动生成,不需手动生成;而子线程的<code>Looper</code>对象则需手动通过<code>Looper.prepare()</code>创建 <br></li>
  <li>在子线程若不手动创建<code>Looper</code>对象 则无法生成<code>Handler</code>对象</li>
  <li><p>根据<code>Handler</code>的作用(在主线程更新<code>UI</code>),<strong>故<code>Handler</code>实例的创建场景 主要在主线程</strong></p></li>
  <li><p>生成<code>Looper</code> &amp; <code>MessageQueue</code>对象后,则会自动进入消息循环:<code>Looper.loop()</code>,即又是另外一个隐式操作。</p></li>
  
  </ol>
</blockquote>


<h3 id="步骤1前的隐式操作2消息循环"><a name="t15"></a>步骤1前的隐式操作2:消息循环</h3>


<p>此处主要分析的是<code>Looper</code>类中的<code>loop()</code>方法</p>






<pre class="prettyprint" name="code"><code class="hljs java has-numbering"><span class="hljs-javadoc">/** 
  * 源码分析: Looper.loop()
  * 作用:消息循环,即从消息队列中获取消息、分发消息到Handler
  * 特别注意:
  *       a. 主线程的消息循环不允许退出,即无限循环
  *       b. 子线程的消息循环允许退出:调用消息队列MessageQueue的quit()
  */</span>
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">loop</span>() {


        ...<span class="hljs-comment">// 仅贴出关键代码</span>


        <span class="hljs-comment">// 1. 获取当前Looper的消息队列</span>
            <span class="hljs-keyword">final</span> Looper me = myLooper();
            <span class="hljs-keyword">if</span> (me == <span class="hljs-keyword">null</span>) {
                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(<span class="hljs-string">"No Looper; Looper.prepare() wasn't called on this thread."</span>);
            }
            <span class="hljs-comment">// myLooper()作用:返回sThreadLocal存储的Looper实例;若me为null 则抛出异常</span>
            <span class="hljs-comment">// 即loop()执行前必须执行prepare(),从而创建1个Looper实例</span>


            <span class="hljs-keyword">final</span> MessageQueue queue = me.mQueue;
            <span class="hljs-comment">// 获取Looper实例中的消息队列对象(MessageQueue)</span>


        <span class="hljs-comment">// 2. 消息循环(通过for循环)</span>
            <span class="hljs-keyword">for</span> (;;) {


            <span class="hljs-comment">// 2.1 从消息队列中取出消息</span>
            Message msg = queue.next(); 
            <span class="hljs-keyword">if</span> (msg == <span class="hljs-keyword">null</span>) {
                <span class="hljs-keyword">return</span>;
            }
            <span class="hljs-comment">// next():取出消息队列里的消息</span>
            <span class="hljs-comment">// 若取出的消息为空,则线程阻塞</span>
            <span class="hljs-comment">// -&gt;&gt; 分析1 </span>


            <span class="hljs-comment">// 2.2 派发消息到对应的Handler</span>
            msg.target.dispatchMessage(msg);
            <span class="hljs-comment">// 把消息Message派发给消息对象msg的target属性</span>
            <span class="hljs-comment">// target属性实际是1个handler对象</span>
            <span class="hljs-comment">// -&gt;&gt;分析2</span>


        <span class="hljs-comment">// 3. 释放消息占据的资源</span>
        msg.recycle();
        }
}


<span class="hljs-javadoc">/** 
  * 分析1:queue.next()
  * 定义:属于消息队列类(MessageQueue)中的方法
  * 作用:出队消息,即从 消息队列中 移出该消息
  */</span>
  Message next() {


        ...<span class="hljs-comment">// 仅贴出关键代码</span>


        <span class="hljs-comment">// 该参数用于确定消息队列中是否还有消息</span>
        <span class="hljs-comment">// 从而决定消息队列应处于出队消息状态 or 等待状态</span>
        <span class="hljs-keyword">int</span> nextPollTimeoutMillis = <span class="hljs-number">0</span>;


        <span class="hljs-keyword">for</span> (;;) {
            <span class="hljs-keyword">if</span> (nextPollTimeoutMillis != <span class="hljs-number">0</span>) {
                Binder.flushPendingCommands();
            }


        <span class="hljs-comment">// nativePollOnce方法在native层,若是nextPollTimeoutMillis为-1,此时消息队列处于等待状态 </span>
        nativePollOnce(ptr, nextPollTimeoutMillis);


        <span class="hljs-keyword">synchronized</span> (<span class="hljs-keyword">this</span>) {


            <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> now = SystemClock.uptimeMillis();
            Message prevMsg = <span class="hljs-keyword">null</span>;
            Message msg = mMessages;


            <span class="hljs-comment">// 出队消息,即 从消息队列中取出消息:按创建Message对象的时间顺序</span>
            <span class="hljs-keyword">if</span> (msg != <span class="hljs-keyword">null</span>) {
                <span class="hljs-keyword">if</span> (now &lt; msg.when) {
                    nextPollTimeoutMillis = (<span class="hljs-keyword">int</span>) Math.min(msg.when - now, Integer.MAX_VALUE);
                } <span class="hljs-keyword">else</span> {
                    <span class="hljs-comment">// 取出了消息</span>
                    mBlocked = <span class="hljs-keyword">false</span>;
                    <span class="hljs-keyword">if</span> (prevMsg != <span class="hljs-keyword">null</span>) {
                        prevMsg.next = msg.next;
                    } <span class="hljs-keyword">else</span> {
                        mMessages = msg.next;
                    }
                    msg.next = <span class="hljs-keyword">null</span>;
                    <span class="hljs-keyword">if</span> (DEBUG) Log.v(TAG, <span class="hljs-string">"Returning message: "</span> + msg);
                    msg.markInUse();
                    <span class="hljs-keyword">return</span> msg;
                }
            } <span class="hljs-keyword">else</span> {


                <span class="hljs-comment">// 若 消息队列中已无消息,则将nextPollTimeoutMillis参数设为-1</span>
                <span class="hljs-comment">// 下次循环时,消息队列则处于等待状态</span>
                nextPollTimeoutMillis = -<span class="hljs-number">1</span>;
            }


            ......
        }
           .....
       }
}<span class="hljs-comment">// 回到分析原处</span>


<span class="hljs-javadoc">/** 
  * 分析2:dispatchMessage(msg)
  * 定义:属于处理者类(Handler)中的方法
  * 作用:派发消息到对应的Handler实例 &amp; 根据传入的msg作出对应的操作
  */</span>
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">dispatchMessage</span>(Message msg) {


    <span class="hljs-comment">// 1. 若msg.callback属性不为空,则代表使用了post(Runnable r)发送消息</span>
    <span class="hljs-comment">// 则执行handleCallback(msg),即回调Runnable对象里复写的run()</span>
    <span class="hljs-comment">// 上述结论会在讲解使用“post(Runnable r)”方式时讲解</span>
        <span class="hljs-keyword">if</span> (msg.callback != <span class="hljs-keyword">null</span>) {
            handleCallback(msg);
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-keyword">if</span> (mCallback != <span class="hljs-keyword">null</span>) {
                <span class="hljs-keyword">if</span> (mCallback.handleMessage(msg)) {
                    <span class="hljs-keyword">return</span>;
                }
            }


            <span class="hljs-comment">// 2. 若msg.callback属性为空,则代表使用了sendMessage(Message msg)发送消息(即此处需讨论的)</span>
            <span class="hljs-comment">// 则执行handleMessage(msg),即回调复写的handleMessage(msg) -&gt;&gt; 分析3</span>
            handleMessage(msg);


        }
    }


  <span class="hljs-javadoc">/** 
   * 分析3:handleMessage(msg)
   * 注:该方法 = 空方法,在创建Handler实例时复写 = 自定义消息处理方式
   **/</span>
   <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">handleMessage</span>(Message msg) {  
          ... <span class="hljs-comment">// 创建Handler实例时复写</span>
   } </code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li><li style="color: rgb(153, 153, 153);">17</li><li style="color: rgb(153, 153, 153);">18</li><li style="color: rgb(153, 153, 153);">19</li><li style="color: rgb(153, 153, 153);">20</li><li style="color: rgb(153, 153, 153);">21</li><li style="color: rgb(153, 153, 153);">22</li><li style="color: rgb(153, 153, 153);">23</li><li style="color: rgb(153, 153, 153);">24</li><li style="color: rgb(153, 153, 153);">25</li><li style="color: rgb(153, 153, 153);">26</li><li style="color: rgb(153, 153, 153);">27</li><li style="color: rgb(153, 153, 153);">28</li><li style="color: rgb(153, 153, 153);">29</li><li style="color: rgb(153, 153, 153);">30</li><li style="color: rgb(153, 153, 153);">31</li><li style="color: rgb(153, 153, 153);">32</li><li style="color: rgb(153, 153, 153);">33</li><li style="color: rgb(153, 153, 153);">34</li><li style="color: rgb(153, 153, 153);">35</li><li style="color: rgb(153, 153, 153);">36</li><li style="color: rgb(153, 153, 153);">37</li><li style="color: rgb(153, 153, 153);">38</li><li style="color: rgb(153, 153, 153);">39</li><li style="color: rgb(153, 153, 153);">40</li><li style="color: rgb(153, 153, 153);">41</li><li style="color: rgb(153, 153, 153);">42</li><li style="color: rgb(153, 153, 153);">43</li><li style="color: rgb(153, 153, 153);">44</li><li style="color: rgb(153, 153, 153);">45</li><li style="color: rgb(153, 153, 153);">46</li><li style="color: rgb(153, 153, 153);">47</li><li style="color: rgb(153, 153, 153);">48</li><li style="color: rgb(153, 153, 153);">49</li><li style="color: rgb(153, 153, 153);">50</li><li style="color: rgb(153, 153, 153);">51</li><li style="color: rgb(153, 153, 153);">52</li><li style="color: rgb(153, 153, 153);">53</li><li style="color: rgb(153, 153, 153);">54</li><li style="color: rgb(153, 153, 153);">55</li><li style="color: rgb(153, 153, 153);">56</li><li style="color: rgb(153, 153, 153);">57</li><li style="color: rgb(153, 153, 153);">58</li><li style="color: rgb(153, 153, 153);">59</li><li style="color: rgb(153, 153, 153);">60</li><li style="color: rgb(153, 153, 153);">61</li><li style="color: rgb(153, 153, 153);">62</li><li style="color: rgb(153, 153, 153);">63</li><li style="color: rgb(153, 153, 153);">64</li><li style="color: rgb(153, 153, 153);">65</li><li style="color: rgb(153, 153, 153);">66</li><li style="color: rgb(153, 153, 153);">67</li><li style="color: rgb(153, 153, 153);">68</li><li style="color: rgb(153, 153, 153);">69</li><li style="color: rgb(153, 153, 153);">70</li><li style="color: rgb(153, 153, 153);">71</li><li style="color: rgb(153, 153, 153);">72</li><li style="color: rgb(153, 153, 153);">73</li><li style="color: rgb(153, 153, 153);">74</li><li style="color: rgb(153, 153, 153);">75</li><li style="color: rgb(153, 153, 153);">76</li><li style="color: rgb(153, 153, 153);">77</li><li style="color: rgb(153, 153, 153);">78</li><li style="color: rgb(153, 153, 153);">79</li><li style="color: rgb(153, 153, 153);">80</li><li style="color: rgb(153, 153, 153);">81</li><li style="color: rgb(153, 153, 153);">82</li><li style="color: rgb(153, 153, 153);">83</li><li style="color: rgb(153, 153, 153);">84</li><li style="color: rgb(153, 153, 153);">85</li><li style="color: rgb(153, 153, 153);">86</li><li style="color: rgb(153, 153, 153);">87</li><li style="color: rgb(153, 153, 153);">88</li><li style="color: rgb(153, 153, 153);">89</li><li style="color: rgb(153, 153, 153);">90</li><li style="color: rgb(153, 153, 153);">91</li><li style="color: rgb(153, 153, 153);">92</li><li style="color: rgb(153, 153, 153);">93</li><li style="color: rgb(153, 153, 153);">94</li><li style="color: rgb(153, 153, 153);">95</li><li style="color: rgb(153, 153, 153);">96</li><li style="color: rgb(153, 153, 153);">97</li><li style="color: rgb(153, 153, 153);">98</li><li style="color: rgb(153, 153, 153);">99</li><li style="color: rgb(153, 153, 153);">100</li><li style="color: rgb(153, 153, 153);">101</li><li style="color: rgb(153, 153, 153);">102</li><li style="color: rgb(153, 153, 153);">103</li><li style="color: rgb(153, 153, 153);">104</li><li style="color: rgb(153, 153, 153);">105</li><li style="color: rgb(153, 153, 153);">106</li><li style="color: rgb(153, 153, 153);">107</li><li style="color: rgb(153, 153, 153);">108</li><li style="color: rgb(153, 153, 153);">109</li><li style="color: rgb(153, 153, 153);">110</li><li style="color: rgb(153, 153, 153);">111</li><li style="color: rgb(153, 153, 153);">112</li><li style="color: rgb(153, 153, 153);">113</li><li style="color: rgb(153, 153, 153);">114</li><li style="color: rgb(153, 153, 153);">115</li><li style="color: rgb(153, 153, 153);">116</li><li style="color: rgb(153, 153, 153);">117</li><li style="color: rgb(153, 153, 153);">118</li><li style="color: rgb(153, 153, 153);">119</li><li style="color: rgb(153, 153, 153);">120</li><li style="color: rgb(153, 153, 153);">121</li><li style="color: rgb(153, 153, 153);">122</li><li style="color: rgb(153, 153, 153);">123</li><li style="color: rgb(153, 153, 153);">124</li><li style="color: rgb(153, 153, 153);">125</li><li style="color: rgb(153, 153, 153);">126</li><li style="color: rgb(153, 153, 153);">127</li><li style="color: rgb(153, 153, 153);">128</li><li style="color: rgb(153, 153, 153);">129</li><li style="color: rgb(153, 153, 153);">130</li><li style="color: rgb(153, 153, 153);">131</li><li style="color: rgb(153, 153, 153);">132</li><li style="color: rgb(153, 153, 153);">133</li><li style="color: rgb(153, 153, 153);">134</li><li style="color: rgb(153, 153, 153);">135</li></ul></pre>


<p>总结:</p>


<ul>
<li>消息循环的操作 = 消息出队 + 分发给对应的<code>Handler</code>实例</li>
<li>分发给对应的<code>Handler</code>的过程:根据出队消息的归属者通过<code>dispatchMessage(msg)</code>进行分发,最终回调复写的<code>handleMessage(Message msg)</code>,从而实现 消息处理 的操作</li>
<li>特别注意:在进行消息分发时<code>(dispatchMessage(msg))</code>,会进行1次发送方式的判断: <br>
<ol><li>若<code>msg.callback</code>属性不为空,则代表使用了<code>post(Runnable r)</code>发送消息,则直接回调<code>Runnable</code>对象里复写的<code>run()</code></li>
<li>若<code>msg.callback</code>属性为空,则代表使用了<code>sendMessage(Message msg)</code>发送消息,则回调复写的<code>handleMessage(msg)</code></li></ol></li>
</ul>


<p><strong>至此,关于步骤1的源码分析讲解完毕</strong>。总结如下</p>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-c18fc8b78d4ec73c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<hr>


<h3 id="步骤2创建消息对象"><a name="t16"></a>步骤2:创建消息对象</h3>






<pre class="prettyprint" name="code"><code class="hljs java has-numbering"><span class="hljs-javadoc">/** 
  * 具体使用
  */</span>
    Message msg = Message.obtain(); <span class="hljs-comment">// 实例化消息对象</span>
    msg.what = <span class="hljs-number">1</span>; <span class="hljs-comment">// 消息标识</span>
    msg.obj = <span class="hljs-string">"AA"</span>; <span class="hljs-comment">// 消息内容存放</span>


<span class="hljs-javadoc">/** 
  * 源码分析:Message.obtain()
  * 作用:创建消息对象
  * 注:创建Message对象可用关键字new 或 Message.obtain()
  */</span>
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Message <span class="hljs-title">obtain</span>() {


        <span class="hljs-comment">// Message内部维护了1个Message池,用于Message消息对象的复用</span>
        <span class="hljs-comment">// 使用obtain()则是直接从池内获取</span>
        <span class="hljs-keyword">synchronized</span> (sPoolSync) {
            <span class="hljs-keyword">if</span> (sPool != <span class="hljs-keyword">null</span>) {
                Message m = sPool;
                sPool = m.next;
                m.next = <span class="hljs-keyword">null</span>;
                m.flags = <span class="hljs-number">0</span>; <span class="hljs-comment">// clear in-use flag</span>
                sPoolSize--;
                <span class="hljs-keyword">return</span> m;
            }
            <span class="hljs-comment">// 建议:使用obtain()”创建“消息对象,避免每次都使用new重新分配内存</span>
        }
        <span class="hljs-comment">// 若池内无消息对象可复用,则还是用关键字new创建</span>
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Message();


    }</code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li><li style="color: rgb(153, 153, 153);">17</li><li style="color: rgb(153, 153, 153);">18</li><li style="color: rgb(153, 153, 153);">19</li><li style="color: rgb(153, 153, 153);">20</li><li style="color: rgb(153, 153, 153);">21</li><li style="color: rgb(153, 153, 153);">22</li><li style="color: rgb(153, 153, 153);">23</li><li style="color: rgb(153, 153, 153);">24</li><li style="color: rgb(153, 153, 153);">25</li><li style="color: rgb(153, 153, 153);">26</li><li style="color: rgb(153, 153, 153);">27</li><li style="color: rgb(153, 153, 153);">28</li><li style="color: rgb(153, 153, 153);">29</li><li style="color: rgb(153, 153, 153);">30</li><li style="color: rgb(153, 153, 153);">31</li></ul></pre>


<ul>
<li>总结</li>
</ul>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-79f00f900b3471c0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>






<h3 id="步骤3在工作线程中-发送消息到消息队列中"><a name="t17"></a>步骤3:在工作线程中 发送消息到消息队列中</h3>


<blockquote>
  <p>多线程的实现方式:<code>AsyncTask</code>、继承<code>Thread</code>类、实现<code>Runnable</code> </p>
</blockquote>






<pre class="prettyprint" name="code"><code class="hljs java has-numbering"><span class="hljs-javadoc">/** 
  * 具体使用
  */</span>


    mHandler.sendMessage(msg);


<span class="hljs-javadoc">/** 
  * 源码分析:mHandler.sendMessage(msg)
  * 定义:属于处理器类(Handler)的方法
  * 作用:将消息 发送 到消息队列中(Message -&gt;&gt; MessageQueue)
  */</span>
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">sendMessage</span>(Message msg)
    {
        <span class="hljs-keyword">return</span> sendMessageDelayed(msg, <span class="hljs-number">0</span>);
        <span class="hljs-comment">// -&gt;&gt;分析1</span>
    }


         <span class="hljs-javadoc">/** 
           * 分析1:sendMessageDelayed(msg, 0)
           **/</span>
           <span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">sendMessageDelayed</span>(Message msg, <span class="hljs-keyword">long</span> delayMillis)
            {
                <span class="hljs-keyword">if</span> (delayMillis &lt; <span class="hljs-number">0</span>) {
                    delayMillis = <span class="hljs-number">0</span>;
                }


                <span class="hljs-keyword">return</span> sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
                <span class="hljs-comment">// -&gt;&gt; 分析2</span>
            }


         <span class="hljs-javadoc">/** 
           * 分析2:sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis)
           **/</span>
           <span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">sendMessageAtTime</span>(Message msg, <span class="hljs-keyword">long</span> uptimeMillis) {
                    <span class="hljs-comment">// 1. 获取对应的消息队列对象(MessageQueue)</span>
                    MessageQueue queue = mQueue;


                    <span class="hljs-comment">// 2. 调用了enqueueMessage方法 -&gt;&gt;分析3</span>
                    <span class="hljs-keyword">return</span> enqueueMessage(queue, msg, uptimeMillis);
                }


         <span class="hljs-javadoc">/** 
           * 分析3:enqueueMessage(queue, msg, uptimeMillis)
           **/</span>
            <span class="hljs-keyword">private</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">enqueueMessage</span>(MessageQueue queue, Message msg, <span class="hljs-keyword">long</span> uptimeMillis) {
                 <span class="hljs-comment">// 1. 将msg.target赋值为this</span>
                 <span class="hljs-comment">// 即 :把 当前的Handler实例对象作为msg的target属性</span>
                 msg.target = <span class="hljs-keyword">this</span>;
                 <span class="hljs-comment">// 请回忆起上面说的Looper的loop()中消息循环时,会从消息队列中取出每个消息msg,然后执行msg.target.dispatchMessage(msg)去处理消息</span>
                 <span class="hljs-comment">// 实际上则是将该消息派发给对应的Handler实例        </span>


                <span class="hljs-comment">// 2. 调用消息队列的enqueueMessage()</span>
                <span class="hljs-comment">// 即:Handler发送的消息,最终是保存到消息队列-&gt;&gt;分析4</span>
                <span class="hljs-keyword">return</span> queue.enqueueMessage(msg, uptimeMillis);
        }


        <span class="hljs-javadoc">/** 
          * 分析4:queue.enqueueMessage(msg, uptimeMillis)
          * 定义:属于消息队列类(MessageQueue)的方法
          * 作用:入队,即 将消息 根据时间 放入到消息队列中(Message -&gt;&gt; MessageQueue)
          * 采用单链表实现:提高插入消息、删除消息的效率
          */</span>
          <span class="hljs-keyword">boolean</span> enqueueMessage(Message msg, <span class="hljs-keyword">long</span> when) {


                ...<span class="hljs-comment">// 仅贴出关键代码</span>


                <span class="hljs-keyword">synchronized</span> (<span class="hljs-keyword">this</span>) {


                    msg.markInUse();
                    msg.when = when;
                    Message p = mMessages;
                    <span class="hljs-keyword">boolean</span> needWake;


                    <span class="hljs-comment">// 判断消息队列里有无消息</span>
                        <span class="hljs-comment">// a. 若无,则将当前插入的消息 作为队头 &amp; 若此时消息队列处于等待状态,则唤醒</span>
                        <span class="hljs-keyword">if</span> (p == <span class="hljs-keyword">null</span> || when == <span class="hljs-number">0</span> || when &lt; p.when) {
                            msg.next = p;
                            mMessages = msg;
                            needWake = mBlocked;
                        } <span class="hljs-keyword">else</span> {
                            needWake = mBlocked &amp;&amp; p.target == <span class="hljs-keyword">null</span> &amp;&amp; msg.isAsynchronous();
                            Message prev;


                        <span class="hljs-comment">// b. 判断消息队列里有消息,则根据 消息(Message)创建的时间 插入到队列中</span>
                            <span class="hljs-keyword">for</span> (;;) {
                                prev = p;
                                p = p.next;
                                <span class="hljs-keyword">if</span> (p == <span class="hljs-keyword">null</span> || when &lt; p.when) {
                                    <span class="hljs-keyword">break</span>;
                                }
                                <span class="hljs-keyword">if</span> (needWake &amp;&amp; p.isAsynchronous()) {
                                    needWake = <span class="hljs-keyword">false</span>;
                                }
                            }


                            msg.next = p; 
                            prev.next = msg;
                        }


                        <span class="hljs-keyword">if</span> (needWake) {
                            nativeWake(mPtr);
                        }
                    }
                    <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;
            }


<span class="hljs-comment">// 之后,随着Looper对象的无限消息循环</span>
<span class="hljs-comment">// 不断从消息队列中取出Handler发送的消息 &amp; 分发到对应Handler</span>
<span class="hljs-comment">// 最终回调Handler.handleMessage()处理消息</span></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li><li style="color: rgb(153, 153, 153);">17</li><li style="color: rgb(153, 153, 153);">18</li><li style="color: rgb(153, 153, 153);">19</li><li style="color: rgb(153, 153, 153);">20</li><li style="color: rgb(153, 153, 153);">21</li><li style="color: rgb(153, 153, 153);">22</li><li style="color: rgb(153, 153, 153);">23</li><li style="color: rgb(153, 153, 153);">24</li><li style="color: rgb(153, 153, 153);">25</li><li style="color: rgb(153, 153, 153);">26</li><li style="color: rgb(153, 153, 153);">27</li><li style="color: rgb(153, 153, 153);">28</li><li style="color: rgb(153, 153, 153);">29</li><li style="color: rgb(153, 153, 153);">30</li><li style="color: rgb(153, 153, 153);">31</li><li style="color: rgb(153, 153, 153);">32</li><li style="color: rgb(153, 153, 153);">33</li><li style="color: rgb(153, 153, 153);">34</li><li style="color: rgb(153, 153, 153);">35</li><li style="color: rgb(153, 153, 153);">36</li><li style="color: rgb(153, 153, 153);">37</li><li style="color: rgb(153, 153, 153);">38</li><li style="color: rgb(153, 153, 153);">39</li><li style="color: rgb(153, 153, 153);">40</li><li style="color: rgb(153, 153, 153);">41</li><li style="color: rgb(153, 153, 153);">42</li><li style="color: rgb(153, 153, 153);">43</li><li style="color: rgb(153, 153, 153);">44</li><li style="color: rgb(153, 153, 153);">45</li><li style="color: rgb(153, 153, 153);">46</li><li style="color: rgb(153, 153, 153);">47</li><li style="color: rgb(153, 153, 153);">48</li><li style="color: rgb(153, 153, 153);">49</li><li style="color: rgb(153, 153, 153);">50</li><li style="color: rgb(153, 153, 153);">51</li><li style="color: rgb(153, 153, 153);">52</li><li style="color: rgb(153, 153, 153);">53</li><li style="color: rgb(153, 153, 153);">54</li><li style="color: rgb(153, 153, 153);">55</li><li style="color: rgb(153, 153, 153);">56</li><li style="color: rgb(153, 153, 153);">57</li><li style="color: rgb(153, 153, 153);">58</li><li style="color: rgb(153, 153, 153);">59</li><li style="color: rgb(153, 153, 153);">60</li><li style="color: rgb(153, 153, 153);">61</li><li style="color: rgb(153, 153, 153);">62</li><li style="color: rgb(153, 153, 153);">63</li><li style="color: rgb(153, 153, 153);">64</li><li style="color: rgb(153, 153, 153);">65</li><li style="color: rgb(153, 153, 153);">66</li><li style="color: rgb(153, 153, 153);">67</li><li style="color: rgb(153, 153, 153);">68</li><li style="color: rgb(153, 153, 153);">69</li><li style="color: rgb(153, 153, 153);">70</li><li style="color: rgb(153, 153, 153);">71</li><li style="color: rgb(153, 153, 153);">72</li><li style="color: rgb(153, 153, 153);">73</li><li style="color: rgb(153, 153, 153);">74</li><li style="color: rgb(153, 153, 153);">75</li><li style="color: rgb(153, 153, 153);">76</li><li style="color: rgb(153, 153, 153);">77</li><li style="color: rgb(153, 153, 153);">78</li><li style="color: rgb(153, 153, 153);">79</li><li style="color: rgb(153, 153, 153);">80</li><li style="color: rgb(153, 153, 153);">81</li><li style="color: rgb(153, 153, 153);">82</li><li style="color: rgb(153, 153, 153);">83</li><li style="color: rgb(153, 153, 153);">84</li><li style="color: rgb(153, 153, 153);">85</li><li style="color: rgb(153, 153, 153);">86</li><li style="color: rgb(153, 153, 153);">87</li><li style="color: rgb(153, 153, 153);">88</li><li style="color: rgb(153, 153, 153);">89</li><li style="color: rgb(153, 153, 153);">90</li><li style="color: rgb(153, 153, 153);">91</li><li style="color: rgb(153, 153, 153);">92</li><li style="color: rgb(153, 153, 153);">93</li><li style="color: rgb(153, 153, 153);">94</li><li style="color: rgb(153, 153, 153);">95</li><li style="color: rgb(153, 153, 153);">96</li><li style="color: rgb(153, 153, 153);">97</li><li style="color: rgb(153, 153, 153);">98</li><li style="color: rgb(153, 153, 153);">99</li><li style="color: rgb(153, 153, 153);">100</li><li style="color: rgb(153, 153, 153);">101</li><li style="color: rgb(153, 153, 153);">102</li><li style="color: rgb(153, 153, 153);">103</li><li style="color: rgb(153, 153, 153);">104</li><li style="color: rgb(153, 153, 153);">105</li><li style="color: rgb(153, 153, 153);">106</li><li style="color: rgb(153, 153, 153);">107</li><li style="color: rgb(153, 153, 153);">108</li><li style="color: rgb(153, 153, 153);">109</li></ul></pre>


<ul>
<li>总结 <br>
<code>Handler</code>发送消息的本质 = 为该消息定义<code>target</code>属性(即本身实例对象) &amp; 将消息入队到绑定线程的消息队列中。具体如下:</li>
</ul>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-338542d6a7ced4a8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<p>至此,关于使用 <code>Handler.sendMessage()</code>的源码解析完毕</p>






<h3 id="总结"><a name="t18"></a>总结</h3>


<ul>
<li>根据操作步骤的源码分析总结</li>
</ul>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-6cf14c6dc05cbf66.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<ul>
<li>工作流程总结</li>
</ul>






<h1 id="下面将顺着文章工作流程再理一次"><a name="t19"></a>下面,将顺着文章:工作流程再理一次</h1>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-b649e05ecbf437c8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-0d7d6f8294f4f4d4.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<hr>






<h3 id="方式2使用-handlerpost"><a name="t20"></a>方式2:使用 Handler.post()</h3>


<ul>
<li>使用步骤</li>
</ul>






<pre class="prettyprint" name="code"><code class="hljs java has-numbering"><span class="hljs-comment">// 步骤1:在主线程中创建Handler实例</span>
    <span class="hljs-keyword">private</span> Handler mhandler = <span class="hljs-keyword">new</span> mHandler();


<span class="hljs-comment">// 步骤2:在工作线程中 发送消息到消息队列中 &amp; 指定操作UI内容</span>
<span class="hljs-comment">// 需传入1个Runnable对象</span>
    mHandler.post(<span class="hljs-keyword">new</span> Runnable() {
            <span class="hljs-annotation">@Override</span>
            <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span>() {
                ... <span class="hljs-comment">// 需执行的UI操作 </span>
            }


    });


<span class="hljs-comment">// 步骤3:开启工作线程(同时启动了Handler)</span>
<span class="hljs-comment">// 多线程可采用AsyncTask、继承Thread类、实现Runnable</span></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li></ul></pre>


<ul>
<li>源码分析 <br>
下面,我将根据上述每个步骤进行源码分析 <br>




<blockquote>
  实际上,该方式与方式1中的<code>Handler.sendMessage()</code>工作原理相同、源码分析类似,下面将主要讲解不同之处</blockquote></li>
  </ul>
  




<h3 id="步骤1在主线程中创建handler实例"><a name="t21"></a>步骤1:在主线程中创建Handler实例</h3>












<pre class="prettyprint" name="code"><code class="hljs java has-numbering"><span class="hljs-javadoc">/** 
  * 具体使用
  */</span>
    <span class="hljs-keyword">private</span> Handler mhandler = <span class="hljs-keyword">new</span>  Handler();
    <span class="hljs-comment">// 与方式1的使用不同:此处无复写Handler.handleMessage()</span>


<span class="hljs-javadoc">/** 
  * 源码分析:Handler的构造方法
  * 作用:
  *     a. 在此之前,主线程创建时隐式创建Looper对象、MessageQueue对象
  *     b. 初始化Handler对象、绑定线程 &amp; 进入消息循环
  * 此处的源码分析类似方式1,此处不作过多描述
  */</span></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li></ul></pre>


























<h3 id="步骤2在工作线程中-发送消息到消息队列中"><a name="t22"></a>步骤2:在工作线程中 发送消息到消息队列中</h3>






<pre class="prettyprint" name="code"><code class="hljs java has-numbering"><span class="hljs-javadoc">/** 
  * 具体使用
  * 需传入1个Runnable对象、复写run()从而指定UI操作
  */</span>
    mHandler.post(<span class="hljs-keyword">new</span> Runnable() {
            <span class="hljs-annotation">@Override</span>
            <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span>() {
                ... <span class="hljs-comment">// 需执行的UI操作 </span>
            }


    });


<span class="hljs-javadoc">/** 
  * 源码分析:Handler.post(Runnable r)
  * 定义:属于处理者类(Handler)中的方法
  * 作用:定义UI操作、将Runnable对象封装成消息对象 &amp; 发送 到消息队列中(Message -&gt;&gt; MessageQueue)
  * 注:
  *    a. 相比sendMessage(),post()最大的不同在于,更新的UI操作可直接在重写的run()中定义
  *    b. 实际上,Runnable并无创建新线程,而是发送 消息 到消息队列中
  */</span>
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">post</span>(Runnable r)
        {
           <span class="hljs-keyword">return</span>  sendMessageDelayed(getPostMessage(r), <span class="hljs-number">0</span>);
           <span class="hljs-comment">// getPostMessage(r) 的源码分析-&gt;&gt;分析1</span>
           <span class="hljs-comment">// sendMessageDelayed()的源码分析 -&gt;&gt;分析2</span>


        }
              <span class="hljs-javadoc">/** 
               * 分析1:getPostMessage(r)
               * 作用:将传入的Runable对象封装成1个消息对象
               **/</span>
              <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> Message <span class="hljs-title">getPostMessage</span>(Runnable r) {
                        <span class="hljs-comment">// 1. 创建1个消息对象(Message)</span>
                        Message m = Message.obtain();
                            <span class="hljs-comment">// 注:创建Message对象可用关键字new 或 Message.obtain()</span>
                            <span class="hljs-comment">// 建议:使用Message.obtain()创建,</span>
                            <span class="hljs-comment">// 原因:因为Message内部维护了1个Message池,用于Message的复用,使用obtain()直接从池内获取,从而避免使用new重新分配内存</span>


                        <span class="hljs-comment">// 2. 将 Runable对象 赋值给消息对象(message)的callback属性</span>
                        m.callback = r;


                        <span class="hljs-comment">// 3. 返回该消息对象</span>
                        <span class="hljs-keyword">return</span> m;
                    } <span class="hljs-comment">// 回到调用原处</span>


             <span class="hljs-javadoc">/** 
               * 分析2:sendMessageDelayed(msg, 0)
               * 作用:实际上,从此处开始,则类似方式1 = 将消息入队到消息队列,
               * 即 最终是调用MessageQueue.enqueueMessage()
               **/</span>
               <span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">sendMessageDelayed</span>(Message msg, <span class="hljs-keyword">long</span> delayMillis)
                {
                    <span class="hljs-keyword">if</span> (delayMillis &lt; <span class="hljs-number">0</span>) {
                        delayMillis = <span class="hljs-number">0</span>;
                    }


                    <span class="hljs-keyword">return</span> sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
                    <span class="hljs-comment">// 请看分析3</span>
                }


             <span class="hljs-javadoc">/** 
               * 分析3:sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis)
               **/</span>
               <span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">sendMessageAtTime</span>(Message msg, <span class="hljs-keyword">long</span> uptimeMillis) {
                        <span class="hljs-comment">// 1. 获取对应的消息队列对象(MessageQueue)</span>
                        MessageQueue queue = mQueue;


                        <span class="hljs-comment">// 2. 调用了enqueueMessage方法 -&gt;&gt;分析3</span>
                        <span class="hljs-keyword">return</span> enqueueMessage(queue, msg, uptimeMillis);
                    }


             <span class="hljs-javadoc">/** 
               * 分析4:enqueueMessage(queue, msg, uptimeMillis)
               **/</span>
                <span class="hljs-keyword">private</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">enqueueMessage</span>(MessageQueue queue, Message msg, <span class="hljs-keyword">long</span> uptimeMillis) {
                     <span class="hljs-comment">// 1. 将msg.target赋值为this</span>
                     <span class="hljs-comment">// 即 :把 当前的Handler实例对象作为msg的target属性</span>
                     msg.target = <span class="hljs-keyword">this</span>;
                     <span class="hljs-comment">// 请回忆起上面说的Looper的loop()中消息循环时,会从消息队列中取出每个消息msg,然后执行msg.target.dispatchMessage(msg)去处理消息</span>
                     <span class="hljs-comment">// 实际上则是将该消息派发给对应的Handler实例        </span>


                    <span class="hljs-comment">// 2. 调用消息队列的enqueueMessage()</span>
                    <span class="hljs-comment">// 即:Handler发送的消息,最终是保存到消息队列</span>
                    <span class="hljs-keyword">return</span> queue.enqueueMessage(msg, uptimeMillis);
            }


            <span class="hljs-comment">// 注:实际上从分析2开始,源码 与 sendMessage(Message msg)发送方式相同</span>
</code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li><li style="color: rgb(153, 153, 153);">17</li><li style="color: rgb(153, 153, 153);">18</li><li style="color: rgb(153, 153, 153);">19</li><li style="color: rgb(153, 153, 153);">20</li><li style="color: rgb(153, 153, 153);">21</li><li style="color: rgb(153, 153, 153);">22</li><li style="color: rgb(153, 153, 153);">23</li><li style="color: rgb(153, 153, 153);">24</li><li style="color: rgb(153, 153, 153);">25</li><li style="color: rgb(153, 153, 153);">26</li><li style="color: rgb(153, 153, 153);">27</li><li style="color: rgb(153, 153, 153);">28</li><li style="color: rgb(153, 153, 153);">29</li><li style="color: rgb(153, 153, 153);">30</li><li style="color: rgb(153, 153, 153);">31</li><li style="color: rgb(153, 153, 153);">32</li><li style="color: rgb(153, 153, 153);">33</li><li style="color: rgb(153, 153, 153);">34</li><li style="color: rgb(153, 153, 153);">35</li><li style="color: rgb(153, 153, 153);">36</li><li style="color: rgb(153, 153, 153);">37</li><li style="color: rgb(153, 153, 153);">38</li><li style="color: rgb(153, 153, 153);">39</li><li style="color: rgb(153, 153, 153);">40</li><li style="color: rgb(153, 153, 153);">41</li><li style="color: rgb(153, 153, 153);">42</li><li style="color: rgb(153, 153, 153);">43</li><li style="color: rgb(153, 153, 153);">44</li><li style="color: rgb(153, 153, 153);">45</li><li style="color: rgb(153, 153, 153);">46</li><li style="color: rgb(153, 153, 153);">47</li><li style="color: rgb(153, 153, 153);">48</li><li style="color: rgb(153, 153, 153);">49</li><li style="color: rgb(153, 153, 153);">50</li><li style="color: rgb(153, 153, 153);">51</li><li style="color: rgb(153, 153, 153);">52</li><li style="color: rgb(153, 153, 153);">53</li><li style="color: rgb(153, 153, 153);">54</li><li style="color: rgb(153, 153, 153);">55</li><li style="color: rgb(153, 153, 153);">56</li><li style="color: rgb(153, 153, 153);">57</li><li style="color: rgb(153, 153, 153);">58</li><li style="color: rgb(153, 153, 153);">59</li><li style="color: rgb(153, 153, 153);">60</li><li style="color: rgb(153, 153, 153);">61</li><li style="color: rgb(153, 153, 153);">62</li><li style="color: rgb(153, 153, 153);">63</li><li style="color: rgb(153, 153, 153);">64</li><li style="color: rgb(153, 153, 153);">65</li><li style="color: rgb(153, 153, 153);">66</li><li style="color: rgb(153, 153, 153);">67</li><li style="color: rgb(153, 153, 153);">68</li><li style="color: rgb(153, 153, 153);">69</li><li style="color: rgb(153, 153, 153);">70</li><li style="color: rgb(153, 153, 153);">71</li><li style="color: rgb(153, 153, 153);">72</li><li style="color: rgb(153, 153, 153);">73</li><li style="color: rgb(153, 153, 153);">74</li><li style="color: rgb(153, 153, 153);">75</li><li style="color: rgb(153, 153, 153);">76</li><li style="color: rgb(153, 153, 153);">77</li><li style="color: rgb(153, 153, 153);">78</li><li style="color: rgb(153, 153, 153);">79</li><li style="color: rgb(153, 153, 153);">80</li><li style="color: rgb(153, 153, 153);">81</li><li style="color: rgb(153, 153, 153);">82</li><li style="color: rgb(153, 153, 153);">83</li><li style="color: rgb(153, 153, 153);">84</li><li style="color: rgb(153, 153, 153);">85</li><li style="color: rgb(153, 153, 153);">86</li><li style="color: rgb(153, 153, 153);">87</li><li style="color: rgb(153, 153, 153);">88</li></ul></pre>


<p>从上面的分析可看出:</p>


<ol>
<li>消息对象的创建 = 内部 根据<code>Runnable</code>对象而封装</li>
<li>发送到消息队列的逻辑 = 方式1中<code>sendMessage(Message msg)</code></li>
</ol>


<p>下面,我们重新回到步骤1前的隐式操作2:消息循环,即<code>Looper</code>类中的<code>loop()</code>方法</p>


<pre class="prettyprint" name="code"><code class="hljs java has-numbering"><span class="hljs-javadoc">/** 
  * 源码分析: Looper.loop()
  * 作用:消息循环,即从消息队列中获取消息、分发消息到Handler
  * 特别注意:
  *       a. 主线程的消息循环不允许退出,即无限循环
  *       b. 子线程的消息循环允许退出:调用消息队列MessageQueue的quit()
  */</span>
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">loop</span>() {


        ...<span class="hljs-comment">// 仅贴出关键代码</span>


        <span class="hljs-comment">// 1. 获取当前Looper的消息队列</span>
            <span class="hljs-keyword">final</span> Looper me = myLooper();
            <span class="hljs-keyword">if</span> (me == <span class="hljs-keyword">null</span>) {
                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(<span class="hljs-string">"No Looper; Looper.prepare() wasn't called on this thread."</span>);
            }
            <span class="hljs-comment">// myLooper()作用:返回sThreadLocal存储的Looper实例;若me为null 则抛出异常</span>
            <span class="hljs-comment">// 即loop()执行前必须执行prepare(),从而创建1个Looper实例</span>


            <span class="hljs-keyword">final</span> MessageQueue queue = me.mQueue;
            <span class="hljs-comment">// 获取Looper实例中的消息队列对象(MessageQueue)</span>


        <span class="hljs-comment">// 2. 消息循环(通过for循环)</span>
            <span class="hljs-keyword">for</span> (;;) {


            <span class="hljs-comment">// 2.1 从消息队列中取出消息</span>
            Message msg = queue.next(); 
            <span class="hljs-keyword">if</span> (msg == <span class="hljs-keyword">null</span>) {
                <span class="hljs-keyword">return</span>;
            }
            <span class="hljs-comment">// next():取出消息队列里的消息</span>
            <span class="hljs-comment">// 若取出的消息为空,则线程阻塞</span>


            <span class="hljs-comment">// 2.2 派发消息到对应的Handler</span>
            msg.target.dispatchMessage(msg);
            <span class="hljs-comment">// 把消息Message派发给消息对象msg的target属性</span>
            <span class="hljs-comment">// target属性实际是1个handler对象</span>
            <span class="hljs-comment">// -&gt;&gt;分析1</span>


        <span class="hljs-comment">// 3. 释放消息占据的资源</span>
        msg.recycle();
        }
}


<span class="hljs-javadoc">/** 
  * 分析1:dispatchMessage(msg)
  * 定义:属于处理者类(Handler)中的方法
  * 作用:派发消息到对应的Handler实例 &amp; 根据传入的msg作出对应的操作
  */</span>
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">dispatchMessage</span>(Message msg) {


    <span class="hljs-comment">// 1. 若msg.callback属性不为空,则代表使用了post(Runnable r)发送消息(即此处需讨论的)</span>
    <span class="hljs-comment">// 则执行handleCallback(msg),即回调Runnable对象里复写的run()-&gt;&gt; 分析2</span>
        <span class="hljs-keyword">if</span> (msg.callback != <span class="hljs-keyword">null</span>) {
            handleCallback(msg);
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-keyword">if</span> (mCallback != <span class="hljs-keyword">null</span>) {
                <span class="hljs-keyword">if</span> (mCallback.handleMessage(msg)) {
                    <span class="hljs-keyword">return</span>;
                }
            }


            <span class="hljs-comment">// 2. 若msg.callback属性为空,则代表使用了sendMessage(Message msg)发送消息(即此处需讨论的)</span>
            <span class="hljs-comment">// 则执行handleMessage(msg),即回调复写的handleMessage(msg) </span>
            handleMessage(msg);


        }
    }


  <span class="hljs-javadoc">/** 
    * 分析2:handleCallback(msg)
    **/</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">handleCallback</span>(Message message) {
        message.callback.run();
        <span class="hljs-comment">//  Message对象的callback属性 = 传入的Runnable对象</span>
        <span class="hljs-comment">// 即回调Runnable对象里复写的run()</span>
    }</code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li><li style="color: rgb(153, 153, 153);">17</li><li style="color: rgb(153, 153, 153);">18</li><li style="color: rgb(153, 153, 153);">19</li><li style="color: rgb(153, 153, 153);">20</li><li style="color: rgb(153, 153, 153);">21</li><li style="color: rgb(153, 153, 153);">22</li><li style="color: rgb(153, 153, 153);">23</li><li style="color: rgb(153, 153, 153);">24</li><li style="color: rgb(153, 153, 153);">25</li><li style="color: rgb(153, 153, 153);">26</li><li style="color: rgb(153, 153, 153);">27</li><li style="color: rgb(153, 153, 153);">28</li><li style="color: rgb(153, 153, 153);">29</li><li style="color: rgb(153, 153, 153);">30</li><li style="color: rgb(153, 153, 153);">31</li><li style="color: rgb(153, 153, 153);">32</li><li style="color: rgb(153, 153, 153);">33</li><li style="color: rgb(153, 153, 153);">34</li><li style="color: rgb(153, 153, 153);">35</li><li style="color: rgb(153, 153, 153);">36</li><li style="color: rgb(153, 153, 153);">37</li><li style="color: rgb(153, 153, 153);">38</li><li style="color: rgb(153, 153, 153);">39</li><li style="color: rgb(153, 153, 153);">40</li><li style="color: rgb(153, 153, 153);">41</li><li style="color: rgb(153, 153, 153);">42</li><li style="color: rgb(153, 153, 153);">43</li><li style="color: rgb(153, 153, 153);">44</li><li style="color: rgb(153, 153, 153);">45</li><li style="color: rgb(153, 153, 153);">46</li><li style="color: rgb(153, 153, 153);">47</li><li style="color: rgb(153, 153, 153);">48</li><li style="color: rgb(153, 153, 153);">49</li><li style="color: rgb(153, 153, 153);">50</li><li style="color: rgb(153, 153, 153);">51</li><li style="color: rgb(153, 153, 153);">52</li><li style="color: rgb(153, 153, 153);">53</li><li style="color: rgb(153, 153, 153);">54</li><li style="color: rgb(153, 153, 153);">55</li><li style="color: rgb(153, 153, 153);">56</li><li style="color: rgb(153, 153, 153);">57</li><li style="color: rgb(153, 153, 153);">58</li><li style="color: rgb(153, 153, 153);">59</li><li style="color: rgb(153, 153, 153);">60</li><li style="color: rgb(153, 153, 153);">61</li><li style="color: rgb(153, 153, 153);">62</li><li style="color: rgb(153, 153, 153);">63</li><li style="color: rgb(153, 153, 153);">64</li><li style="color: rgb(153, 153, 153);">65</li><li style="color: rgb(153, 153, 153);">66</li><li style="color: rgb(153, 153, 153);">67</li><li style="color: rgb(153, 153, 153);">68</li><li style="color: rgb(153, 153, 153);">69</li><li style="color: rgb(153, 153, 153);">70</li><li style="color: rgb(153, 153, 153);">71</li><li style="color: rgb(153, 153, 153);">72</li><li style="color: rgb(153, 153, 153);">73</li><li style="color: rgb(153, 153, 153);">74</li><li style="color: rgb(153, 153, 153);">75</li><li style="color: rgb(153, 153, 153);">76</li><li style="color: rgb(153, 153, 153);">77</li></ul></pre>


<p>至此,你应该明白使用 <code>Handler.post()</code>的工作流程:与方式1<code>(Handler.sendMessage())</code>类似,区别在于:</p>


<ol>
<li>不需外部创建消息对象,而是内部根据传入的<code>Runnable</code>对象 封装消息对象</li>
<li>回调的消息处理方法是:复写<code>Runnable</code>对象的<code>run()</code></li>
</ol>


<p>二者的具体异同如下:</p>


<p><img src="https://upload-images.jianshu.io/upload_images/944365-29fc8832f4a8b399.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<p>至此,关于使用 <code>Handler.post()</code>的源码解析完毕</p>






<h3 id="总结-1"><a name="t23"></a>总结</h3>


<ul>
<li><p>根据操作步骤的源码分析总结 <br>
<img src="http://upload-images.jianshu.io/upload_images/944365-62eb790fbcdff4cd.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p></li>
<li><p>工作流程总结</p></li>
</ul>






<h1 id="下面将顺着文章工作流程再理一次-1"><a name="t24"></a>下面,将顺着文章:工作流程再理一次</h1>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-b649e05ecbf437c8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-58a275152eb5099a.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<p><strong>至此,关于<code>Handler</code>机制的源码全部分析完毕。</strong></p>


<hr>






<h1 id="5-总结"><a name="t25"></a>5. 总结</h1>


<ul>
<li>本文详细分析了<code>Handler</code>机制的源码,文字总结 &amp; 流程图如下:</li>
</ul>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-4c1a4fb4b228c48e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-184ea94ec1b5ce05.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-494e0b26a2724087.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<p><img src="http://upload-images.jianshu.io/upload_images/944365-ab8502405221b5c6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="示意图" title=""></p>


<ul>
<li>下面我将继续深入讲解 <code>Android</code>中的<code>Handler</code>异步通信传递机制的相关知识,如 工作机制流程、源码解析等,有兴趣可以继续关注<a href="https://blog.csdn.net/carson_ho" target="_blank">Carson_Ho的安卓开发笔记</a></li>
</ul>


<hr>


<h1 id="请帮顶-评论点赞因为你的鼓励是我写作的最大动力"><a name="t26"></a>请帮顶 / 评论点赞!因为你的鼓励是我写作的最大动力!</h1>            </div>
            <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/markdown_views-ea0013b516.css">
                </div>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值