正如我们知道的,android是不让在子线程中更新ui的。在子线程中更新ui会直接抛出异常
- Only the original thread that created a view hierarchy can touch its views
- 那么这种检查机制在什么时候发生的呢?
- 那么真的不能在子线程中更新ui么?我们带着这个疑问来看一下系统代码
我们知道android中的view的更新(大小,位置,内容)全部都交给了WindowManager,那么我们带着疑问来看下WindowMagager接口的实现类WindowManagerImpl,中如何控制对view的更新的
- 我们知道WindowManager中有三个常用方法 addView(),removeView()和updateViewLayout();
接下来我们只分析updateViewLayout()方法。
public void updateViewLayout(@NonNull View view, @NonNull ViewGroup.LayoutParams params) { applyDefaultToken(params); mGlobal.updateViewLayout(view, params); }
- applyDefaultToken(params);方法和Window的层级有关系,这里和我们探讨的view的跟新没有关系,因此跳过
mGlobal.updateViewLayout(view, params); 发现windowManager的更新其实是交给了mGlobal来操作了,那么mGlobal是什么呢?
private final WindowManagerGlobal mGlobal = WindowManagerGlobal.getInstance();
- 发现mGlobal其实是WindowManaerImpl一个成员变量,而且还是单例。其实WindowManagerImpl的跟新委托给了WindowManagerGlobal
那么WindowManagerGlobal的updateViewLayout()方法里面完成了什么功能呢?
public void updateViewLayout(View view, ViewGroup.LayoutParams params) { if (view == null) { throw new IllegalArgumentException("view must not be null"); } if (!(params instanceof WindowManager.LayoutParams)) { throw new IllegalArgumentException("Params must be WindowManager.LayoutParams"); } final WindowManager.LayoutParams wparams = (WindowManager.LayoutPa