当前位置:   article > 正文

Android14 WMS启动流程_android wms

android wms

一 概述

本文Android14源代码可参考:Search

Android 系统中,从设计的角度来看,窗口管理系统是基于 C/S 模式的。整个窗口系统分为服务端和客户端两大部分,客户端负责请求创建窗口和使用窗口,服务端完成窗口的维护,窗口显示等。

WMS 在 Android 系统的地位,它作为中间层,连接了上层的 View 框架和下层的 SurfaceFingler。

SurfaceFingler在systrace的表现可以参考:Perfetto详细解析-CSDN博客

WMS 主要职责

窗口管理:负责启动、添加、删除窗口,管理窗口大小、层级,核心成员有:WindowContainer、RootWindowContainer、DisplayContent、TaskStack、Task、AppWindowToken、WindowState;

窗口动画:由其子系统 WindowAnimator 管理;

输入系统中转站:通过对窗口的触摸从而产生触摸事件,由 InputMethodService(IMS)对触摸事件进行处理,它会寻找一个最合适的窗口处理触摸反馈信息;

Surface 管理:为每个窗口分配一块 Surface,用于绘制要显示的内容。

二、WMS重要成员

WMS

继承于 IWindowManager.Stub,作为 Binder 服务端

mSessions

ArraySet 类型的变量,元素类型为 Session,保存着所有的 Session 对象,Session 继承于 IWindowSession.Stub,作为 Binder 服务端,它主要用于进程间通信,其他的应用程序进程想要和 WMS 进程进行通信就需要经过 Session,并且每个应用程序进程都会对应一个Session,WMS 保存这些 Session 用来记录所有向 WMS 提出窗口管理服务的客户端。

mPolicy

WindowManagerPolicy 类型的变量,是窗口管理策略的接口类,用来定义一个窗口策略所要遵循的通用规范,并提供了 WindowManager 所有的特定的 UI 行为。具体实现类为 PhoneWindowManager,这个实现类在 WMS 创建时被创建。WMP 允许定制窗口层级和特殊窗口类型以及关键的调度和布局。

DisplayContent 的成员变量 mTokenMap,保存所有的 WindowToken 对象,以 IBinder 为 key,可以是 IAppWindowToken 或者其他 Binder 的 Bp 端;另一端情况:ActivityRecord.Token extends IApplicationToken.Stub

mWindowMap

WindowHashMap 类型的变量,WindowHashMap 继承了 HashMap,它限制了 HashMap 的 key 值的类型为 IBinder,value 值的类型为 WindowState。保存 WMS 中所有的 WindowState 对象

mResizingWindows

ArrayList 类型的变量,元素类型为 WindowState。mResizingWindows 是用来存储正在调整大小的窗口的列表。

mAnimator

WindowAnimator 类型的变量,用于管理窗口的动画以及特效动画。

mH

H 类型的变量,系统的 Handler 类,用于将任务加入到主线程的消息队列中,这样代码逻辑就会在主线程中执行。

三、WMS 的启动流程

3.1 SystemServer.java

3.1.1 main(String[] args)

  1. /**
  2. * The main entry point from zygote.
  3. */
  4. public static void main(String[] args) {
  5. new SystemServer().run();
  6. }

main方法中只调用了SystemServer的run方法,如下所示。

3.1.2 run()

从下面的注释中可以看到,官方把系统服务分为了三种类型,分别是引导服务、核心服务和其他服务,其中其他服务是一些非紧要和一些不需要立即启动的服务。系统服务总共大约有80多个,我们主要来查看引导服务WMS是如何启动的。

  1. private void run() {
  2. // Initialize native services.
  3. //1.加载了动态库libandroid_servers.so
  4. System.loadLibrary("android_servers");
  5. ......
  6. // Create the system service manager.
  7. //2.创建SystemServiceManager,它会对系统的服务进行创建、启动和生命周期管理。
  8. mSystemServiceManager = new SystemServiceManager(mSystemContext);
  9. mSystemServiceManager.setStartInfo(mRuntimeRestart,
  10. mRuntimeStartElapsedTime, mRuntimeStartUptime);
  11. mDumper.addDumpable(mSystemServiceManager);
  12. ......
  13. // Start services.
  14. try {
  15. t.traceBegin("StartServices");
  16. //用SystemServiceManager启动了ActivityManagerService、PowerManagerService、PackageManagerService等服务。
  17. startBootstrapServices(t);
  18. //启动了BatteryService、UsageStatsService和WebViewUpdateService。
  19. startCoreServices(t);
  20. //启动了CameraService、WindowManagerService、VrManagerService等服务。这些服务的父类均为SystemService。
  21. startOtherServices(t);
  22. startApexServices(t);
  23. // Only update the timeout after starting all the services so that we use
  24. // the default timeout to start system server.
  25. updateWatchdogTimeout(t);
  26. } catch (Throwable ex) {
  27. Slog.e("System", "******************************************");
  28. Slog.e("System", "************ Failure starting system services", ex);
  29. throw ex;
  30. } finally {
  31. t.traceEnd(); // StartServices
  32. }
  33. ...
  34. }

3.1.3 startOtherServices(@NonNull TimingsTraceAndSlog t)

  1. private void startOtherServices(@NonNull TimingsTraceAndSlog t) {
  2. t.traceBegin("startOtherServices");
  3. mSystemServiceManager.updateOtherServicesStartIndex();
  4. ......
  5. t.traceBegin("StartInputManagerService");
  6. // wms与 InputManagerService 息息相关,创建 InputManagerService 对象
  7. inputManager = new InputManagerService(context);
  8. t.traceEnd();
  9. ......
  10. t.traceBegin("StartWindowManagerService");
  11. // WMS needs sensor service ready
  12. mSystemServiceManager.startBootPhase(t, SystemService.PHASE_WAIT_FOR_SENSOR_SERVICE);
  13. 3.2. 创建 WindowManagerService 对象
  14. wm = WindowManagerService.main(context, inputManager, !mFirstBoot,
  15. new PhoneWindowManager(), mActivityManagerService.mActivityTaskManager);
  16. // 将WindowManagerService添加到服务中
  17. ServiceManager.addService(Context.WINDOW_SERVICE, wm, /* allowIsolated= */ false,
  18. DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO);
  19. // 将InputManagerService 添加到服务中
  20. ServiceManager.addService(Context.INPUT_SERVICE, inputManager,
  21. /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
  22. t.traceEnd();
  23. t.traceBegin("SetWindowManagerService");
  24. 3.3. wms 与 ams 关联
  25. mActivityManagerService.setWindowManager(wm);
  26. t.traceEnd();
  27. t.traceBegin("WindowManagerServiceOnInitReady");
  28. // 3.4 初始化完成
  29. wm.onInitReady();
  30. t.traceEnd();
  31. t.traceBegin("StartInputManager");
  32. // 3.5 InputManagerService 设置回调,并启动 InputManagerService
  33. inputManager.setWindowManagerCallbacks(wm.getInputManagerCallback());
  34. inputManager.start();
  35. t.traceEnd();
  36. ......
  37. t.traceBegin("MakeDisplayReady");
  38. try {
  39. // 3.6 调用 displayReady 方法
  40. wm.displayReady();
  41. } catch (Throwable e) {
  42. reportWtf("making display ready", e);
  43. }
  44. t.traceEnd();
  45. t.traceBegin("MakeDisplayReady");
  46. try {
  47. wm.displayReady();
  48. } catch (Throwable e) {
  49. reportWtf("making display ready", e);
  50. }
  51. t.traceEnd();
  52. ......
  53. try {
  54. //3.7 系统准备完毕,调用 systemReady
  55. wm.systemReady();
  56. } catch (Throwable e) {
  57. reportWtf("making Window Manager Service ready", e);
  58. }
  59. t.traceEnd();
  60. ......
  61. }

下面根据注释的1-6跟进源码查看

3.2 创建 WindowManagerService 对象

3.2.1 WindowManagerService.java & WindowManagerService main(...)

  1. public static WindowManagerService main(final Context context, final InputManagerService im,
  2. final boolean showBootMsgs, WindowManagerPolicy policy,
  3. ActivityTaskManagerService atm) {
  4. return main(context, im, showBootMsgs, policy, atm, new DisplayWindowSettingsProvider(),
  5. SurfaceControl.Transaction::new, SurfaceControl.Builder::new);
  6. }
  7. //PhoneWindowManager,主要是负责窗口管理的各种策略。在 android.display 实例化 wms,所以wms 跑在android.display线程中
  8. // 一个Supplier可以通过lambda表达式、方法引用或默认构造函数来实例化。
  9. // Supplier在Java 8中被引入,属于java.util.function包
  10. // transactionFactory 为 SurfaceControl.Transaction::new,创建 Transaction 对象
  11. // 通过get 可以获取到对象 Transaction
  12. /**
  13. * Creates and returns an instance of the WindowManagerService. This call allows the caller
  14. * to override factories that can be used to stub native calls during test.
  15. */
  16. @VisibleForTesting
  17. public static WindowManagerService main(final Context context, final InputManagerService im,
  18. final boolean showBootMsgs, WindowManagerPolicy policy, ActivityTaskManagerService atm,
  19. DisplayWindowSettingsProvider displayWindowSettingsProvider,
  20. Supplier<SurfaceControl.Transaction> transactionFactory,
  21. Function<SurfaceSession, SurfaceControl.Builder> surfaceControlFactory) {
  22. final WindowManagerService[] wms = new WindowManagerService[1];
  23. //3.2.2运行在"android.display"线程
  24. //3.2.4运行 runWithScissors
  25. DisplayThread.getHandler().runWithScissors(() ->
  26. //执行WindowManagerService构造函数
  27. wms[0] = new WindowManagerService(context, im, showBootMsgs, policy, atm,
  28. displayWindowSettingsProvider, transactionFactory,
  29. surfaceControlFactory), 0);
  30. return wms[0];
  31. }

3.2.2 DisplayThread.java & getHandler()

  1. DisplayThread 给系统使用的共享单例前台线程类,线程名字为 android.display,专门提供给WindowManager, DisplayManager, InputManager来执行快速响应的实时操作。
  2. public final class DisplayThread extends ServiceThread {
  3. private static DisplayThread sInstance;
  4. private static Handler sHandler;
  5. private DisplayThread() {
  6. // DisplayThread runs important stuff, but these are not as important as things running in
  7. // AnimationThread. Thus, set the priority to one lower.
  8. // 线程名字为 "android.display",优先级为 -3
  9. super("android.display", Process.THREAD_PRIORITY_DISPLAY + 1, false /*allowIo*/);
  10. }
  11. private static void ensureThreadLocked() {
  12. if (sInstance == null) {
  13. sInstance = new DisplayThread();
  14. sInstance.start();
  15. sInstance.getLooper().setTraceTag(Trace.TRACE_TAG_SYSTEM_SERVER);
  16. // 调用makeSharedHandler,跟进代码
  17. sHandler = makeSharedHandler(sInstance.getLooper());
  18. }
  19. }
  20. public static DisplayThread get() {
  21. synchronized (DisplayThread.class) {
  22. ensureThreadLocked();
  23. return sInstance;
  24. }
  25. }
  26. // 获取到handler
  27. public static Handler getHandler() {
  28. synchronized (DisplayThread.class) {
  29. ensureThreadLocked();
  30. return sHandler;
  31. }
  32. }
  33. /**
  34. * Disposes current display thread if it's initialized. Should only be used in tests to set up a
  35. * new environment.
  36. */
  37. @VisibleForTesting
  38. public static void dispose() {
  39. synchronized (DisplayThread.class) {
  40. if (sInstance == null) {
  41. return;
  42. }
  43. //handler 执行 runWithScissors 方法
  44. getHandler().runWithScissors(() -> sInstance.quit(), 0 /* timeout */);
  45. sInstance = null;
  46. }
  47. }
  48. }

3.2.3 ServiceThread.java $ makeSharedHandler()

  1. public class ServiceThread extends HandlerThread {
  2. private static final String TAG = "ServiceThread";
  3. private final boolean mAllowIo;
  4. public ServiceThread(String name, int priority, boolean allowIo) {
  5. super(name, priority);
  6. mAllowIo = allowIo;
  7. }
  8. @Override
  9. public void run() {
  10. Process.setCanSelfBackground(false);
  11. if (!mAllowIo) {
  12. StrictMode.initThreadDefaults(null);
  13. }
  14. super.run();
  15. }
  16. //创建handler,looper 为 thread "android.display" 的looper
  17. protected static Handler makeSharedHandler(Looper looper) {
  18. return new Handler(looper, /*callback=*/ null, /* async=*/ false, /* shared=*/ true);
  19. }
  20. }

3.2.4 Handler.java & runWithScissors()

  1. public final boolean runWithScissors(@NonNull Runnable r, long timeout) {
  2. if (r == null) {
  3. throw new IllegalArgumentException("runnable must not be null");
  4. }
  5. if (timeout < 0) {
  6. throw new IllegalArgumentException("timeout must be non-negative");
  7. }
  8. if (Looper.myLooper() == mLooper) {
  9. r.run();
  10. return true;
  11. }
  12. BlockingRunnable br = new BlockingRunnable(r);
  13. // 返回BlockingRunnable的postAndWait
  14. return br.postAndWait(this, timeout);
  15. }
  16. private static final class BlockingRunnable implements Runnable {
  17. private final Runnable mTask;
  18. private boolean mDone;
  19. public BlockingRunnable(Runnable task) {
  20. mTask = task;
  21. }
  22. @Override
  23. public void run() {
  24. try {
  25. mTask.run();
  26. } finally {
  27. synchronized (this) {
  28. mDone = true;
  29. // 执行完则唤醒系统主线程
  30. notifyAll();
  31. }
  32. }
  33. }
  34. public boolean postAndWait(Handler handler, long timeout)
  35. // 将其增加到消息队列中
  36. if (!handler.post(this)) {
  37. return false;
  38. }
  39. synchronized (this) {
  40. if (timeout > 0) {
  41. final long expirationTime = SystemClock.uptimeMillis() + timeout;
  42. while (!mDone) {
  43. long delay = expirationTime - SystemClock.uptimeMillis();
  44. if (delay <= 0) {
  45. return false; // timeout
  46. }
  47. try {
  48. wait(delay);
  49. } catch (InterruptedException ex) {
  50. }
  51. }
  52. } else {
  53. while (!mDone) {
  54. try {
  55. // 阻塞systemserver 主线程
  56. wait();
  57. } catch (InterruptedException ex) {
  58. }
  59. }
  60. }
  61. }
  62. return true;
  63. }
  64. }
  65. }

3.2.5 WindowManagerService构造函数

  1. private WindowManagerService(Context context, InputManagerService inputManager,
  2. boolean showBootMsgs, boolean onlyCore, WindowManagerPolicy policy,
  3. ActivityTaskManagerService atm, DisplayWindowSettingsProvider
  4. displayWindowSettingsProvider, Supplier<SurfaceControl.Transaction> transactionFactory,
  5. Supplier<Surface> surfaceFactory,
  6. Function<SurfaceSession, SurfaceControl.Builder> surfaceControlFactory) {
  7. installLock(this, INDEX_WINDOW);
  8. // 锁机制与 atm 一致
  9. mGlobalLock = atm.getGlobalLock();
  10. // 缓存 AtmS
  11. mAtmService = atm;
  12. mContext = context;
  13. mIsPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
  14. mAllowBootMessages = showBootMsgs;
  15. mOnlyCore = onlyCore;
  16. mLimitedAlphaCompositing = context.getResources().getBoolean(
  17. com.android.internal.R.bool.config_sf_limitedAlpha);
  18. mHasPermanentDpad = context.getResources().getBoolean(
  19. com.android.internal.R.bool.config_hasPermanentDpad);
  20. mInTouchMode = context.getResources().getBoolean(
  21. com.android.internal.R.bool.config_defaultInTouchMode);
  22. inputManager.setInTouchMode(
  23. mInTouchMode, myPid(), myUid(), /* hasPermission = */ true);
  24. mDrawLockTimeoutMillis = context.getResources().getInteger(
  25. com.android.internal.R.integer.config_drawLockTimeoutMillis);
  26. // 是否允许在低电量开启动画
  27. mAllowAnimationsInLowPowerMode = context.getResources().getBoolean(
  28. com.android.internal.R.bool.config_allowAnimationsInLowPowerMode);
  29. mMaxUiWidth = context.getResources().getInteger(
  30. com.android.internal.R.integer.config_maxUiWidth);
  31. mDisableTransitionAnimation = context.getResources().getBoolean(
  32. com.android.internal.R.bool.config_disableTransitionAnimation);
  33. mPerDisplayFocusEnabled = context.getResources().getBoolean(
  34. com.android.internal.R.bool.config_perDisplayFocusEnabled);
  35. mAssistantOnTopOfDream = context.getResources().getBoolean(
  36. com.android.internal.R.bool.config_assistantOnTopOfDream);
  37. mLetterboxConfiguration = new LetterboxConfiguration(
  38. // Using SysUI context to have access to Material colors extracted from Wallpaper.
  39. ActivityThread.currentActivityThread().getSystemUiContext());
  40. // Must be before createDisplayContentLocked.
  41. mInputManager = inputManager;
  42. mDisplayManagerInternal = LocalServices.getService(DisplayManagerInternal.class);
  43. mPossibleDisplayInfoMapper = new PossibleDisplayInfoMapper(mDisplayManagerInternal);
  44. mSurfaceControlFactory = surfaceControlFactory;
  45. mTransactionFactory = transactionFactory;
  46. mSurfaceFactory = surfaceFactory;
  47. // 获取 Transaction 对象
  48. mTransaction = mTransactionFactory.get();
  49. mPolicy = policy;
  50. // 创建 WindowAnimator 对象
  51. mAnimator = new WindowAnimator(this);
  52. // 创建 RootWindowContainer 对象
  53. mRoot = new RootWindowContainer(this);
  54. final ContentResolver resolver = context.getContentResolver();
  55. mUseBLAST = Settings.Global.getInt(resolver,
  56. Settings.Global.DEVELOPMENT_USE_BLAST_ADAPTER_VR, 1) == 1;
  57. mSyncEngine = new BLASTSyncEngine(this);
  58. mWindowPlacerLocked = new WindowSurfacePlacer(this);
  59. // 任务快照控制类
  60. mTaskSnapshotController = new TaskSnapshotController(this);
  61. mWindowTracing = WindowTracing.createDefaultAndStartLooper(this,
  62. Choreographer.getInstance());
  63. LocalServices.addService(WindowManagerPolicy.class, mPolicy);
  64. mDisplayManager = (DisplayManager)context.getSystemService(Context.DISPLAY_SERVICE);
  65. // mH 为 final H mH = new H();
  66. mKeyguardDisableHandler = KeyguardDisableHandler.create(mContext, mPolicy, mH);
  67. mPowerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
  68. mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
  69. // 注册低电量观察者
  70. if (mPowerManagerInternal != null) {
  71. mPowerManagerInternal.registerLowPowerModeObserver(
  72. new PowerManagerInternal.LowPowerModeListener() {
  73. @Override
  74. public int getServiceType() {
  75. return ServiceType.ANIMATION;
  76. }
  77. @Override
  78. public void onLowPowerModeChanged(PowerSaveState result) {
  79. synchronized (mGlobalLock) {
  80. final boolean enabled = result.batterySaverEnabled;
  81. if (mAnimationsDisabled != enabled && !mAllowAnimationsInLowPowerMode) {
  82. mAnimationsDisabled = enabled;
  83. dispatchNewAnimatorScaleLocked(null);
  84. }
  85. }
  86. }
  87. });
  88. mAnimationsDisabled = mPowerManagerInternal
  89. .getLowPowerState(ServiceType.ANIMATION).batterySaverEnabled;
  90. }
  91. mScreenFrozenLock = mPowerManager.newWakeLock(
  92. PowerManager.PARTIAL_WAKE_LOCK, "SCREEN_FROZEN");
  93. mScreenFrozenLock.setReferenceCounted(false);
  94. mDisplayNotificationController = new DisplayWindowListenerController(this);
  95. mTaskSystemBarsListenerController = new TaskSystemBarsListenerController();
  96. mActivityManager = ActivityManager.getService();
  97. mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
  98. mAppOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
  99. AppOpsManager.OnOpChangedInternalListener opListener =
  100. new AppOpsManager.OnOpChangedInternalListener() {
  101. @Override public void onOpChanged(int op, String packageName) {
  102. updateAppOpsState();
  103. }
  104. };
  105. mAppOps.startWatchingMode(OP_SYSTEM_ALERT_WINDOW, null, opListener);
  106. mAppOps.startWatchingMode(AppOpsManager.OP_TOAST_WINDOW, null, opListener);
  107. mPmInternal = LocalServices.getService(PackageManagerInternal.class);
  108. mTestUtilityService = LocalServices.getService(TestUtilityService.class);
  109. final IntentFilter suspendPackagesFilter = new IntentFilter();
  110. suspendPackagesFilter.addAction(Intent.ACTION_PACKAGES_SUSPENDED);
  111. suspendPackagesFilter.addAction(Intent.ACTION_PACKAGES_UNSUSPENDED);
  112. context.registerReceiverAsUser(new BroadcastReceiver() {
  113. @Override
  114. public void onReceive(Context context, Intent intent) {
  115. final String[] affectedPackages =
  116. intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
  117. final boolean suspended =
  118. Intent.ACTION_PACKAGES_SUSPENDED.equals(intent.getAction());
  119. updateHiddenWhileSuspendedState(new ArraySet<>(Arrays.asList(affectedPackages)),
  120. suspended);
  121. }
  122. }, UserHandle.ALL, suspendPackagesFilter, null, null);
  123. // Get persisted window scale setting
  124. mWindowAnimationScaleSetting = Settings.Global.getFloat(resolver,
  125. Settings.Global.WINDOW_ANIMATION_SCALE, mWindowAnimationScaleSetting);
  126. mTransitionAnimationScaleSetting = Settings.Global.getFloat(resolver,
  127. Settings.Global.TRANSITION_ANIMATION_SCALE,
  128. context.getResources().getFloat(
  129. R.dimen.config_appTransitionAnimationDurationScaleDefault));
  130. setAnimatorDurationScale(Settings.Global.getFloat(resolver,
  131. Settings.Global.ANIMATOR_DURATION_SCALE, mAnimatorDurationScaleSetting));
  132. mForceDesktopModeOnExternalDisplays = Settings.Global.getInt(resolver,
  133. DEVELOPMENT_FORCE_DESKTOP_MODE_ON_EXTERNAL_DISPLAYS, 0) != 0;
  134. final String displaySettingsPath = Settings.Global.getString(resolver,
  135. DEVELOPMENT_WM_DISPLAY_SETTINGS_PATH);
  136. mDisplayWindowSettingsProvider = displayWindowSettingsProvider;
  137. if (displaySettingsPath != null) {
  138. mDisplayWindowSettingsProvider.setBaseSettingsFilePath(displaySettingsPath);
  139. }
  140. mDisplayWindowSettings = new DisplayWindowSettings(this, mDisplayWindowSettingsProvider);
  141. IntentFilter filter = new IntentFilter();
  142. // Track changes to DevicePolicyManager state so we can enable/disable keyguard.
  143. filter.addAction(ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
  144. mContext.registerReceiverAsUser(mBroadcastReceiver, UserHandle.ALL, filter, null, null);
  145. mLatencyTracker = LatencyTracker.getInstance(context);
  146. mSettingsObserver = new SettingsObserver();
  147. mHoldingScreenWakeLock = mPowerManager.newWakeLock(
  148. PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, TAG_WM);
  149. mHoldingScreenWakeLock.setReferenceCounted(false);
  150. mSurfaceAnimationRunner = new SurfaceAnimationRunner(mTransactionFactory,
  151. mPowerManagerInternal);
  152. mAllowTheaterModeWakeFromLayout = context.getResources().getBoolean(
  153. com.android.internal.R.bool.config_allowTheaterModeWakeFromWindowLayout);
  154. mTaskPositioningController = new TaskPositioningController(this);
  155. mDragDropController = new DragDropController(this, mH.getLooper());
  156. mHighRefreshRateDenylist = HighRefreshRateDenylist.create(context.getResources());
  157. mConstants = new WindowManagerConstants(this, DeviceConfigInterface.REAL);
  158. mConstants.start(new HandlerExecutor(mH));
  159. LocalServices.addService(WindowManagerInternal.class, new LocalService());
  160. mEmbeddedWindowController = new EmbeddedWindowController(mAtmService);
  161. mDisplayAreaPolicyProvider = DisplayAreaPolicy.Provider.fromResources(
  162. mContext.getResources());
  163. mDisplayHashController = new DisplayHashController(mContext);
  164. setGlobalShadowSettings();
  165. mAnrController = new AnrController(this);
  166. mStartingSurfaceController = new StartingSurfaceController(this);
  167. // anr 控制类,无响应,无焦点等
  168. mBlurController = new BlurController(mContext, mPowerManager);
  169. mTaskFpsCallbackController = new TaskFpsCallbackController(mContext);
  170. mAccessibilityController = new AccessibilityController(this);
  171. }

3.3 关联wms 与 ams

3.3.1 ActivityTaskManagerService.java & setWindowManager()

  1. public void setWindowManager(WindowManagerService wm) {
  2. synchronized (mGlobalLock) {
  3. mWindowManager = wm;
  4. // 缓存 RootWindowContainer
  5. mRootWindowContainer = wm.mRoot;
  6. mWindowOrganizerController.setWindowManager(wm);
  7. mTempConfig.setToDefaults();
  8. mTempConfig.setLocales(LocaleList.getDefault());
  9. mConfigurationSeq = mTempConfig.seq = 1;
  10. mRootWindowContainer.onConfigurationChanged(mTempConfig);
  11. mLockTaskController.setWindowManager(wm);
  12. mTaskSupervisor.setWindowManager(wm);
  13. // RootWindowContainer 设置 WindowManager
  14. mRootWindowContainer.setWindowManager(wm);
  15. if (mBackNavigationController != null) {
  16. mBackNavigationController.setTaskSnapshotController(wm.mTaskSnapshotController);
  17. }
  18. }
  19. }

3.4 初始化完成 onInitReady

3.4.1 WindowManagerService.java & onInitReady

  1. //3.4.1 初始化完成 onInitReady
  2. public void onInitReady() {
  3. initPolicy();
  4. // Add ourself to the Watchdog monitors.
  5. Watchdog.getInstance().addMonitor(this);
  6. createWatermark();
  7. showEmulatorDisplayOverlayIfNeeded();
  8. }
  9. private void initPolicy() {
  10. // 在ui 线程执行下列函数,"android.ui"
  11. UiThread.getHandler().runWithScissors(new Runnable() {
  12. @Override
  13. public void run() {
  14. WindowManagerPolicyThread.set(Thread.currentThread(), Looper.myLooper());
  15. //3.4.2 初始化 PhoneWindowManager
  16. mPolicy.init(mContext, WindowManagerService.this);
  17. }
  18. }, 0);
  19. }

3.4.2 PhoneWindowManager.java & init()

  1. mHandler = new PolicyHandler();
  2. public void init(Context context, WindowManagerFuncs funcs) {
  3. init(new Injector(context, funcs));
  4. }
  5. @VisibleForTesting
  6. void init(Injector injector) {
  7. mContext = injector.getContext();
  8. mWindowManagerFuncs = injector.getWindowManagerFuncs();
  9. mWindowManagerInternal = LocalServices.getService(WindowManagerInternal.class);
  10. mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
  11. mActivityTaskManagerInternal = LocalServices.getService(ActivityTaskManagerInternal.class);
  12. mInputManagerInternal = LocalServices.getService(InputManagerInternal.class);
  13. mDreamManagerInternal = LocalServices.getService(DreamManagerInternal.class);
  14. mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
  15. mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
  16. mSensorPrivacyManager = mContext.getSystemService(SensorPrivacyManager.class);
  17. mDisplayManager = mContext.getSystemService(DisplayManager.class);
  18. mDisplayManagerInternal = LocalServices.getService(DisplayManagerInternal.class);
  19. mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
  20. mPackageManager = mContext.getPackageManager();
  21. mHasFeatureWatch = mPackageManager.hasSystemFeature(FEATURE_WATCH);
  22. mHasFeatureLeanback = mPackageManager.hasSystemFeature(FEATURE_LEANBACK);
  23. mHasFeatureAuto = mPackageManager.hasSystemFeature(FEATURE_AUTOMOTIVE);
  24. mHasFeatureHdmiCec = mPackageManager.hasSystemFeature(FEATURE_HDMI_CEC);
  25. mAccessibilityShortcutController = injector.getAccessibilityShortcutController(
  26. mContext, new Handler(), mCurrentUserId);
  27. mGlobalActionsFactory = injector.getGlobalActionsFactory();
  28. mLockPatternUtils = new LockPatternUtils(mContext);
  29. mLogger = new MetricsLogger();
  30. mScreenOffSleepTokenAcquirer = mActivityTaskManagerInternal
  31. .createSleepTokenAcquirer("ScreenOff");
  32. Resources res = mContext.getResources();
  33. mWakeOnDpadKeyPress =
  34. res.getBoolean(com.android.internal.R.bool.config_wakeOnDpadKeyPress);
  35. mWakeOnAssistKeyPress =
  36. res.getBoolean(com.android.internal.R.bool.config_wakeOnAssistKeyPress);
  37. mWakeOnBackKeyPress =
  38. res.getBoolean(com.android.internal.R.bool.config_wakeOnBackKeyPress);
  39. // Init display burn-in protection
  40. boolean burnInProtectionEnabled = mContext.getResources().getBoolean(
  41. com.android.internal.R.bool.config_enableBurnInProtection);
  42. // Allow a system property to override this. Used by developer settings.
  43. boolean burnInProtectionDevMode =
  44. SystemProperties.getBoolean("persist.debug.force_burn_in", false);
  45. if (burnInProtectionEnabled || burnInProtectionDevMode) {
  46. final int minHorizontal;
  47. final int maxHorizontal;
  48. final int minVertical;
  49. final int maxVertical;
  50. final int maxRadius;
  51. if (burnInProtectionDevMode) {
  52. minHorizontal = -8;
  53. maxHorizontal = 8;
  54. minVertical = -8;
  55. maxVertical = -4;
  56. maxRadius = (isRoundWindow()) ? 6 : -1;
  57. } else {
  58. Resources resources = mContext.getResources();
  59. minHorizontal = resources.getInteger(
  60. com.android.internal.R.integer.config_burnInProtectionMinHorizontalOffset);
  61. maxHorizontal = resources.getInteger(
  62. com.android.internal.R.integer.config_burnInProtectionMaxHorizontalOffset);
  63. minVertical = resources.getInteger(
  64. com.android.internal.R.integer.config_burnInProtectionMinVerticalOffset);
  65. maxVertical = resources.getInteger(
  66. com.android.internal.R.integer.config_burnInProtectionMaxVerticalOffset);
  67. maxRadius = resources.getInteger(
  68. com.android.internal.R.integer.config_burnInProtectionMaxRadius);
  69. }
  70. mBurnInProtectionHelper = new BurnInProtectionHelper(
  71. mContext, minHorizontal, maxHorizontal, minVertical, maxVertical, maxRadius);
  72. }
  73. ....
  74. // handler是跑在ui 线程
  75. mSideFpsEventHandler = new SideFpsEventHandler(mContext, mHandler, mPowerManager);

3.5 InputManagerService 设置回调,并启InputManagerService

3.5.1 InputManagerService.java & setWindowManagerCallbacks

  1. public void setWindowManagerCallbacks(WindowManagerCallbacks callbacks) {
  2. // 保证只有一个 callback
  3. if (mWindowManagerCallbacks != null) {
  4. unregisterLidSwitchCallbackInternal(mWindowManagerCallbacks);
  5. }
  6. mWindowManagerCallbacks = callbacks;
  7. registerLidSwitchCallbackInternal(mWindowManagerCallbacks);
  8. }

3.5.2 InputManagerService.java & registerLidSwitchCallbackInternal()

  1. void registerLidSwitchCallbackInternal(@NonNull LidSwitchCallback callback) {
  2. synchronized (mLidSwitchLock) {
  3. // 将 callback 保存到 mLidSwitchCallbacks
  4. mLidSwitchCallbacks.add(callback);
  5. // Skip triggering the initial callback if the system is not yet ready as the switch
  6. // state will be reported as KEY_STATE_UNKNOWN. The callback will be triggered in
  7. // systemRunning().
  8. if (mSystemReady) {
  9. boolean lidOpen = getSwitchState(-1 /* deviceId */, InputDevice.SOURCE_ANY, SW_LID)
  10. == KEY_STATE_UP;
  11. callback.notifyLidSwitchChanged(0 /* whenNanos */, lidOpen);
  12. }
  13. }
  14. }

3.5.3 InputManagerService.java & start()

  1. public void start() {
  2. Slog.i(TAG, "Starting input manager");
  3. mNative.start();
  4. // Add ourselves to the Watchdog monitors.
  5. Watchdog.getInstance().addMonitor(this);
  6. }

3.6 调用 displayReady 方法

3.6.1 WindowManagerService.java & displayReady()

  1. public void displayReady() {
  2. synchronized (mGlobalLock) {
  3. if (mMaxUiWidth > 0) {
  4. mRoot.forAllDisplays(displayContent -> displayContent.setMaxUiWidth(mMaxUiWidth));
  5. }
  6. applyForcedPropertiesForDefaultDisplay();
  7. mAnimator.ready();
  8. mDisplayReady = true;
  9. // Reconfigure all displays to make sure that forced properties and
  10. // DisplayWindowSettings are applied.
  11. mRoot.forAllDisplays(DisplayContent::reconfigureDisplayLocked);
  12. mIsTouchDevice = mContext.getPackageManager().hasSystemFeature(
  13. PackageManager.FEATURE_TOUCHSCREEN);
  14. mIsFakeTouchDevice = mContext.getPackageManager().hasSystemFeature(
  15. PackageManager.FEATURE_FAKETOUCH);
  16. }
  17. mAtmService.updateConfiguration(null /* request to compute config */);
  18. }

3.7 系统准备完毕,调用 systemReady

  1. public void systemReady() {
  2. mSystemReady = true;
  3. // 调用 PhoneWindowManager的systemReady
  4. mPolicy.systemReady();
  5. mRoot.forAllDisplayPolicies(DisplayPolicy::systemReady);
  6. // 快照控制类
  7. mSnapshotController.systemReady();
  8. mHasWideColorGamutSupport = queryWideColorGamutSupport();
  9. mHasHdrSupport = queryHdrSupport();
  10. // ui线程执行 loadSettings
  11. UiThread.getHandler().post(mSettingsObserver::loadSettings);
  12. IVrManager vrManager = IVrManager.Stub.asInterface(
  13. ServiceManager.getService(Context.VR_SERVICE));
  14. if (vrManager != null) {
  15. try {
  16. final boolean vrModeEnabled = vrManager.getVrModeState();
  17. synchronized (mGlobalLock) {
  18. vrManager.registerListener(mVrStateCallbacks);
  19. if (vrModeEnabled) {
  20. mVrModeEnabled = vrModeEnabled;
  21. mVrStateCallbacks.onVrStateChanged(vrModeEnabled);
  22. }
  23. }
  24. } catch (RemoteException e) {
  25. // Ignore, we cannot do anything if we failed to register VR mode listener
  26. }
  27. }
  28. }

整个启动过程有3个线程,systemserver主线程,”android.display”,”android.ui”,整个过程采用阻塞的方式(利用runWithScissors)执行,WMS.mH的Looper运行在”android.display”进程。

参考:

WMS启动流程分析 | Skytoby

WMS—启动过程 - Gityuan博客 | 袁辉辉的技术博客

Android渲染(一)_系统服务WMS启动过程(基于Android10) - 掘金

Android窗口管理2 WMS启动过程_postandwait-CSDN博客

【安卓12源码】WMS的作用及其启动流程_android wms_蜘蛛侠不会飞的博客-CSDN博客

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/574716
推荐阅读
相关标签
  

闽ICP备14008679号