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

背景

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

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是我发送数据的地方。java

这个错误在我刚入门Android的时候遇到过几回,如今已经很熟悉了,因而我花了1.25秒就想出了了问题所在,我确定是在子线程更新view了。嗯,虽然看了下代码没看出来这个子线程是哪一个,但机智的我仍是无论三七二十一,直接用handler抛到了主线程:android

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

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

分析

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

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

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

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

复制代码

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

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节点。post

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

checkThread()里面会判断当前线程是否是建立ViewRootImpl的那个线程,若是不是的就抛出异常。this

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. 是怎么产生的

相关文章
相关标签/搜索