什么?你跟我说只能在子线程更新View!

2,620 阅读3分钟

背景

今天做了一个功能,注册一个监听wifi连接的广播,连接后显示一个悬浮Textview,并在外面设置一个Button,用户点击后可以传递一些内容给这个悬浮Textview来显示,一切都是那么顺利,可等到运行的时候出错了:

 android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
                      at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6891)
                      at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:1083)
                      at android.view.ViewGroup.invalidateChild(ViewGroup.java:5205)
                      at android.view.View.invalidateInternal(View.java:13656)
                      at android.view.View.invalidate(View.java:13620)
                      at android.view.View.invalidate(View.java:13604)
                      at android.widget.TextView.checkForRelayout(TextView.java:7347)
                      at android.widget.TextView.setText(TextView.java:4480)
                      at android.widget.TextView.setText(TextView.java:4337)
                      at android.widget.TextView.setText(TextView.java:4312)
        at com.renny.demo.view.activity.HomeActivity$onCreate$1.onClick(HomeActivity.kt:57)

HomeActivity是我发送数据的地方。

这个错误在我刚入门Android的时候遇到过几次,现在已经很熟悉了,于是我花了1.25秒就想出了了问题所在,我肯定是在子线程更新view了。嗯,虽然看了下代码没看出来这个子线程是哪个,但机智的我还是不管三七二十一,直接用handler抛到了主线程:

 new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                mTextviw.setText("hello");
            }
        });

无奈,问题依旧,看来事情并不简单。

分析

根据错误信息里的提示,先来介绍下ViewRootImpl,当它创建的时候,创建它的Thread会赋值给mThread成员变量。

 public ViewRootImpl(Context context, Display display) {
        mContext = context;
        mWindowSession = WindowManagerGlobal.getWindowSession();
        mDisplay = display;
        mBasePackageName = context.getBasePackageName();
        mThread = Thread.currentThread();

当我们给TextView设置文本内容的时候,会判断mLayout是否为空,如果不会空,则会调用checkForRelayout()方法。

private void setText(CharSequence text, BufferType type,boolean notifyBefore, int oldlen) {
    // ......
    if (mLayout != null) {
        checkForRelayout();
    }
   // ......
}

这个mLayout先不用管,在第一次onMeasure的时候会赋值,现在Textview已经先显示,所以此时不为空。随后在checkForRelayout()中会调用

private void checkForRelayout() {
    if (...) {
        requestLayout();
        invalidate();
    } else {
        nullLayouts();
        requestLayout();
        invalidate();
    }
}

然后当View(或者是ViewGroup)调用invalidate()方法的时候,会调用父View的invalidateChild(View child, final Rect dirty),这里面有一个do while循环,每循环一次会调用parent = parent.invalidateChildInParent(location, dirty),直到到最外面的View节点。

当遍历到根节点,也就是ViewRoot,调用ViewRoot的invalidateChildInParent方法,实际是调用ViewRoot的实现类ViewRootImpl身上的invalidateChildInParent方法。 当ViewGroup中的invalidateChild(View child, final Rect dirty)方法循环到最外层的时候,这个mParent就是ViewRootImpl。 当调用到ViewRootImpl的invalidateChildInParent(int[] location, Rect dirty)方法的时候会去检测线程,也就是checkThread()。

checkThread()里面会判断当前线程是不是创建ViewRootImpl的那个线程,如果不是的就抛出异常。

void checkThread() {
    if (mThread != Thread.currentThread()) {
        throw new CalledFromWrongThreadException(
                "Only the original thread that created a view hierarchy can touch its views.");
    }
}

所以只要看到ViewRootImpl创建的线程是不是主线程就行了。添加悬浮窗的过程中会创建ViewRootImpl

        val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
            val lp = WindowManager.LayoutParams().apply {
                type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT or WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY
                gravity = Gravity.LEFT or Gravity.TOP
            }
            textView = TextView(applicationContext)
            windowManager.addView(textView, lp)

在addView方法中创建:

 public void addView(View view, LayoutParams params) {
        //...
        root = new ViewRootImpl(view.getContext(), display);
        view.setLayoutParams(wparams);
        this.mViews.add(view);
        this.mRoots.add(root);
        this.mParams.add(wparams);
    }

最后加了下打印线程信息,居然发现创建这个悬浮窗的线程不是主线程。。。就是因为注册广播的时候:

 mContext.registerReceiver(mReceiver, mFilter, null, mWorkHandler)

所以onReceive会在我指定的线程回调。

结论

view只能在UI线程更新没错,但UI线程不一定等于主线程,而是创建ViewRootImpl所在的线程,更准确的说是windowManager添加rootview所在的线程,当在子线程添加View时,这个子线程就是这个view和子view(如果有)所在的UI线程,我们也就不能在另外的线程更新view了,包括主线程。最后,对于这个UI线程要求就是一定要开启loop循环:

        thread {
            Looper.prepare()
                   val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
            val lp = WindowManager.LayoutParams().apply {
                type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT or WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY
                gravity = Gravity.LEFT or Gravity.TOP
            }
            textView = TextView(applicationContext)
            windowManager.addView(textView, lp)
            Looper.loop()
        }

参考

Only the original thread that created a view hierarchy can touch its views. 是怎么产生的