<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by 田侑生 on Medium]]></title>
        <description><![CDATA[Stories by 田侑生 on Medium]]></description>
        <link>https://medium.com/@shy_seashell_gnat_729?source=rss-87d7976cb129------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*RBkfxwSCs38lRYt6</url>
            <title>Stories by 田侑生 on Medium</title>
            <link>https://medium.com/@shy_seashell_gnat_729?source=rss-87d7976cb129------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 11:41:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shy_seashell_gnat_729/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[子執行緒一定不能更新UI嗎？(Android)]]></title>
            <link>https://medium.com/twjoin/%E5%AD%90%E5%9F%B7%E8%A1%8C%E7%B7%92%E4%B8%80%E5%AE%9A%E4%B8%8D%E8%83%BD%E6%9B%B4%E6%96%B0ui%E5%97%8E-android-f785ca9f3e27?source=rss-87d7976cb129------2</link>
            <guid isPermaLink="false">https://medium.com/p/f785ca9f3e27</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[technical-notes]]></category>
            <category><![CDATA[哲煜科技]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[軟體開發]]></category>
            <dc:creator><![CDATA[田侑生]]></dc:creator>
            <pubDate>Thu, 28 Apr 2022 12:51:33 GMT</pubDate>
            <atom:updated>2025-07-18T03:27:54.537Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>前言</blockquote><p>大家都有面試的經驗，過程中曾經被問到執行序的問題，面試官問你：「確定UI真的一定不能在子執行緒更新嗎？為什麼？」，當時的回答感覺不夠深入。事後激起了我對這議題的興趣，再更深入的爬文研究，整理一些資訊分享給大家。</p><p>這個議題相信很多人知道，在這邊做兩方面的整理：</p><pre><strong>1. 規則方面</strong></pre><pre><strong>2. 底層Code阻擋機制方面</strong></pre><p>開發過程中我們不會在子執行緒裡做更新UI的動作，整理三個原因：</p><pre><strong>1. 為了分工機制更明確以及提升效率，有所謂單執行緒原則<br>   - 不阻塞主執行緒，導致畫面凍結<br>   - 不要在主執行緒之外訪問Android UI toolkit</strong></pre><pre><strong>2. 在非子執行緒中重新整理UI的時候，可能因非同步特性造成多個UI無法同步，導致執行緒             <br>  不安全</strong></pre><pre><strong>3. 最重要的會導致crash</strong></pre><p>但是真的一定不行在子執行緒進行UI更新嗎？</p><p>上網查詢後發現有篇帶著你看底層的文章推薦給大家，很適合和我一樣的小菜雞做底層查看練習<a href="https://www.796t.com/content/1550545384.html">https://www.796t.com/content/1550545384.html</a></p><p>雖說官方有防止在 UI 在子執行緒，但我們可以看看底層是怎麼運作的。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_I59GZmxCvfdVuzyZXzWeg.png" /><figcaption>附上ViewRoot、Window、Activity、DecorView的關係圖可以邊對邊看</figcaption></figure><p>文章中提供了兩個專案，一個是在 Activity onCreate 的地方，進行 UI 在子執行緒運行，可以成功，但在點擊監聽下會報錯</p><p>UI 更新在子執行緒執行 crash 時，會跑出以下資訊：</p><pre>android.view.<strong>ViewRootImpl</strong>$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.</pre><pre>at android.view.<strong>ViewRootImpl</strong>.checkThread(ViewRootImpl.java:9450)</pre><pre>at android.view.<strong>ViewRootImpl</strong>.invalidateChildInParent(ViewRootImpl.java:1871)</pre><pre>at android.view.<strong>ViewRootImpl</strong>.invalidateChild(ViewRootImpl.java:1866)</pre><p>我們可以看到一個 ViewRootImpl 的類別，丟出</p><p>CalledFromWrongThreadException</p><p>進入 ViewRootImpl 會清楚的看到，checkThread() 做 thread 的判斷</p><pre>public final class ViewRootImpl implements ViewParent... {</pre><pre>   void checkThread() {</pre><pre>      if (mThread != Thread.currentThread()) {</pre><pre>         throw new CalledFromWrongThreadException(</pre><pre>         “Only the original thread that created a view hierarchy can<br>          touch its views.”);</pre><pre>      }</pre><pre>   }</pre><pre>}</pre><p>問題來了，怎麼知道 mThread 是主執行緒為什麼在 onCreate 裡子執行緒更新UI就不報錯，而點選事件裡做子執行緒更新UI就報錯了呢？</p><p>首先 UI 更新跟 View 有關，因為 View 是所有畫面元件的父類別，View 在更新的時候會呼叫invalidate()</p><p>用 command+F 找到 invalidate()</p><p>點擊 invalidate()</p><pre>public final class ViewRootImpl implements ViewParent... {<br>   public void invalidate() {</pre><pre>      <strong>invalidate(true);</strong> //刷新UI畫面</pre><pre>   }</pre><pre>}</pre><p>再點 invalidateInternal()</p><pre>public final class ViewRootImpl implements ViewParent... {<br>   public void invalidate(boolean invalidateCache) {</pre><pre>      <strong>invalidateInternal(0, 0, mRight — mLeft, mBottom — mTop,<br>      invalidateCache, true);</strong></pre><pre>   }</pre><pre>}</pre><p>點擊 p.invalidateChild(this, damage)</p><pre>public final class ViewRootImpl implements ViewParent... {</pre><pre>   void invalidateInternal(int l, int t, int r, int b, boolean <br>   invalidateCache, boolean fullInvalidate) {</pre><pre>   ......</pre><pre>      final AttachInfo ai = mAttachInfo;</pre><pre>      final ViewParent p = mParent;</pre><pre>      if (p != null &amp;&amp; ai != null &amp;&amp; l &lt; r &amp;&amp; t &lt; b) {</pre><pre>      final Rect damage = ai.mTmpInvalRect;</pre><pre>      damage.set(l, t, r, b);</pre><pre>      <strong>p.invalidateChild(this, damage);</strong></pre><pre>      }</pre><pre>   ......</pre><pre>   }</pre><pre>}</pre><p>會看到 p.invalidateChild(this, damage) 這個方法宣告在 ViewParent 裡面的</p><pre>public interface ViewParent {</pre><pre><strong>public void invalidateChild(View child, Rect r);</strong></pre><pre>}</pre><p>我們可以找到 invalidateChild 可以在 ViewGroup 實現，看到parent.invalidateChildInParent(location, dirty) 再點進去看看</p><pre>public abstract class ViewGroup extends View implements ViewParent, ViewManager {<br>public final void invalidateChild(View child, final Rect dirty) {</pre><pre>......</pre><pre>parent = <strong>parent.invalidateChildInParent(location, dirty);</strong></pre><pre>......</pre><pre>}</pre><pre>}</pre><p>發現 invalidateChildInParent 一樣是宣告在 ViewParent 裡面</p><pre>public interface ViewParent {</pre><pre><strong>public ViewParent invalidateChildInParent(int[] location, Rect r);</strong></pre><pre>}</pre><p>invalidateChildInParent()被ViewRootImpl 實現，並且可以在裡面看到checkThread() 被呼叫，原來更新UI時， checkThread() 會在這個時候被呼叫，我們就會知道原來更新 UI 的時候，會在這邊檢查 thread ，那問題來了， checkThread() 裡的 mThread 是什麼時候被賦予值得呢？</p><pre>public final class ViewRootImpl implements ViewParent... {</pre><pre>   @Override</pre><pre>   public ViewParent invalidateChildInParent(int[] location, Rect    <br>   dirty) {</pre><pre>   <strong>checkThread();</strong></pre><pre>   ......</pre><pre>   }</pre><pre>}</pre><p>回到ViewRootImpl用command+F找mThread = 會看到mThread在這裡被賦值，可是我們還是不能說明mThread就一定是主執行緒。</p><pre>public final class ViewRootImpl implements ViewParent... {</pre><pre>   final Thread mThread;</pre><pre>   public ViewRootImpl(@UiContext Context context, Display display,    <br>   IWindowSession session,</pre><pre>      boolean useSfChoreographer) {</pre><pre>      ......</pre><pre>        <strong>mThread = Thread.currentThread();</strong> //mThread在這裡被賦值</pre><pre>     }</pre><pre>}</pre><p>到這裡回想為什麼在 onCreate 裡子執行緒更新UI就不報錯但在點擊監聽會報錯的問題， checkThread 這個方法執行的時間是不是比 Activity 的onCreate() 方法執行的要晚呢？</p><p>那我們只有看一看 Activity 的生命週期在哪裡開始被呼叫。</p><p>在app啟動時，系統會呼叫 ActivityThread的main 方法，並且把ActivityThread 作為我們 app 的主執行緒，在 ActivityThread 中，找到handleLaunchActivity() 裡頭會看到 performLaunchActivity() 和handleResumeActivity()：</p><pre>public final class ActivityThread extends ...{<br>   private void handleLaunchActivity(ActivityClientRecord r, Intent    <br>   customIntent) {</pre><pre>      ......</pre><pre>      Activity a = <strong>performLaunchActivity(r, customIntent);</strong></pre><pre>      if (a != null) {</pre><pre>      r.createdConfig = new Configuration(mConfiguration);</pre><pre>      Bundle oldState = r.state;</pre><pre>      <strong>handleResumeActivity(r.token, false, r.isForward,</strong></pre><pre><strong>      !r.activity.mFinished &amp;&amp; !r.startsNotResumed);</strong></pre><pre>      ......</pre><pre>   }</pre><pre>}</pre><p>先看 performLaunchActivity() 這個方法， callActivityOnCreate() 會呼叫Activity 的 onCreate</p><pre>public final class ActivityThread ...{<br>   private Activity performLaunchActivity(ActivityClientRecord r,    <br>   Intent customIntent) {</pre><pre>   ......</pre><pre>      if (r.isPersistable()) {</pre><pre>         mInstrumentation.<strong>callActivityOnCreate</strong>(activity, r.state,       <br>         r.persistentState);</pre><pre>      } else {</pre><pre>         mInstrumentation.<strong>callActivityOnCreate</strong>(activity, r.state);</pre><pre>      }</pre><pre>   ......</pre><pre>   }</pre><pre>}</pre><p>再看 handleResumeActivity() 方法</p><pre>public final class ActivityThread ...{</pre><pre>   final void handleResumeActivity(IBinder token,</pre><pre>   boolean clearHide, boolean isForward, boolean reallyResume) {</pre><pre>   ......</pre><pre>      ActivityClientRecord r = performResumeActivity(token,    <br>      clearHide);//這裡是activity的onResume被呼叫的入口</pre><pre>   ......</pre><pre>      if (r.window == null &amp;&amp; !a.mFinished &amp;&amp; willBeVisible) {</pre><pre>   ......</pre><pre>         if (a.mVisibleFromClient) {</pre><pre>         a.mWindowAdded = true;</pre><pre><strong>         wm.addView(decor, l);</strong>//這裡是將View和window關聯的地方</pre><pre>         }</pre><pre>      } else if (!willBeVisible) {</pre><pre>         if (localLOGV) Slog.v(</pre><pre>         TAG, “Launch “ + r + “ mStartedActivity set”);</pre><pre>         r.hideForNow = true;</pre><pre>         }</pre><pre>   ......</pre><pre>      }</pre><pre>}</pre><p>這裡我們找到了 View 和 Window 關聯的地方 wm.addView(decor, l) ，由於WindowManager 是個繼承 ViewManager 的介面</p><pre>public interface ViewManager{</pre><pre>   public void addView(View view, ViewGroup.LayoutParams params);</pre><pre>}</pre><pre>----------------------WindowManager 繼承 ViewManager-----------------</pre><pre>public interface <strong>WindowManager</strong> extends ViewManager {</pre><pre>}</pre><p>我們找到 addView 在 WindowManagerImpl 裡被實現，再點擊mGlobal.addView(view, params, mDisplay, mParentWindow)</p><pre>public class WindowManagerImpl implements WindowManager {<br>   ......</pre><pre>   @Override<br>   public void addView(@NonNull View view, @NonNull    <br>   ViewGroup.LayoutParams params) {</pre><pre>      applyDefaultToken(params);</pre><pre>      mGlobal.addView(view, params, mDisplay, mParentWindow);</pre><pre>   }</pre><pre>   ......</pre><pre>}</pre><p>會發現 ViewRootImpl 物件在這裡被建立，證明 ViewRootImpl 物件是在activity 的 onResume 之後建立，ViewRootImpl 中的 mThread 變數是在ViewRootImpl 被時力後賦值的，所以在 onCreate 更新 UI ，不會報錯，而我們新增點選事件以後，由於 activity 已肉眼可見並且處於 Resume 狀態，這時 ViewRootImpl 中的 mThread 已經是主執行緒，所以我們在子執行緒中更新 UI 就會報錯。</p><pre>public final class WindowManagerGlobal {</pre><pre>   public void addView(View view, ViewGroup.LayoutParams params,</pre><pre>   Display display, Window parentWindow) {</pre><pre>      ......</pre><pre>      ViewRootImpl root;</pre><pre>      View panelParentView = null;</pre><pre>      ......</pre><pre>      root = new ViewRootImpl(view.getContext(), display); //在這裡被實例</pre><pre>      view.setLayoutParams(wparams);</pre><pre>      mViews.add(view);</pre><pre>      mRoots.add(root);</pre><pre>      mParams.add(wparams);</pre><pre>      ......</pre><pre>   }</pre><pre>}</pre><blockquote>結論：</blockquote><p>我們可以了解在屬於所有 View 的根(<strong>ViewRootImpl</strong>，但 ViewRootImpl 不是View，只是實現了 ViewParent 接口)還沒被建立時，都可以在子執行緒底下進行，不過多個子執行緒非同步的特性，可能會造成多個 UI 顯示不同步，不推薦將 UI 更新放在子執行緒執行。</p><p>參考連結，推薦大家進去裡面看看：<a href="https://www.796t.com/content/1550545384.html">https://www.796t.com/content/1550545384.html</a></p><blockquote>延伸閱讀</blockquote><p><a href="https://blog.twjoin.com/%E5%BE%9Eandroid-mvvm%E9%96%8B%E7%99%BC%E6%9E%B6%E6%A7%8B%E6%B7%BA%E8%AB%87usecase-e68eb5976946">從Android MVVM開發架構淺談UseCase（上）</a></p><p><strong>如果喜歡以上分享內容…</strong></p><p>歡迎留言或分享出去，或是按下拍手，你們的鼓勵都會成為我們分享的動力</p><p>也歡迎按讚並關注 <a href="https://www.facebook.com/TWJOIN">哲煜科技的粉絲專頁</a> 喔 ! 感謝閱讀到最後的你。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f785ca9f3e27" width="1" height="1" alt=""><hr><p><a href="https://medium.com/twjoin/%E5%AD%90%E5%9F%B7%E8%A1%8C%E7%B7%92%E4%B8%80%E5%AE%9A%E4%B8%8D%E8%83%BD%E6%9B%B4%E6%96%B0ui%E5%97%8E-android-f785ca9f3e27">子執行緒一定不能更新UI嗎？(Android)</a> was originally published in <a href="https://medium.com/twjoin">JoinX 哲煜科技</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>