Android子线程什么时候能更新UI测试及原因探索

写了一个最简单的子线程setText,本来以为会出错,但是实际上可以正常运行。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textView = findViewById(R.id.textview);
    changeText();

}

private void changeText() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            textView.setText("aaa");
        }
    }).start();
}

  为了测试,我又将changeText方法移动到onStart、onResume、onPause、onStop,onRestart、onDestroy中运行,得出一个结果。

  结论:只有在Activity初始化到onResume()的过程中,可以成功的setText。也就是说当Activity执行onCreate() -> onStart() -> onResume()这一个过程的时候,在这三个方法中changeText都不会报错。

  而其他情况下均会报错,如果我将changeText放在onStart()下,那么,一开始打开Activity的时候不会报错,而当我切到桌面,再切回到app的时候,执行了onRestart() -> onStart() -> onResume()的过程中,调用changeText就报错了。

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
    at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:8191)
    at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:1420)
    at android.view.View.requestLayout(View.java:24454)
    at android.view.View.requestLayout(View.java:24454)
    at android.view.View.requestLayout(View.java:24454)
    at android.view.View.requestLayout(View.java:24454)
    at android.view.View.requestLayout(View.java:24454)
    at android.view.View.requestLayout(View.java:24454)
    at android.view.View.requestLayout(View.java:24454)
    at android.widget.TextView.checkForRelayout(TextView.java:9681)
    at android.widget.TextView.setText(TextView.java:6269)
    at android.widget.TextView.setText(TextView.java:6097)
    at android.widget.TextView.setText(TextView.java:6049)
    at com.example.handlerdemo.MainActivity$2.run(MainActivity.java:37)
    at java.lang.Thread.run(Thread.java:919)

在setText的方法中,有一个checkLayout的方法,这个方法主要是检查textview是否需要一个新的layout布局。

@UnsupportedAppUsage
private void setText(CharSequence text, BufferType type,
                     boolean notifyBefore, int oldlen) {

	......

    if (mLayout != null) {
        checkForRelayout();
    }

	......

}

这个checkForRelayout()方法中,无论如何都会调用一个requestLayout(),而这个requestLayout()就是报错的方法了。

/**
 * Check whether entirely new text requires a new view layout
 * or merely a new text layout.
 */
@UnsupportedAppUsage
private void checkForRelayout() {

    if ((mLayoutParams.width != LayoutParams.WRAP_CONTENT
            || (mMaxWidthMode == mMinWidthMode && mMaxWidth == mMinWidth))
      
      	......

        requestLayout();
        invalidate();
    } else {

        nullLayouts();
        requestLayout();
        invalidate();
    }
}

requestLayout()不是TextView的方法,而是它的父类View的方法。


protected ViewParent mParent;

/**
 * Call this when something has changed which has invalidated the
 * layout of this view. This will schedule a layout pass of the view
 * tree. This should not be called while the view hierarchy is currently in a layout
 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
 * end of the current layout pass (and then layout will run again) or after the current
 * frame is drawn and the next layout occurs.
 *
 * <p>Subclasses which override this method should call the superclass method to
 * handle possible request-during-layout errors correctly.</p>
 */
@CallSuper
public void requestLayout() {
    if (mMeasureCache != null) mMeasureCache.clear();

    if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
        // Only trigger request-during-layout logic if this is the view requesting it,
        // not the views in its parent hierarchy
        ViewRootImpl viewRoot = getViewRootImpl();
        if (viewRoot != null && viewRoot.isInLayout()) {
            if (!viewRoot.requestLayoutDuringLayout(this)) {
                return;
            }
        }
        mAttachInfo.mViewRequestingLayout = this;
    }

    mPrivateFlags |= PFLAG_FORCE_LAYOUT;
    mPrivateFlags |= PFLAG_INVALIDATED;

    if (mParent != null && !mParent.isLayoutRequested()) {
        mParent.requestLayout();
    }
    if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
        mAttachInfo.mViewRequestingLayout = null;
    }
}

在这个方法中,有一个mParent,requestLayout(),这个mParent是一个ViewParent的类,但是ViewParent是一个interface,调查来源后发现,是ViewRootImpl这个类implements ViewParent,然后再赋值给mParent,再查看ViewRootlmpl的requestLayout()方法。

@Override
public void requestLayout() {
    if (!mHandlingLayoutInLayoutRequest) {
        checkThread();
        mLayoutRequested = true;
        scheduleTraversals();
    }
}


......


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

这回算是找到了报错的原因,在这个方法中如果线程不等就会报错。

用调试再监控了一下mThread和mHandlingLayoutInLayoutRequest两个变量,mThread会在初始化的时候指向主线程,而mHandlingLayoutInLayoutRequest默认是false,在这期间内也一直没有更改过值。

那么为什么在初始化的时候不会报错呢?再次回到setText这个方法。

    if (mLayout != null) {
        checkForRelayout();
    }

然后对setText方法再次调试得到。
在这里插入图片描述
也就是说,在初始化Activity的过程中,mLayout还是为空,这个时候就不需要做线程的判断,checkForRelayout()并不执行,自然就不会报线程不同的错误。

那么mLayout到底什么时候不为空?在onResume之后。

参考材料

子线程为什么可以更新UI操作,那是因为 - CSDN
https://blog.csdn.net/qq_21937107/article/details/79998194

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值