博主声明:
转载请在开头附加本文链接及作者信息,并标记为转载。本文由博主 威威喵 原创,请多支持与指教。
直接步入主题,今天我们来讲讲为什么在子线程无法更新 UI,这也是困扰我很久的一个问题,在我初学 Android 的那个时候,特别是在学习 Android 联网那一个章节,需要从网络上获取文本、图片等信息,然后更新到 TextView 或 ImageView 中。但是,我们在请求网络时,通常都是开了一个子线程去获取数据,等到拿到数据,开始的直接 setText(...) 或者 setImage(...) 等等,这个时候呢,它就给你来了这么一个错误:
-
Only the original thread that created a view hierarchy can touch its views.
这段英文的意思是:只要原始创建视图的线程,才能去更新 View。那这个原始的线程,指的就是我们主线程,也就是 UI 线程,我们开启网络的线程,就称为子线程,这两个显然不是同一个线程,所以它就给我们报了这样的异常。
于是呢,我们一般都会把错误日志往搜索引擎里面一粘贴,答案就出来了。但是,这些答案都是告诉你怎么怎么做,怎么该代码才能运行,一般都不会告诉你为什么报这样的错。虽然呢,你在以后会知道不要在子线程中更新 UI 操作,但别人一问你为什么呢,却哑口无言了。
看完这篇文章,你就可以回答:为什么在子线程无法更新 UI 的问题了,下面一起进入源码探索,了解一下为什么吧。
首先呢,我们从最基础的一个 textview.setText("威威喵:https://blog.csdn.net/smile_Running"),这个方法入手,我们来看看这个方法的源码,里面做了什么事情:
//省略代码
if (mLayout != null) {
checkForRelayout();
}
//省略代码
它调用了这样的一个方法,如果布局不为空,它会去调用这个方法里面的关键一句代码
invalidate();
就是上面的方法,不仅 setText()、还有很多如 setXXX() 都会调用 invalidate() 去刷新 View。接下来我们就进入 invalidate() 的源码看看了,它会一直调用到这个方法,如下
void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
boolean fullInvalidate) {
if (mGhostView != null) {
mGhostView.invalidate(true);
return;
}
if (skipInvalidate()) {
return;
}
//省略
// Propagate the damage rectangle to the parent view.
final AttachInfo ai = mAttachInfo;
final ViewParent p = mParent;
if (p != null && ai != null && l < r && t < b) {
final Rect damage = ai.mTmpInvalRect;
damage.set(l, t, r, b);
p.invalidateChild(this, damage);
}
// 省略
}
}
我们看最关键的代码 p.invalidateChild(this, damage) ,调用了 ViewParent 接口的刷新 ChildView,进入代码看看吧,我们一路跟到了 ViewGroup 类下面的这个方法
@Deprecated
@Override
public final void invalidateChild(View child, final Rect dirty) {
//代码省略
View view = null;
if (parent instanceof View) {
view = (View) parent;
}
if (drawAnimation) {
if (view != null) {
view.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
} else if (parent instanceof ViewRootImpl) {
((ViewRootImpl) parent).mIsAnimating = true;
}
}
parent = parent.invalidateChildInParent(location, dirty);
if (view != null) {
// Account for transform on current parent
Matrix m = view.getMatrix();
if (!m.isIdentity()) {
RectF boundingRect = attachInfo.mTmpTransformRect;
boundingRect.set(dirty);
m.mapRect(boundingRect);
dirty.set((int) Math.floor(boundingRect.left),
(int) Math.floor(boundingRect.top),
(int) Math.ceil(boundingRect.right),
(int) Math.ceil(boundingRect.bottom));
}
}
} while (parent != null);
}
}
博主跟到这里的话,发现已经下不去了,好像没看到这里搞了什么东西,也报那个异常的代码。不过呢,我们发现 ViewParent 它是一个接口,而看到它调了这样的方法 parent = parent.invalidateChildInParent(location, dirty),这里的 parent 可能是 View 的实例,也可能是 ViewRootImpl 的实例,而 View 里面显然没有这个方法,所以明显就调了 ViewRootImpl 里面的方法,进入看看吧:
@Override
public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
checkThread();
if (DEBUG_DRAW) Log.v(mTag, "Invalidate child: " + dirty);
if (dirty == null) {
invalidate();
return null;
} else if (dirty.isEmpty() && !mIsAnimating) {
return null;
}
if (mCurScrollY != 0 || mTranslator != null) {
mTempRect.set(dirty);
dirty = mTempRect;
if (mCurScrollY != 0) {
dirty.offset(0, -mCurScrollY);
}
if (mTranslator != null) {
mTranslator.translateRectInAppWindowToScreen(dirty);
}
if (mAttachInfo.mScalingRequired) {
dirty.inset(-1, -1);
}
}
invalidateRectOnScreen(dirty);
return null;
}
好了,目的地已经到了,就是那第一句代码:checkThread() 方法,来看看它干了什么
void checkThread() {
if (mThread != Thread.currentThread()) {
throw new CalledFromWrongThreadException(
"Only the original thread that created a view hierarchy can touch its views.");
}
}
吼吼,你这个小东西藏在这里啊,这就够明显的吧,它是获取到了当前线程的实例,比如我们在子线程中去 setText() 的话,那就不等于 mThread 了,这个 mThread 就是我们的主线程,即 UI 线程。这下总可以回答:为什么在子线程无法更新 UI 这个问题了吧,哈哈。