Android中Activity、Window、ViewRootImpl与子线程更新UI

本文详细介绍了Android中Activity、Window、WindowManager、WindowManagerGlobal和ViewRootImpl之间的层级关系,重点讨论了为什么子线程不能直接更新UI,并提出了在子线程中初始化ViewRootImpl以实现在子线程更新UI的方法。通过分析错误信息和源码,解释了ViewRootImpl的mThread检查机制,提供了在特定情况下子线程更新UI的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

三者层级关系

在这里插入图片描述

1、Window

  • Window是一个抽象类,唯一的实现类是PhoneWindow
  • Window分为三种类型应用Window、子Window、系统Window。子Window无法独立存在必须依赖父级Window,例如Dialog必须依附于Activity
  • Window分层,在显示时层级高的窗口会覆盖在在层级低的窗口
类型 层级(z-ordered) 例子
应用 Window 1~99 Activity
子 Window 1000~1999 Dialog
系统 Window 2000~2999 Toast

2、WindowManager

  • WindowManager是Window的管理者,WindowManager是一个接口它的实现类是WindowMangerImpl
  • WindowManager只提供是对View的add、update、remove操作
  • WindowManager的addView()方法最终会创建新的ViewRootImpl而addContentView()直接把View添加到DecorView上

3、WindowManagerGlobal

  • WindowManagerGlobal是单例模式,进程唯一
    在这里插入图片描述

  • WindowManager的add、update、remove操作最终会调用WindowManagerGlobal的方法

  • WindowManagerGlobal下管理了4个List

ArrayList<View> mViews;   //——所有Window的根View
ArrayList<ViewRootImpl> mRoots;  //所有根View对应的ViewRootImpl
ArrayList<WindowManager.LayoutParams> mParams;  //所有根View(Window)对应的布局参数
ArraySet<View> mDyingViews;  //待销毁的根View(Window)
  • WindowManagerGlobal负责对ViewRootImpl进行统一管理,而具体实现是在ViewRootImpl

4、ViewRootImpl

关系图
在这里插入图片描述

  • 一个Window(PhoneWindow)可能存在多个ViewRootImpl链,所以需要一个Window将所有链管理起来
  • WindowManager.addView()调用WindowManagerGlobal.addView(),最终在WindowManagerGlobal.addView()方法中创建RootViewImpl
//WindowManagerGlobal.addView()

public void addView(View view, ViewGroup.LayoutParams params,
       Display display, Window parentWindow, int userId) {
   
   //检查参数是否合法
   if (view == null) {
   
       throw new IllegalArgumentException("view must not be null");
   }
   if (display == null) {
   
       throw new IllegalArgumentException("display must not be null");
   }
   if (!(params instanceof WindowManager.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值