我是android新手,看了博客,很多人说不能在其他线程更新view,必须在ui线程更新,请问是什么原因,为什么我们做的时候会报异常?任何人都可以给出原因
在过去的几周里,我阅读了有关如何将视图添加到窗口的源代码。
当我们调用setContentView
set view 时,它实际上调用了window.setContentView
并且最终ActivityThread.handleResumeActivity
会调用 ActivityonResume
方法,视图显示。我们看handleResumeActivity
方法。它将调用活动makeVisible
方法。
...
if (r.activity.mVisibleFromClient) {
r.activity.makeVisible();
}
...
// the makeVieible will call wm.addView method
void makeVisible() {
if (!mWindowAdded) {
ViewManager wm = getWindowManager();
wm.addView(mDecor, getWindow().getAttributes());
mWindowAdded = true;
}
mDecor.setVisibility(View.VISIBLE);
}
// this metod in the last called WindowGolbal.addView;then in the inner method;
// it will call ViewRootImpl.setView, in this method, it calls requestLayout
public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
...
// Schedule the first layout -before- adding to the window
// manager, to make sure we do the relayout before receiving
// any other events from the system.
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.");
}
}
所以我们在这里发现它提醒我们我们不能更新视图。系统这样做,使 UI 显示流畅,更新视图简单。如果许多线程可以更新它。这是一件坏事。因为它必须处理并发问题
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句