Activity 创建过程(子线程更新 UI 真的可以吗)

890 阅读8分钟

来看个都遇到过的 Error

相信大家都遇到过这种 Exception 吧

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
只有主线程能更新 UI,但是子线程真的不能更新 UI 吗?我们来看以下代码

片段一: onCreate 中开启子线程来更新 UI


public class StartActivity extends AppCompatActivity {

    private TextView tvName;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);
        tvName = findViewById(R.id.tv_name);

        new Thread(() -> {
            tvName.setText("Hello, WhenSun!");
        }).start();
    }
}

很简单的代码,绑定控件之后直接在子线程更新TextView显示的内容为 Hello, WhenSun!,来猜下是否能运行呢?

你这是在写啥,开始已经说了啊,只能在主线程更新 UI,而现在在子线程运行的,肯定报错啊。真的是这样吗?我们来看运行结果
卧槽? 我看到了什么,它竟然运行成功了,不仅没有报错,还进行绘制了。说好的子线程不能更新 UI 呢?是不是很震惊,那接下来就来解答你的疑惑。

我们都知道 Activity 的生命周期是从 onCreate 开始的,但是在 onCreate 之前做了什么,你有没有考虑过呢,

我之前也写过一篇文章,关于 Activity 创建的,但是现在我去看已经有点蒙了,没办法只能从头再来一次了,这次我尽量说的明白些

1. 从 performLaunchActivity 开始

Activity 创建的最后一步就是执行 performLaunchActivity 方法,那么我们就从这里开始往下走。

    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        Activity activity = null;

//        创建 Activity 实例
        java.lang.ClassLoader cl = appContext.getClassLoader();
        activity = mInstrumentation.newActivity(
                cl, component.getClassName(), r.intent);

//        调用 Activity 的 attach
        activity.attach(appContext, this, getInstrumentation(), r.token,
                r.ident, app, r.intent, r.activityInfo, title, r.parent,
                r.embeddedID, r.lastNonConfigurationInstances, config,
                r.referrer, r.voiceInteractor, window, r.configCallback,
                r.assistToken);

        return activity;
    }

这次我尽量简化代码,只写主要部分,我们可以看到首先创建了一个 Activity 的实例,然后会执行 attach 方法,相信大家对attach 方法应该很数据吧,在fragment中获取context的时候,就是用的它。但是不要以为只有fragmentattach,咱们的 Activity也有 attach 哦。那么 attach 到底做了什么呢?

      final void attach(Context context, ActivityThread aThread,
                Instrumentation instr, IBinder token, int ident,
        Application application, Intent intent, ActivityInfo info,
                CharSequence title, Activity parent, String id,
                NonConfigurationInstances lastNonConfigurationInstances,
                Configuration config, String referrer, IVoiceInteractor voiceInteractor,
                Window window, ActivityConfigCallback activityConfigCallback,
                IBinder assistToken) {
            attachBaseContext(context);
            // 创建 Window
            mWindow = new PhoneWindow(this, window, activityConfigCallback);

            // 通过 context.getSystemService(Context.WINDOW_SERVICE) 获取 WindowManager 进程
            // 绑定 PhoneWindow
            mWindow.setWindowManager(
                    (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
                    mToken, mComponent.flattenToString(),
                    (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
        }

其实 attach 主要干了两件事,创建了 PhoneWindow,并且将 PhoneWindowWindowManager 进行了绑定,获取到了 Window 的服务进程。那么这个 PhoneWindow 又是什么呢?我们来看一张图,了解下咱们写的布局的结构。

其实所有的 layout 都是绘制在 ContentView 中的,而上层已经为咱们设计好了。

Window、Activity、View 关系

或许你会说,什么?他们三还有关系?不就是你上图标出来的那样吗,层级包含关系咯。其实不然,我们知道 Activity 是咱们的活动,而 View 是一个一个的小单元,就是咱们的控件,他们俩结合起来总感觉缺点什么,很难将它们俩连接起来,因此就出现了 Window,它就是一个连接作用,一个缓冲,其实根本没什么卵用。

说了那么多,回到我们的正题,在 attach 中创建了 PhoneWindow 并获取到 Window 的服务进程之后,这样 Activity 就做好管理界面的准备了。 接下来我们回到 performLaunchActivity 继续看咱们剩下的逻辑了

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    if (r.isPersistable()) {
        mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
    } else {
        mInstrumentation.callActivityOnCreate(activity, r.state);
    }
    return activity;
}

那么 callActivityOnCreate 中又做了什么呢

/**
 * Perform calling of an activity's {@link Activity#onCreate}
 * method.  The default implementation simply calls through to that method.
 *
 * @param activity The activity being created.
 * @param icicle The previously frozen state (or null) to pass through to onCreate().
 */
public void callActivityOnCreate(Activity activity, Bundle icicle) {
    prePerformCreate(activity);
    activity.performCreate(icicle);
    postPerformCreate(activity);
}

Perform calling of an activity's {@link Activity#onCreate},看这里,调用了 ActivityonCreate方法,从这里开始就进入咱们熟悉的生命周期了。

DecorView 的创建

DecorView 的创建其实是在 setContentView 中完成的,来追踪下 setContentView 的源码

public void setContentView(View v) {
    ensureSubDecor();
    ViewGroup contentParent = mSubDecor.findViewById(android.R.id.content);
    contentParent.removeAllViews();
    contentParent.addView(v);
    mAppCompatWindowCallback.getWrapped().onContentChanged();
}

进入 ensureSubDecor 方法

private void ensureSubDecor() {
    if (!mSubDecorInstalled) {
        mSubDecor = createSubDecor();
    }
}

通过调用 createSubDecor 来创建的 DecorView,但是这时候的 DecorView 并没有和 Activity 产生联系,这时候你或许就应该明白了,为什么在 onCreate 中使用子线程更新 UI,可以运行成功的原因了。那么 DecorViewActivity 是在哪里产生联系的呢?

片段二:onResume 中开启子线程来更新 UI

public class StartActivity extends AppCompatActivity {

    private TextView tvName;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);
        tvName = findViewById(R.id.tv_name);
    }


    @Override
    protected void onResume() {
        super.onResume();
        new Thread(() -> {
            tvName.setText("Hello, WhenSun!");
        }).start();
    }
}

这次咱们不在 onCreate 中更新 UI 了,咱们在 onResume 中更新 UI,那么他能更新成功吗?

肯定不行啊,这次该对了吧,都绘制 UI 了,在子线程更新 UI 肯定也不行了。但是我要告诉你的是,这样也是可以运行成功的。

2. handleResumeActivity 再出发

先问个问题: Activity 绘制界面是从 哪个生命周期开始的?

答案:onResume

为什么这么说呢,我们来看 handleResumeActivity 中具体做了什么

public void handleResumeActivity(IBinder token, boolean finalStateRequest,
                                 boolean isForward,
                                 String reason) {

    final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);

    final Activity a = r.activity;
    
    if (r.window == null && !a.mFinished && willBeVisible) {
        r.window = r.activity.getWindow();
        View decor = r.window.getDecorView();
        decor.setVisibility(View.INVISIBLE);
        ViewManager wm = a.getWindowManager();
        WindowManager.LayoutParams l = r.window.getAttributes();
        a.mDecor = decor;
    }
}

这段代码中我们能看出我们获取了 DecorViewViewManager 等,其他的我就不过多解释了,这里主要说一个 ActivityClientRecord 类,对于它我们需要先了解另外一个类,那就是 ActivityRecord

ActivityRecord

ActivityRecordActivityActivityManagerServiceActivityStack 中的数据结构,AMS 通过 ActivityRecord 管理 Activity 的生命周期和状态.

ActivityClientRecord

ActivityClientRecord 则是应用进程对应 ActivityRecord 的数据结构。每一个没有 destroyActivityActivityThread 中都有一个 ActivityClientRecord

从上述代码中,我们发现,着这里创建了 DecorViewViewManager 等,并把 DecorView 赋值给了 ActivityDecorView,还记得上边那个层级结构图吗?现在已经出现了三个了,分别是 ActivityWindow(PhoneWindow)DecorView。那么接下来就开始绘制 UI 的过程了。

1)绘制 UI 过程

我们继续看 handleResumeActivity 的源码

public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
                                 String reason) {
    
    if (!r.activity.mFinished && willBeVisible && r.activity.mDecor != null && !r.hideForNow) {
        WindowManager.LayoutParams l = r.window.getAttributes();
        if ((l.softInputMode
                & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
                != forwardBit) {
            if (r.activity.mVisibleFromClient) {
                ViewManager wm = a.getWindowManager();
                View decor = r.window.getDecorView();
                wm.updateViewLayout(decor, l);
            }
        }
    }
}

我们一路追随 updateViewLayout 的源码,我这里给出具体的调用流程。

ViewManager.updateViewLayout

ViewManager 是一个借口,而 ViewManager 的实现类是 WindowManagerImpl,所以我们需要看 WindowManagerImpl.updateViewLayout 的源码

@Override
public void updateViewLayout(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
    applyDefaultToken(params);
    mGlobal.updateViewLayout(view, params);
}
WindowManagerGlobal.updateViewLayout

这里我们只需要关注 setLayoutParams 方法

public void updateViewLayout(View view, ViewGroup.LayoutParams params) {
    synchronized (mLock) {
        int index = findViewLocked(view, true);
        ViewRootImpl root = mRoots.get(index);
        mParams.remove(index);
        mParams.add(index, wparams);
        root.setLayoutParams(wparams, false);
    }
}
ViewRootImpl.setLayoutParams
void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
    synchronized (this) {
        if (newView) {
            mSoftInputMode = attrs.softInputMode;
            requestLayout();
        }

        scheduleTraversals();
    }
}
ViewRootImpl.requestLayout
public void requestLayout() {
    if (!mHandlingLayoutInLayoutRequest) {
        checkThread();
        mLayoutRequested = true;
        scheduleTraversals();
    }
}
ViewRootImpl.scheduleTraversals
void scheduleTraversals() {
    if (!mTraversalScheduled) {
        mTraversalScheduled = true;
        mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
        mChoreographer.postCallback(
                Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
        if (!mUnbufferedInputDispatch) {
            scheduleConsumeBatchedInput();
        }
        notifyRendererOfFramePending();
        pokeDrawLockIfNeeded();
    }
}

从这里开始,就开启了 UI 的绘制流程了,为什么这么说呢?在 scheduleTraversals 方法中,发现调用了 mTraversalRunnable,那么 mTraversalRunnable 是什么呢?

final TraversalRunnable mTraversalRunnable = new TraversalRunnable();

final class TraversalRunnable implements Runnable {
    @Override
    public void run() {
        doTraversal();
    }
}
ViewRootImpl.doTraversal
void doTraversal() {
    if (mTraversalScheduled) {
        performTraversals();
    }
}
ViewRootImpl.performTraversals

到这里终于进入正题了,我们来看下这个方法的代码,代码非常长,我这里只粘贴三个关键的方法

private void performTraversals() {
    if (mFirst || windowShouldResize || insetsChanged ||
            viewVisibilityChanged || params != null || mForceNextWindowRelayout) {

        if (!mStopped || mReportNextDraw) {
            boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
                    (relayoutResult&WindowManagerGlobal.RELAYOUT_RES_IN_TOUCH_MODE) != 0);
            if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
                    || mHeight != host.getMeasuredHeight() || contentInsetsChanged ||
                    updatedConfiguration) {
                int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
                int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);

                performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);

                if (measureAgain) {
                    performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
                }

            }
        }
    } else {
        maybeHandleWindowMove(frame);
    }

    final boolean didLayout = layoutRequested && (!mStopped || mReportNextDraw);
    boolean triggerGlobalLayoutListener = didLayout
            || mAttachInfo.mRecomputeGlobalAttributes;
    if (didLayout) {
        performLayout(lp, mWidth, mHeight);
    }

    if (!cancelDraw) {
        performDraw();
    } 
}

咱们只看三个关键的方法,performMeasureperformLayoutperformDraw,到了这里,或许已经有人猜出来这三个方法的作用了,这里我只贴出一个方法的代码,另外两个方法都是类似的

private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
    if (mView == null) {
        return;
    }
    Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
    try {
        mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    } finally {
        Trace.traceEnd(Trace.TRACE_TAG_VIEW);
    }
}

你发现了什么?对,就是 Viewmeasure 方法,我们知道 View 的绘制需要经历三个阶段,分别是 easure(测量)Layout(布局)draw(绘制)这三个阶段,而这三个阶段就是这这里执行的了。

那么为什么在 onResume 中使用子线程更新 UI 不会报错呢?这个还是要从 handleResumeActivity 开始说了。

苦命的 `handleResumeActivity`,默默承受了那么多,哈哈哈。来看这段代码吧
public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
                                 String reason) {

    final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);

    if (r.window == null && !a.mFinished && willBeVisible) {
        r.window = r.activity.getWindow();
        View decor = r.window.getDecorView();
        decor.setVisibility(View.INVISIBLE);
        ViewManager wm = a.getWindowManager();
        WindowManager.LayoutParams l = r.window.getAttributes();
        a.mDecor = decor;
        l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
        l.softInputMode |= forwardBit;
    } else if (!willBeVisible) {
        if (localLOGV) Slog.v(TAG, "Launch " + r + " mStartedActivity set");
        r.hideForNow = true;
    }
}

调用了 ActivityThread.performResumeActivity 的方法

public ActivityClientRecord performResumeActivity(IBinder token, boolean finalStateRequest,
                                                 String reason) {
   final ActivityClientRecord r = mActivities.get(token);
   try {
       r.activity.performResume(r.startsNotResumed, reason);
   } catch (Exception e) {
       
   }
   return r;
}

在这里调用了 Activity.performResume,继续往下看

final void performResume(boolean followedByPause, String reason) {
    dispatchActivityPreResumed();
    mInstrumentation.callActivityOnResume(this);

}

再往下走,就能发现一个很熟悉的方法了,来看下 Instrumentation.callActivityOnResume 方法

public void callActivityOnResume(Activity activity) {
    activity.mResumed = true;
    activity.onResume();

}

看到没,Activity.onResume 就是在这里调用的,那么为什么在子线程更新 UI 不会报错呢,我们还是要回到 handleResumeActivity 来看下

public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
                               String reason) {

  final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);

  if (r.window == null && !a.mFinished && willBeVisible) {
      r.window = r.activity.getWindow();
      View decor = r.window.getDecorView();
      decor.setVisibility(View.INVISIBLE);
      ViewManager wm = a.getWindowManager();
      WindowManager.LayoutParams l = r.window.getAttributes();
      a.mDecor = decor;
      l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
      l.softInputMode |= forwardBit;
  } else if (!willBeVisible) {
      if (localLOGV) Slog.v(TAG, "Launch " + r + " mStartedActivity set");
      r.hideForNow = true;
  }
}

发现没,我们是在走完了 onResume 之后,Activity 才和 DecorView 产生联系的,这就说明,只要在 ActivityDecorView 产生联系之前,无论我们在子线程做什么,都是合法的,简直是为所欲为啊。

好了,到这里该分析的也分析完了。我们来看下边两段代码

片段三:使用 Thread.sleep() 那还能更新 UI 吗?

1). onCreate 中使用 Thread.sleep() 来更新 UI

public class StartActivity extends AppCompatActivity {

    private TextView tvName;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);
        tvName = findViewById(R.id.tv_name);
        new Thread(() -> {
            try {
                Thread.sleep(1000);
                Log.i("StartActivity", "我开始绘制 UI 了");
                tvName.setText("Hello, WhenSun!");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

2). onResume 中使用 Thread.sleep() 来更新 UI

public class StartActivity extends AppCompatActivity {

    private TextView tvName;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);
        tvName = findViewById(R.id.tv_name);
    }


    @Override
    protected void onResume() {
        super.onResume();
        new Thread(() -> {
            try {
                Thread.sleep(1000);
                Log.i("StartActivity", "我开始绘制 UI 了");
                tvName.setText("Hello, WhenSun!");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

他们会更新 UI 成功吗?