安卓的ui数据的内容,只能在主线程里更新数据。
如果在子线程里更新数据,就会报错。
void checkThread() {
if (mThread != Thread.currentThread()) {
throw new CalledFromWrongThreadException(
"Only the original thread that created a view hierarchy can touch its views.");
}
}
安卓10.0在viewRootImpl里面调用流程说明
1、Handler里面dispatchMessage
2、TransactionExecutor里面的execute
3、TransactionExecutor里面的executeLifecycleState
4、ResumeActivityItem方法execute
5、ActivityThread方法handleResumeActivity
6、WindowManagerImpl方法addView
7、WindowManagerGlobal方法addView
8、ViewRootImp方法setView
9、ViweRootImp方法requestLayout
10、ViewRootImp方法checkThread
在每次的执行绘制前,会调用检测是否是当前的线程
在线程中更新ur数据的错误示例
handler.postDelayed(new Runnable() {
@Override
public void run() {
new Thread(new Runnable() {
@Override
public void run() {
tv.setText("fffff");
}
}).start();
}
},5000);
上述的方法会在子线程里更新ui页面,导致抛出异常
调用流程
TextView setText
TextView checkForRelayout
requrestLayout ConstraintLayout
requestLayout View
requessetLayout ViewRootImp
checkThread ViewRootImp检查当前的布局是否合适,否则会提示错误