Android-从开机动画到输入使能的完整流程详解

4 阅读43分钟

Android 从开机动画到输入使能的完整流程详解


目录

  1. 问题背景:一个 30 秒的触摸死区
  2. 全景图与完整调用链:这条链路长什么样、谁调用谁
  3. 第一幕:开机动画进程(BootAnimation)
  4. 第二幕:Keyguard 判定(KeyguardServiceDelegate)
  5. 第三幕:亮屏状态机(DisplayPolicy)
  6. 第四幕:编排者(PhoneWindowManager)
  7. 第五幕:终局(WindowManagerService 五道门)
  8. 第六幕:SurfaceFlinger 与输入分发使能
  9. 三个真实案例对照
  10. 排查工具箱
  11. 修复清单
  12. 总结

1. 问题背景:一个 30 秒的触摸死区

现象:恢复出厂设置后重启,画面正常(Launcher 已显示、隐私弹窗已弹出),但点击毫无反应。用户从 14:48:17 连续点屏 40 多次,内核触摸驱动每一次都收到了事件:

14:48:17.827  kernel  : semidrive,safets semidrive_ts@0: touch up(x=753,y=361,dn=1)
14:48:21.302  kernel  : semidrive,safets semidrive_ts@0: touch down(x=1000,y=663,dn=11)
...(40+ 次,dn 计数一路涨到 47)

但 Android 框架侧只有一条回应:

14:48:17.561  InputDispatcher: Dropped event because input dispatch is disabled.

输入分发被禁用了——事件在 system_server 门口就被丢弃,从未送达任何 App。直到:

14:48:40.414  WindowManager: ***** BOOT TIMEOUT: forcing display enabled
14:48:42.816  kernel     : touch down(...,dn=49)   ← 这次点击生效了

问题锁定:从 boot_progress_enable_screen(14:48:10.414)到 BOOT TIMEOUT(14:48:40.414),恰好 30.000 秒。这不是触摸屏的问题,是框架"开机使能屏幕"的流程被卡死,最后被 30 秒兜底定时器强行救回。

而进一步排查发现:这个 30 秒死区每次开机都存在,只是平时没人一开机就点屏幕,所以从未暴露。恢复出厂只是把用户推到了必须立刻与弹窗交互的场景。


2. 全景图与完整调用链:这条链路长什么样、谁调用谁

init 启动 bootanimation 进程
        │  (线程循环播放动画,同时轮询 service.bootanim.exit)
        ▼
SystemUI 启动 ──► PWP.onSystemUiStarted / systemBooted
        │              └─► bindKeyguard() ──► KeyguardServiceDelegate.bindService()
        │                        └─► 判定"这台机器有没有锁屏" → deviceHasKeyguard
        ▼
DisplayPowerController 首次亮屏
        │              └─► PWP.screenTurningOn()
        │                      ├─ hasKeyguard()==true ──► 挂 5 秒超时,等 keyguard 画完
        │                      └─ hasKeyguard()==false ─► 立即进入下一环
        ▼
keyguard 画完(或超时) ──► PWP.finishKeyguardDrawn()
        │                      └─► waitForAllWindowsDrawn(等所有窗口首帧)
        ▼
窗口全部画完 ──► PWP.finishWindowsDrawn ──► finishScreenTurningOn ──► enableScreen
        │                      └─► mKeyguardDrawnOnce 门锁(仅第一次) ──► enableScreenIfNeeded
        ▼
AMS.ensureBootCompleted ──► WMS.enableScreenAfterBoot
        │                      └─► 挂 30 秒 BOOT_TIMEOUT 兜底定时器
        │                      └─► mPolicy.systemBooted()(重跑一轮亮屏链!)
        │                      └─► performEnableScreen()  ← 五道门
        ▼
   ┌────────────────────────────────────────────────┐
   │ 门1  mDisplayEnabled?                          │
   │ 门2  mSystemBooted || mShowingBootMessages?    │
   │ 门3  canDismissBootAnimation()?                │
   │ 门4  系统装饰窗(状态栏/导航栏)都画完了?          │
   │      ↓ 通过后: service.bootanim.exit = 1       │
   │ 门5  bootanimation 进程退出了吗?(200ms 轮询)    │
   └────────────────────────────────────────────────┘
        ▼
SurfaceControl.bootFinished() ──► SurfaceFlinger::bootFinished
        │                              └─► 打印 sf_stop_bootanim、sys.boot_completed=1
        ▼
mDisplayEnabled = true
        ▼
mInputManagerCallback.setEventDispatchingLw(...)  ← ★ 输入分发打开,触摸可用

三个设计要点(理解全链的关键):

  1. 输入分发是整条链的最后一行代码——前面任何一环 return,它就不会执行;
  2. performEnableScreen() 是"一次性"的——正常路径只被有效执行一次,失败后能否重试取决于几个容易断掉的触发源;
  3. 30 秒 BOOT_TIMEOUT 是保底——它强制跳过门 4/门 5,是"给异常情况准备的最后防线"。一旦它成了每次开机的必经之路,说明前面的正常链路坏了。

2.1 一条时间线走到底:按真实调用/打印顺序讲解(以健康机 1.log 为锚)

先回答一个高频疑问:PWP 是哪个服务?

PWP 不是服务,不是独立进程,更不是独立线程。 PWP = PhoneWindowManager,是 system_server 进程里的一个普通 Java 类,实现 WindowManagerPolicy 接口,由 WindowManagerService 创建并持有(存在 mPolicy 字段)。它自己没有线程——它的 mHandler 跑在 WMS 的 policy 线程上(日志里显示为 android.ui);DisplayPowerController 要调它时,是 DisplayManagerService 通过内部回调在同进程内直接调用的,所以那条日志显示 thread=PowerManagerService。

这条链上所有"玩家"的归属一览:

类/进程角色所在进程谁创建/拉起
bootanimation播开机动画独立 native 进程init
SystemUI(com.app.systemui)状态栏/导航栏/锁屏 UI独立 App 进程AMS
AMS(ActivityManagerService)系统总管,boot 收尾的发起者system_serverSystemServer
WMS(WindowManagerService)窗口总管,五道门的执行者system_serverSystemServer
PWP(PhoneWindowManager)策略编排:亮屏链的中央调度system_serverWMS 创建
DisplayPolicy亮屏状态机(四个标志位)system_serverWMS/PWP 持有
KeyguardServiceDelegate锁屏判定与代理system_serverPWP 持有

通信方式只有三种:① system_server 内部(AMS/WMS/PWP/DisplayPolicy/KSD)= 普通 Java 方法调用;② 与 bootanimation = 系统属性 service.bootanim.exit(单向);③ 与 SystemUI = binder。

下面按真实执行顺序从头走到尾。 每步标注"谁调谁",并附健康机 1.log 的对应打印——日志出现的顺序就是代码执行的顺序。


第 1 步 · 进程起点(boot 早期,无日志)

init 同时拉起两条线:bootanimation 进程(开始播动画,内部循环轮询 service.bootanim.exit 属性)和 zygote → system_server。

第 2 步 · 服务创建(仍是 boot 早期)

SystemServer.startOtherServices 依次:创建 WMS → PWP.init()(注册 Handler、读 config_keyguardDrawnTimeout 配置)→ 调 AMS.systemReady()(其主线程收尾见第 8 步)。

第 3 步 · 首次亮屏线(与 boot 收尾并行赛跑,健康机上它先到)

DisplayPowerController(状态机) → DisplayManagerService → PWP.screenTurningOn(...)
   ├─► DisplayPolicy.screenTurnedOn(listener)     ← 四个标志位重置
   └─► hasKeyguard() 此刻还是默认 true(bindKeyguard 还没执行)
          └─► 挂 5 秒超时 + KeyguardServiceDelegate.onScreenTurningOn(回调被暂存)
11-05 10:48:48.130  BootFlow3: [DP] screenTurnedOn: NEW screen-on cycle, RESET state ... thread=PowerManagerService
11-05 10:48:48.130  BootFlow3: [PWP-screenTurningOn] hasKeyguard()=true: waiting for keyguard drawn, timeout=5000ms
11-05 10:48:48.130  KeyguardServiceDelegate: onScreenTurningOn(): no keyguard service!
11-05 10:48:48.130  BootFlow2: [KSD-onScreenTurningOn] drawn callback STASHED ... deviceHasKeyguard=true

第 4 步 · 触摸屏与显示完成关联(硬件链路就绪,但输入分发仍未开)

11-05 10:48:47.284  InputManager-JNI: Viewport [0] to add: local:0, isActive: false
11-05 10:48:48.139  InputManager-JNI: Viewport [0] to add: local:0, isActive: true

第 5 步 · AMS 主阶段就绪

11-05 10:48:48.516  boot_progress_ams_ready: 15850

第 6 步 · SystemUI 进程上报(标准 bindKeyguard 触发点,约 2 秒后到达)

SystemUI 进程 → WindowManagerGlobal.onSystemUiStarted()   ← binder
   → WMS.onSystemUiStarted() → PWP.onSystemUiStarted() → bindKeyguard()
        → KeyguardServiceDelegate.bindService()
             → isLoadScreenLock(): credentialType=-1(无锁屏凭据)
                  → SKIP bind → reseteKguardState(): deviceHasKeyguard=false   ← "无锁屏"从此生效
11-05 10:48:50.096  BootFlow2: [KSD-bindService] enter: component=ComponentInfo{...KeyguardService} isXts=false currentUser=0 thread=main
11-05 10:48:50.097  BootFlow2: [KSD] isLoadScreenLock: userId=0 credentialType=-1 (CREDENTIAL_TYPE_NONE=-1)
11-05 10:48:50.098  BootFlow2: [KSD-bindService] SKIP bind (no lock screen), setting deviceHasKeyguard=false EARLY (good path)
11-05 10:48:50.101  BootFlow2: [KSD] reseteKguardState: deviceHasKeyguard -> false

第 7 步 · 救场请求全部被门 2 挡掉(解释日志里 SKIPPED 为何刷屏)

窗口陆续画完 → RootWindowContainer 布局钩子 / PWP 门锁 → WMS.enableScreenIfNeededLocked() → 但 mSystemBooted 仍是 false → 每一次都被拒:

11-05 10:48:47.281  BootFlow5: [enableScreen] enableScreenIfNeeded SKIPPED: system not booted yet (retrigger wasted at uptimeMs=14614)
11-05 10:48:47.281  BootFlow5: [enableScreen] enableScreenIfNeeded SKIPPED: system not booted yet (retrigger wasted at uptimeMs=14615)
...(开机 20 秒内出现十余次,全部被拒,直到第 8 步 enableScreenAfterBoot 亲自进场)

第 8 步 · boot 收尾:主使能线,一次通关(30 秒计时从这里开始,全链核心)

AMS.systemReady 主线程收尾 → AMS.ensureBootCompleted()
   → mAtmInternal.enableScreenAfterBoot → ActivityTaskSupervisor
        → EventLogTags.writeBootProgressEnableScreen(...)   ← boot_progress_enable_screen,计时零点
        → WMS.enableScreenAfterBoot()
             ├─► 挂 30 秒 BOOT_TIMEOUT
             ├─► mPolicy.systemBooted()                     ← PWP
             │      ├─► bindKeyguard()(第二触发点,被 mKeyguardBound 门锁挡住,不重复执行)
             │      └─► 重跑亮屏链:screenTurningOn → DDP 状态重置
             │             → hasKeyguard()=false → fast path → keyguardDrawComplete 1ms 内补回
             └─► performEnableScreen()  #1
                    ├─► 门1/2/3/4 全过(入口快照:canDismissBootAnimation=true、bootanimSvc=stopped)
                    ├─► service.bootanim.exit = 1          ← bootanimation 进程读属性自行退出
                    ├─► 门5 过(进程早已被 init 强杀,零轮询)
                    ├─► SurfaceControl.bootFinished() → SurfaceFlinger::bootFinished
                    │        └─► sf_stop_bootanim: 21388
                    ├─► mDisplayEnabled = true              ← wm_boot_animation_done: 21389
                    ├─► mInputManagerCallback.setEventDispatchingLw(...)  ← 输入分发使能动作
                    └─► mActivityManager.bootAnimationComplete()
                             → AMS.finishBooting() → BOOT_COMPLETED / ADAYO_BOOT_COMPLETED 广播
11-05 10:48:54.027  boot_progress_enable_screen: 21361
11-05 10:48:54.027  BootFlow5: [enableScreen] enableScreenAfterBoot enter: mDisplayEnabled=false mSystemBooted=false thread=android.ui
11-05 10:48:54.030  BootFlow5: [enableScreen] BOOT_TIMEOUT armed (+30s), uptimeMs=21364
11-05 10:48:54.031  BootFlow3: [PWP-systemBooted] display ON/turning-on ... RE-RUNNING screenTurningOn + screenTurnedOn ...
11-05 10:48:54.031  BootFlow3: [DP] screenTurnedOn: NEW screen-on cycle, RESET state ... thread=android.ui
11-05 10:48:54.031  BootFlow3: [PWP-screenTurningOn] hasKeyguard()=false: immediate MSG_KEYGUARD_DRAWN_COMPLETE (fast path)
11-05 10:48:54.032  BootFlow5: [enableScreen#1] enter: ... canDismissBootAnimation=true ... bootanimSvc=stopped ... thread=android.ui
11-05 10:48:54.032  BootFlow5: [enableScreen#1] all gates passed, setting service.bootanim.exit=1
11-05 10:48:54.054  sf_stop_bootanim: 21388
11-05 10:48:54.055  wm_boot_animation_done: 21389
11-05 10:48:54.061  BootFlow7: [enableScreen#1] SUCCESS: mDisplayEnabled=true, took 30ms, mEventDispatchingEnabled=false
11-05 10:48:54.061  BootFlow7: [enableScreen#1] INPUT DISPATCH ENABLED (touch ready)

第 9 步 · 输入分发真正打开(画面亮与触摸可用之间还有 256ms)

11-05 10:48:54.317  InputDispatcher: setInputDispatchMode: enabled=1, frozen=0

由另一条路径(WMS.setEventDispatching(true),来自用户切换/AMS)下发——第 8 步 SUCCESS 时刻的 mEventDispatchingEnabled=false 在这里被翻正。从这一刻起触摸才真正可用。

第 10 步 · 首次亮屏挂的 5 秒超时"迟到"(全程 no-op)

第 3 步挂起的 5 秒超时此刻才到期(主线程繁忙延迟约 1 秒)。它把亮屏响应链(⑥⑦)完整走了一遍——但 mDisplayEnabled 早已是 true,所有动作都变成空转:

11-05 10:48:54.325  WindowManager: Keyguard drawn timeout. Setting mKeyguardDrawComplete
11-05 10:48:54.325  BootFlow3: [DP] finishKeyguardDrawn: TRUE, keyguardDrawComplete=true
11-05 10:48:54.325  BootFlow3: [PWP] finishKeyguardDrawn: keyguardDrawComplete=true, starting waitForAllWindowsDrawn(1000ms)
11-05 10:48:54.347  BootFlow3: [DP] finishKeyguardDrawn: FALSE ...   ← 同周期第二次,幂等拒绝(正常)
11-05 10:48:54.347  BootFlow4: [DP] finishWindowsDrawn: TRUE, windowsDrawnComplete=true
11-05 10:48:54.347  BootFlow4: [DP] finishScreenTurningOn: TRUE, screenOnFully=true
11-05 10:48:54.347  BootFlow4: [PWP-enableScreen] FIRST keyguard-drawn: latch consumed ...

一句话总结(健康机的时间顺序) :第 3 步首次亮屏(5 秒等待开始)→ 第 6 步 bindKeyguard SKIP(无锁屏生效)→ 第 8 步 boot 收尾一次通关(30ms)→ 第 9 步输入分发打开 → 第 10 步 5 秒超时迟到(纯 no-op)。先亮屏、后 bind、再使能——三条独立触发线(DisplayPowerController 亮屏线、SystemUI 上报线、AMS boot 收尾线)在时间轴上交叉赛跑,这正是流程第一眼显得"乱"的原因:不是代码乱,是三个触发源在竞争,最终靠各种门锁和超时收敛。

兜底分支:若第 8 步任何一道门卡住 30 秒 → BOOT TIMEOUT handler → performBootTimeout() → mForceDisplayEnabled=true(跳过门 4/门 5)→ 强制通关(案例 1 即此路径,见第 9.1 节)。

2.2 两个"多入口"清单(混乱的主要来源)

performEnableScreen 有四个重入入口,记住这张表就不乱:

#入口调用者时机
1enableScreenAfterBoot 尾部直调WMS(← AMS.ensureBootCompleted)boot 收尾,第一次进场
2ENABLE_SCREEN handlerenableScreenIfNeededLocked(← PWP.enableScreen 门锁 / RootWindowContainer 布局钩子)窗口画完 / surface 布局时
3CHECK_IF_BOOT_ANIMATION_FINISHED handlercheckBootAnimationCompleteLocked 的 200ms 轮询动画进程退出后
4BOOT_TIMEOUT handlerperformBootTimeout30 秒兜底

bindKeyguard 有两个触发点(mKeyguardBound 门锁保证只生效一次):

触发点调用链备注
onSystemUiStartedSystemUI 进程 → WindowManagerGlobal → WMS.onSystemUiStarted → PWP.onSystemUiStarted → bindKeyguardAOSP 标准路径(④)
systemBootedWMS.enableScreenAfterBoot → mPolicy.systemBooted → bindKeyguard提前兜底(⑤)

screenTurningOn 有两条并行触发线:

触发线调用者线程时间特征
首次亮屏DisplayPowerController(③)PowerManagerService / android.display开机早期,通常早于 bindKeyguard → hasKeyguard 还是默认 true → 吃 5 秒等待
systemBooted 重跑WMS.enableScreenAfterBoot → mPolicy.systemBooted(⑤)android.uiboot 收尾,重置 DDP 状态,是 GATE3 竞争的来源

3. 第一幕:开机动画进程(BootAnimation)

文件:frameworks/base/cmds/bootanimation/BootAnimation.cpp

调用链位置(见 2.1) :本幕是独立 native 进程,不由任何 Java 代码调用——入口 threadLoop 由 init 拉起(①)。它与 WMS 的唯一通信是轮询 service.bootanim.exit 属性,该属性由 WMS 门 4 之后置 1(⑧)、SurfaceFlinger 再置一次。它"退没退干净"是门 5 的判据。

3.1 入口决策:播 zip 动画还是内置 logo

// BootAnimation.cpp — readyToRun() 的收尾逻辑
// 若无动画资源,直接返回 NAME_NOT_FOUND,进程自然退出
if (mZipFileName.empty() && mDisplayLayerStack != 0) {
    t.setDisplayLayerStack(mDisplayToken, ui::DEFAULT_LAYER_STACK);
    t.apply();
    return NAME_NOT_FOUND;
}
​
// threadLoop():动画主循环
bool BootAnimation::threadLoop() {
    bool result;
    initShaders();
    // ── 插桩日志(BootFlow1):进入动画循环,打印走哪条路 ──
    __android_log_print(ANDROID_LOG_INFO, "BootFlow1",
            "[bootanim-threadLoop] enter: mZipFileName='%s' (empty -> android() logo,"
            " non-empty -> movie())", mZipFileName.string());
​
    // We have no bootanimation file, so we use the stock android logo
    // animation.
    if (mZipFileName.isEmpty()) {
        ALOGD("No animation file");
        result = android();      // 播内置 Android logo(掩码+闪光)
    } else {
        result = movie();        // 播 /system/media/bootanimation.zip
    }
    // ── 插桩日志(BootFlow1):循环结束,进程即将退出 ──
    __android_log_print(ANDROID_LOG_INFO, "BootFlow1",
            "[bootanim-threadLoop] animation loop finished result=%d, tearing down"
            " (process exiting)", result);
​
    mCallbacks->shutdown();
    // ...EGL 资源清理、IPCThreadState::stopProcess(),进程退出
    return result;
}

真机日志实录:

; 问题机(Q 版,第二次开机):动画进程生命周期
14:46:42.784  BootAnimation: BootAnimationStartTiming start time: 5198ms
14:46:42.875  BootAnimation: BootAnimationShownTiming start time: 5284ms
​
; 健康机(Android 14):动画进程开机 6.7 秒被 init 直接 SIGKILL —— vendor 定制的"强制退场"
08:00:05.664  SIGNAL_TRACE: sig=9(SIGKILL) sender_pid=1(init) target_pid=386(bootanimation) type=2

健康机这条 SIGKILL from init 是"到点强杀"路径,恰好绕开了后面门 5 的坑(见案例 3)。

3.2 zip 加载:那个著名的坑

// BootAnimation.cpp — movie() → loadAnimation() → preloadZip()
if (mAnimation == nullptr) {
    mAnimation = loadAnimation(mZipFileName);
}
if (mAnimation == nullptr) {
    // ── 插桩日志(BootFlow1):加载失败,进程本应随循环结束退出 ──
    __android_log_print(ANDROID_LOG_INFO, "BootFlow1",
            "[bootanim-movie] loadAnimation FAILED -> returning false"
            " (threadLoop will tear down; if process stays alive after this,"
            " it's stuck outside the animation loop!)");
    return false;        // ← 加载失败:threadLoop 结束,进程应当退出
}
// ── 插桩日志(BootFlow1):加载成功,打印 part 数与首 part 帧数 ──
__android_log_print(ANDROID_LOG_INFO, "BootFlow1",
        "[bootanim-movie] animation loaded: parts=%zu totalFrames=%d",
        mAnimation->parts.size(),
        static_cast<int>(mAnimation->parts.size() > 0
                ? mAnimation->parts[0].frames.size() : -1));
// preloadZip():先启动条目迭代,失败打插桩日志
if (!zip->startIteration(&cookie)) {
    __android_log_print(ANDROID_LOG_INFO, "BootFlow1",
            "[bootanim-preloadZip] startIteration FAILED (bad/corrupt zip?)");
    return false;
}
​
// 遍历 zip 条目时:
if (zip->getEntryDataOffset(entry) == 0) {
    // 只接受 STORE(不压缩)方式
} else {
    SLOGE("bootanimation.zip is compressed; must be only stored");
}
// loadAnimation():打开 zip 文件本身
ZipFileRO *zip = ZipFileRO::open(fn);
if (zip == nullptr) {
    SLOGE("Failed to open animation zip "%s": %s",
        fn.string(), strerror(errno));
    // ── 插桩日志(BootFlow1)──
    __android_log_print(ANDROID_LOG_INFO, "BootFlow1",
            "[bootanim-loadAnimation] zip OPEN FAILED: %s", fn.string());
    return nullptr;
}
ALOGD("%s is loaded successfully", fn.string());
// ── 插桩日志(BootFlow1)──
__android_log_print(ANDROID_LOG_INFO, "BootFlow1",
        "[bootanim-loadAnimation] zip opened OK: %s", fn.string());

坑点:bootanimation.zip 必须用 STORE(仅存储)方式打包(zip -0)。用压缩方式打包时,每条目都打上面的 E 级错误,所有帧都无法加载,loadAnimation 返回 nullptr。

真机日志实录(问题机,三次开机每次都打):

14:46:42.794  BootAnimation: bootanimation.zip is compressed; must be only stored

这条 E 级日志是门 5 死等的第一现场证据:zip 坏 → 帧加载失败 → 进程退出异常 → init.svc.bootanim 一直 running。

3.3 退出机制:轮询一个系统属性

// BootAnimation.cpp
static const char EXIT_PROP_NAME[] = "service.bootanim.exit";
​
// 动画循环内(android() 中):
checkExit();
while (!exitPending());
​
void BootAnimation::checkExit() {
    // Allow surface flinger to gracefully request shutdown
    char value[PROPERTY_VALUE_MAX];
    property_get(EXIT_PROP_NAME, value, "0");
    int exitnow = atoi(value);
    if (exitnow) {
        // ── 插桩日志(BootFlow6):收到退出请求,进程即将自然结束 ──
        __android_log_print(ANDROID_LOG_INFO, "BootFlow6",
                "[bootanim-checkExit] %s=1 detected -> requestExit() (process will exit soon)",
                EXIT_PROP_NAME);
        requestExit();      // 置 exitPending,循环退出,进程自然结束
    } else {
        // ── 插桩日志(BootFlow6):还没收到,继续等 ──
        __android_log_print(ANDROID_LOG_INFO, "BootFlow6",
                "[bootanim-checkExit] %s=0, keep waiting", EXIT_PROP_NAME);
    }
}

日志指纹:

日志含义
BootAnimation: bootanimation.zip is compressed; must be only storedzip 打包方式错误,帧全部加载失败
SIGNAL_TRACE: sig=9(SIGKILL) sender_pid=1(init) target_pid=XXX(bootanimation)某个 init 规则直接杀掉了动画进程(vendor 定制的"强制退场")
sf_stop_bootanim: NNNNNSurfaceFlinger 收到 bootFinished 调用(见第六幕)

Q 版 30 秒死区的真凶就在这一幕:zip 是压缩格式 → 帧加载失败 → 但进程没有干净退出(卡在异常状态),此后 WMS 置 service.bootanim.exit=1,进程却收不到/不响应 → init.svc.bootanim 一直 running → 把第五道门堵死 29 秒。

BootFlow6 插桩后的预期输出(checkExit 每次被调用都会打):

BootFlow6: [bootanim-checkExit] service.bootanim.exit=0, keep waiting
BootFlow6: [bootanim-checkExit] service.bootanim.exit=0, keep waiting
...
BootFlow6: [bootanim-checkExit] service.bootanim.exit=1 detected -> requestExit() (process will exit soon)

问题机的真实表现:WMS 已把 service.bootanim.exit 置 1,但始终看不到 =1 detected——进程早已退出异常状态,不再响应属性,init.svc.bootanim 保持 running 直到 30 秒兜底。


4. 第二幕:Keyguard 判定(KeyguardServiceDelegate)

文件:services/core/java/com/android/server/policy/keyguard/KeyguardServiceDelegate.java

调用链位置(见 2.1) :入口 bindService 由 PWP.bindKeyguard() 调用,触发点有两个——onSystemUiStarted()(④,SystemUI 上报)和 systemBooted()(⑤,,mKeyguardBound 门锁保证只执行一次。onScreenTurningOn 由 PWP.screenTurningOn 调用(③ 首次亮屏 / ⑤ 重跑)。本类只服务 PWP,不主动调用其他幕。

4.1 这个类管什么

它不实现锁屏,只做三件事:① 缓存锁屏状态(mKeyguardState);② 尝试 bind 真正的 KeyguardService(SystemUI 进程里);③ 把 framework 侧对锁屏的调用转发给已连接的服务。

private static final class KeyguardState {
    KeyguardState() {
        reset();
    }
    boolean showing;
    boolean inputRestricted;
    boolean secure;
    boolean dreaming;
    boolean systemIsReady;
    boolean deviceHasKeyguard;    // ★ 这台机器"有没有锁屏"的最终结论
    ...
    private void reset() {
        // Assume keyguard is showing and secure until we know for sure.
        showing = true;
        secure = true;
        deviceHasKeyguard = true;   // ★ 默认:假设有锁屏!
        enabled = true;
    }
};

4.2 车机 bindService

public void bindService(Context context) {
    Intent intent = new Intent();
    final Resources resources = context.getApplicationContext().getResources();
​
    final ComponentName keyguardComponent = ComponentName.unflattenFromString(
            resources.getString(com.android.internal.R.string.config_keyguardComponent));
    intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
    intent.setComponent(keyguardComponent);
    // ── 插桩日志(BootFlow2):判定开始,打印要 bind 的组件 ──
    Slog.i("BootFlow2", "[KSD-bindService] enter: component=" + keyguardComponent
            + " isXts=" + isXts + " currentUser=" + ActivityManager.getCurrentUser()
            + " thread=" + Thread.currentThread().getName());
​
    // ── 车机:无锁屏密码就不加载锁屏 ──
    final boolean loadScreenLock = isLoadScreenLock(ActivityManager.getCurrentUser());
    // ── 插桩日志(BootFlow2):判定结果 ──
    Slog.i("BootFlow2", "[KSD-bindService] isLoadScreenLock=" + loadScreenLock);
    if(!isXts && !loadScreenLock){
        // ── 插桩日志(BootFlow2):好路径,提前关闭 ──
        Slog.i("BootFlow2", "[KSD-bindService] SKIP bind (no lock screen),"
                + " setting deviceHasKeyguard=false EARLY (good path)");
        reseteKguardState();      // deviceHasKeyguard = false,提前关闭
        return;
    }
​
    if (!context.bindServiceAsUser(intent, mKeyguardConnection,
            Context.BIND_AUTO_CREATE, mHandler, UserHandle.SYSTEM)) {
        // ── 插桩日志(BootFlow2):组件不存在,bind 失败才关闭(晚了!)──
        Slog.i("BootFlow2", "[KSD-bindService] bind FAILED (component not found?),"
                + " setting deviceHasKeyguard=false (LATE — race window was open"
                + " until now!)");
        Log.v(TAG, "*** Keyguard: can't bind to " + keyguardComponent);
        reseteKguardState();      // bind 失败,同样关闭
    } else {
        // ── 插桩日志(BootFlow2):bind 请求已受理,等连接回调 ──
        Slog.i("BootFlow2", "[KSD-bindService] bindServiceAsUser returned true,"
                + " waiting for onServiceConnected");
        if (DEBUG) Log.v(TAG, "*** Keyguard started");
    }
    ...
}
​
private boolean isLoadScreenLock(int userId){
    if (sLockSettings == null) {
        sLockSettings = ILockSettings.Stub.asInterface(
                (IBinder) ServiceManager.getService("lock_settings"));
    }
    try {
        final int credentialType = sLockSettings.getCredentialType(userId);
        // ── 插桩日志(BootFlow2):凭据类型(-1 = CREDENTIAL_TYPE_NONE)──
        Slog.i("BootFlow2", "[KSD] isLoadScreenLock: userId=" + userId
                + " credentialType=" + credentialType
                + " (CREDENTIAL_TYPE_NONE=" + CREDENTIAL_TYPE_NONE + ")");
        if(CREDENTIAL_TYPE_NONE == credentialType){
            Log.w(TAG, "No password does not load the lock screen, return");
            return false;          // 当前用户没设任何锁屏凭据
        }
    } catch (Exception re) {
        // ── 插桩日志(BootFlow2):查询异常,仍会尝试 bind!──
        Slog.i("BootFlow2", "[KSD] isLoadScreenLock: EXCEPTION -> returning true"
                + " (will try to bind!): " + re);
        Log.e(TAG, "failed to get credential type", re);   // 异常时返回 true,仍会尝试 bind!
    }
    return true;
}
​
private void reseteKguardState(){
    // ── 插桩日志(BootFlow2):唯一的"关闭"动作 ──
    Slog.i("BootFlow2", "[KSD] reseteKguardState: deviceHasKeyguard -> false");
    mKeyguardState.showing = false;
    mKeyguardState.secure = false;
    synchronized (mKeyguardState) {
        mKeyguardState.deviceHasKeyguard = false;   // ← 唯一的"关闭"动作
    }
}

对外查询:

public boolean hasKeyguard() {
    return mKeyguardState.deviceHasKeyguard;
}

真机日志实录(健康机 1.log,SKIP 好路径——BootFlow2 全序列):

11-05 10:48:50.096  BootFlow2: [KSD-bindService] enter: component=ComponentInfo{com.android.systemui/com.android.systemui.keyguard.KeyguardService} isXts=false currentUser=0 thread=main
11-05 10:48:50.097  BootFlow2: [KSD] isLoadScreenLock: userId=0 credentialType=-1 (CREDENTIAL_TYPE_NONE=-1)
11-05 10:48:50.097  BootFlow2: [KSD-bindService] isLoadScreenLock=false
11-05 10:48:50.098  BootFlow2: [KSD-bindService] SKIP bind (no lock screen), setting deviceHasKeyguard=false EARLY (good path)
11-05 10:48:50.101  BootFlow2: [KSD] reseteKguardState: deviceHasKeyguard -> false

读日志的姿势:bind 判定链 1 毫秒走完——credentialType=-1(无锁屏凭据) → SKIP bind → deviceHasKeyguard=false。这就是健康机不堵门 3 的根本原因。

4.3 回调暂存机制(为什么回调会丢)

public void onScreenTurningOn(final DrawnListener drawnListener) {
    if (mKeyguardService != null) {
        // ── 插桩日志(BootFlow2):服务已连接,回调正常转发 ──
        Slog.i("BootFlow2", "[KSD-onScreenTurningOn] service connected, forwarding drawn callback");
        // 正常路径:转发给 SystemUI 的 KeyguardService,画完回调
        mKeyguardService.onScreenTurningOn(new KeyguardShowDelegate(drawnListener));
    } else {
        // try again when we establish a connection
        Slog.w(TAG, "onScreenTurningOn(): no keyguard service!");
        // ── 插桩日志(BootFlow2):回调被暂存,连接不上则永久丢失 ──
        Slog.i("BootFlow2", "[KSD-onScreenTurningOn] drawn callback STASHED into"
                + " mDrawnListenerWhenConnect (lost forever if bind never succeeds),"
                + " deviceHasKeyguard=" + mKeyguardState.deviceHasKeyguard);
        // 服务未连接:把回调暂存,等 onServiceConnected 时补发
        mDrawnListenerWhenConnect = drawnListener;
    }
    mKeyguardState.screenState = SCREEN_STATE_TURNING_ON;
}

坑点:mDrawnListenerWhenConnect 只有在 onServiceConnected()(bind 成功)里才会被消费。如果组件不存在、bind 永远失败,回调永久丢失——framework 侧的 5 秒超时成为唯一出路。

日志指纹:

日志含义
KeyguardServiceDelegate: onScreenTurningOn(): no keyguard service!亮屏时 keyguard 服务尚未连接,回调被暂存
ActivityManager: Unable to start service Intent { cmp=com.android.systemui/.keyguard.KeyguardService } not foundconfig_keyguardComponent 指向的组件根本不存在(包没装或没声明该服务)
PackageManager$NameNotFoundException: com.android.systemui整个原生 SystemUI 包都不在

真机日志实录(健康机,首次亮屏早于 bind 判定,回调被暂存;2 秒后 SKIP 路径闭环):

11-05 10:48:48.130  KeyguardServiceDelegate: onScreenTurningOn(): no keyguard service!
11-05 10:48:48.130  BootFlow2: [KSD-onScreenTurningOn] drawn callback STASHED into mDrawnListenerWhenConnect (lost forever if bind never succeeds), deviceHasKeyguard=true

5. 第三幕:亮屏状态机(DisplayPolicy)

文件:services/core/java/com/android/server/wm/DisplayPolicy.java(Android S 起,原 DefaultDisplayPolicy 并入此类)

调用链位置(见 2.1) :本类是纯被调用方,只被 PWP 调用:screenTurnedOn(状态重置)由 PWP.screenTurningOn 调用(③⑤);三个 finishXxx 由 PWP 的同名 finishXxx 调用(⑥⑦)。它不调任何其他幕——它是被 PWP 读写的"状态寄存器"。

5.1 四个标志位

private boolean mScreenOnEarly;              // 开始亮屏
private boolean mScreenOnFully;              // 完全点亮(链条终点)
private boolean mKeyguardDrawComplete;       // keyguard 画完了
private boolean mWindowManagerDrawComplete;  // 所有窗口画完了
private ScreenOnListener mScreenOnListener;

5.2 状态重置——GATE3 卡点的根源

public void screenTurnedOn(ScreenOnListener screenOnListener) {
    // ── 插桩日志(BootFlow3):新的亮屏周期开始,四个标志全部重置 ──
    Slog.i("BootFlow3", "[DP] screenTurnedOn: NEW screen-on cycle, RESET state"
            + " (mKeyguardDrawComplete/mWindowManagerDrawComplete -> false!)"
            + " listener=" + screenOnListener
            + " thread=" + Thread.currentThread().getName());
    synchronized (mLock) {
        mScreenOnEarly = true;
        mScreenOnFully = false;
        mKeyguardDrawComplete = false;      // ★ 每次亮屏周期都清零!
        mWindowManagerDrawComplete = false;
        mScreenOnListener = screenOnListener;
    }
}

public void screenTurnedOff() {
    // ── 插桩日志(BootFlow3):灭屏同样重置 ──
    Slog.i("BootFlow3", "[DP] screenTurnedOff: RESET state");
    synchronized (mLock) {
        mScreenOnEarly = false;
        mScreenOnFully = false;
        mKeyguardDrawComplete = false;
        mWindowManagerDrawComplete = false;
        mScreenOnListener = null;
    }
}

注意:任何一次新的 screenTurnedOn() 调用(包括 systemBooted() 里"重跑一轮亮屏链"的那次)都会把 keyguardDrawComplete 重置为 false。而 performEnableScreen() 的门 3 恰好查这个标志——两者在微秒级交错时,就会撞出"明明画完了却判为没画完"的竞争(见案例 1 的 exit@GATE3)。

真机日志实录(健康机,一次开机内两次"亮屏周期",每次都重置四个标志):

; 首次亮屏:PowerManagerService 线程
11-05 10:48:48.130  BootFlow3: [DP] screenTurnedOn: NEW screen-on cycle, RESET state (mKeyguardDrawComplete/mWindowManagerDrawComplete -> false!) listener=null thread=PowerManagerService
; systemBooted 重跑:android.ui 线程
11-05 10:48:54.031  BootFlow3: [DP] screenTurnedOn: NEW screen-on cycle, RESET state (mKeyguardDrawComplete/mWindowManagerDrawComplete -> false!) listener=null thread=android.ui

5.3 三步完成状态机

/** Return false if we are not awake yet or we have already informed of this event. */
public boolean finishKeyguardDrawn() {
    synchronized (mLock) {
        if (!mScreenOnEarly || mKeyguardDrawComplete) {
            // ── 插桩日志(BootFlow3):幂等拒绝 ──
            Slog.i("BootFlow3", "[DP] finishKeyguardDrawn: FALSE (mScreenOnEarly="
                    + mScreenOnEarly + " mKeyguardDrawComplete=" + mKeyguardDrawComplete
                    + ") — keyguardDrawComplete NOT set");
            return false;                 // 未亮屏/已处理 → 拒绝
        }
        mKeyguardDrawComplete = true;
        mWindowManagerDrawComplete = false;
    }
    // ── 插桩日志(BootFlow3):完成置位 ──
    Slog.i("BootFlow3", "[DP] finishKeyguardDrawn: TRUE, keyguardDrawComplete=true");
    return true;
}
​
/** Return false if screen is not turned on or we did already handle this case earlier. */
public boolean finishWindowsDrawn() {
    synchronized (mLock) {
        if (!mScreenOnEarly || mWindowManagerDrawComplete) {
            // ── 插桩日志(BootFlow4):幂等拒绝 ──
            Slog.i("BootFlow4", "[DP] finishWindowsDrawn: FALSE (mScreenOnEarly="
                    + mScreenOnEarly + " mWindowManagerDrawComplete="
                    + mWindowManagerDrawComplete + ") — windowsDrawnComplete NOT set");
            return false;
        }
        mWindowManagerDrawComplete = true;
    }
    // ── 插桩日志(BootFlow4):完成置位 ──
    Slog.i("BootFlow4", "[DP] finishWindowsDrawn: TRUE, windowsDrawnComplete=true");
    return true;
}
​
/** Return false if it is not ready to turn on. */
public boolean finishScreenTurningOn() {
    synchronized (mLock) {
        if (mScreenOnFully || !mScreenOnEarly || !mWindowManagerDrawComplete
                || (mAwake && !mKeyguardDrawComplete)) {
            // ── 插桩日志(BootFlow4):四条件分解,定位缺哪一环 ──
            Slog.i("BootFlow4", "[DP] finishScreenTurningOn: FALSE (mAwake=" + mAwake
                    + " mScreenOnEarly=" + mScreenOnEarly
                    + " mScreenOnFully=" + mScreenOnFully
                    + " mKeyguardDrawComplete=" + mKeyguardDrawComplete
                    + " mWindowManagerDrawComplete=" + mWindowManagerDrawComplete + ")");
            return false;                 // ★ 四条件任一不满足 → 拒绝
        }
        mScreenOnListener = null;
        mScreenOnFully = true;
    }
    // ── 插桩日志(BootFlow4):完全点亮 ──
    Slog.i("BootFlow4", "[DP] finishScreenTurningOn: TRUE, screenOnFully=true");
    return true;
}

三个 finishXxx 都是幂等门闩:同一周期内第二次调用返回 false(防止重复完成),但也意味着"提前失败的机会只有一次"。

真机日志实录(健康机,一轮走完 + 幂等拒绝现场):

11-05 10:48:54.325  BootFlow3: [DP] finishKeyguardDrawn: TRUE, keyguardDrawComplete=true
11-05 10:48:54.347  BootFlow3: [DP] finishKeyguardDrawn: FALSE (mScreenOnEarly=true mKeyguardDrawComplete=true) — keyguardDrawComplete NOT set
11-05 10:48:54.347  BootFlow4: [DP] finishWindowsDrawn: TRUE, windowsDrawnComplete=true
11-05 10:48:54.347  BootFlow4: [DP] finishScreenTurningOn: TRUE, screenOnFully=true

第二条 FALSE 不是故障——是"同周期第二次调用被幂等拒绝"的正常表现(TRUE 在前,FALSE 在后,间隔 22ms)。读日志看顺序,不要看到 FALSE 就慌。


6. 第四幕:编排者(PhoneWindowManager)

文件:services/core/java/com/android/server/policy/PhoneWindowManager.java

调用链位置(见 2.1) :PWP 是整条链的中央调度。上游被两类调用者调用:DisplayPowerController → DisplayManagerService 调 screenTurningOn(③),WMS 调 systemBooted/onSystemUiStarted(⑤④)。下游它调用:DisplayPolicy.screenTurnedOn/finishXxx(状态机)、KeyguardServiceDelegate.onScreenTurningOn(锁屏判定)、WindowManagerInternal.waitForAllWindowsDrawn(等窗口,⑥)、mWindowManagerFuncs.enableScreenIfNeeded(触发 WMS 重入,⑦)。

6.1 screenTurningOn:两条路的分岔口

// Called on the DisplayManager's DisplayPowerController thread.
public void screenTurningOn(int displayId, final ScreenOnListener screenOnListener) {
    reportScreenTurningOnToWallpaper(displayId);
    if (displayId == DEFAULT_DISPLAY) {
        Trace.asyncTraceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, "screenTurningOn", 0);
        updateScreenOffSleepToken(false, false);
        mDefaultDisplayPolicy.screenTurnedOn(screenOnListener);   // ← 状态重置
        mBootAnimationDismissable = false;
​
        synchronized (mLock) {
            if (mKeyguardDelegate != null && mKeyguardDelegate.hasKeyguard()) {
                // ── 插桩日志(BootFlow3):路径A,等 keyguard 画完 ──
                Slog.i("BootFlow3", "[PWP-screenTurningOn] hasKeyguard()=true:"
                        + " waiting for keyguard drawn, timeout="
                        + getKeyguardDrawnTimeout() + "ms");
                // 路径A:有锁屏 → 挂 5 秒超时,等 keyguard 画完
                mHandler.removeMessages(MSG_KEYGUARD_DRAWN_TIMEOUT);
                mHandler.sendEmptyMessageDelayed(MSG_KEYGUARD_DRAWN_TIMEOUT,
                        getKeyguardDrawnTimeout());
                mKeyguardDelegate.onScreenTurningOn(mKeyguardDrawnCallback);
            } else {
                // ── 插桩日志(BootFlow3):路径B,立即完成 ──
                Slog.i("BootFlow3", "[PWP-screenTurningOn] hasKeyguard()=false:"
                        + " immediate MSG_KEYGUARD_DRAWN_COMPLETE (fast path)");
                // 路径B:无锁屏 → 立即完成
                mHandler.sendEmptyMessage(MSG_KEYGUARD_DRAWN_COMPLETE);
            }
        }
    } else {
        // 副屏:直接等窗口画完
        mWindowManagerInternal.waitForAllWindowsDrawn(
                mHandler.obtainMessage(MSG_WINDOW_MANAGER_DRAWN_COMPLETE, displayId, 0),
                WAITING_FOR_DRAWN_TIMEOUT, displayId);
    }
}

超时值:开机未完成时固定 5 秒,开机完成后用配置值:

private long getKeyguardDrawnTimeout() {
    final boolean bootCompleted =
            LocalServices.getService(SystemServiceManager.class).isBootCompleted();
    // Set longer timeout if it has not booted yet to prevent showing empty window.
    return bootCompleted ? mKeyguardDrawnTimeout : 5000;
}
​
// mKeyguardDrawnTimeout 来自 config_keyguardDrawnTimeout(默认 1000ms)
mKeyguardDrawnTimeout = mContext.getResources().getInteger(
        com.android.internal.R.integer.config_keyguardDrawnTimeout);

这解释了为什么只有"开机后的第一次亮屏"吃 5 秒——日常熄屏/亮屏时 bootCompleted 已为 true,走 1 秒配置值,感知不明显。

真机日志实录(健康机,两条路径在同一次开机内先后出现):

; 首次亮屏(14.6s):bind 判定还没跑,hasKeyguard 还是默认 true → 5 秒等待路径
11-05 10:48:48.130  BootFlow3: [PWP-screenTurningOn] hasKeyguard()=true: waiting for keyguard drawn, timeout=5000ms
​
; systemBooted 重跑(21.4s):bind 已 SKIP,deviceHasKeyguard=false → fast path
11-05 10:48:54.031  BootFlow3: [PWP-screenTurningOn] hasKeyguard()=false: immediate MSG_KEYGUARD_DRAWN_COMPLETE (fast path)

6.2 keyguard 画完的回调与超时兜底

final DrawnListener mKeyguardDrawnCallback = new DrawnListener() {
    @Override
    public void onDrawn() {
        if (DEBUG_WAKEUP) Slog.d(TAG, "mKeyguardDelegate.ShowListener.onDrawn.");
        mHandler.sendEmptyMessage(MSG_KEYGUARD_DRAWN_COMPLETE);
    }
};

PWP 的 Handler 分发:

case MSG_KEYGUARD_DRAWN_COMPLETE:
    if (DEBUG_WAKEUP) Slog.w(TAG, "Setting mKeyguardDrawComplete");
    finishKeyguardDrawn();
    break;
case MSG_KEYGUARD_DRAWN_TIMEOUT:
    Slog.w(TAG, "Keyguard drawn timeout. Setting mKeyguardDrawComplete");   // ← 日志指纹
    finishKeyguardDrawn();
    break;
case MSG_WINDOW_MANAGER_DRAWN_COMPLETE:
    final int displayId = msg.arg1;
    if (DEBUG_WAKEUP) Slog.w(TAG, "All windows drawn on display " + displayId);
    Trace.asyncTraceEnd(Trace.TRACE_TAG_WINDOW_MANAGER,
            TRACE_WAIT_FOR_ALL_WINDOWS_DRAWN_METHOD, displayId);
    finishWindowsDrawn(displayId);
    break;

注意 MSG_KEYGUARD_DRAWN_TIMEOUT 和 MSG_KEYGUARD_DRAWN_COMPLETE 都调 finishKeyguardDrawn() ——超时同样被视为"完成",这是第一层兜底(5 秒级)。

真机日志实录(健康机,首次亮屏(48.130)挂起的 5 秒超时在 54.325 到期,因主线程繁忙延迟约 1 秒——注意屏幕早在 54.061 已使能完成,该超时只是"无害的迟到"):

11-05 10:48:54.325  WindowManager: Keyguard drawn timeout. Setting mKeyguardDrawComplete

6.3 finishKeyguardDrawn → waitForAllWindowsDrawn

private void finishKeyguardDrawn() {
    if (!mDefaultDisplayPolicy.finishKeyguardDrawn()) {
        // ── 插桩日志(BootFlow3):幂等拒绝 ──
        Slog.i("BootFlow3", "[PWP] finishKeyguardDrawn: DDP returned FALSE"
                + " (spurious/not-ready — keyguardDrawComplete NOT set!)");
        return;      // 幂等拒绝(第二次进入)
    }
    // ── 插桩日志(BootFlow3):keyguard 完成,转入等窗口画完 ──
    Slog.i("BootFlow3", "[PWP] finishKeyguardDrawn: keyguardDrawComplete=true,"
            + " starting waitForAllWindowsDrawn(" + WAITING_FOR_DRAWN_TIMEOUT + "ms)");
​
    synchronized (mLock) {
        if (mKeyguardDelegate != null) {
            mHandler.removeMessages(MSG_KEYGUARD_DRAWN_TIMEOUT);
        }
    }
​
    // ... eventually calls finishWindowsDrawn which will finalize our screen turn on
    // as well as enabling the orientation change logic/sensor.
    Trace.asyncTraceBegin(Trace.TRACE_TAG_WINDOW_MANAGER,
            TRACE_WAIT_FOR_ALL_WINDOWS_DRAWN_METHOD, INVALID_DISPLAY);
    mWindowManagerInternal.waitForAllWindowsDrawn(
            mHandler.obtainMessage(MSG_WINDOW_MANAGER_DRAWN_COMPLETE, INVALID_DISPLAY, 0),
            WAITING_FOR_DRAWN_TIMEOUT,      // = 1000ms
            INVALID_DISPLAY);
}

keyguard 完成后,进入"等所有窗口首帧画完"环节(WMS 会跟踪每个窗口的 drawn 状态,画完后回 MSG_WINDOW_MANAGER_DRAWN_COMPLETE)。

真机日志实录(健康机,5 秒超时路径进入本函数):

11-05 10:48:54.325  BootFlow3: [PWP] finishKeyguardDrawn: keyguardDrawComplete=true, starting waitForAllWindowsDrawn(1000ms)

6.4 finishWindowsDrawn / finishScreenTurningOn / enableScreen

private void finishWindowsDrawn(int displayId) {
    if (displayId != DEFAULT_DISPLAY && displayId != INVALID_DISPLAY) {
        final ScreenOnListener l = mScreenOnListeners.removeReturnOld(displayId);
        if (l != null) l.onScreenOn();
        return;
    }
    if (!mDefaultDisplayPolicy.finishWindowsDrawn()) {
        // ── 插桩日志(BootFlow4):幂等拒绝 ──
        Slog.i("BootFlow4", "[PWP] finishWindowsDrawn: DDP returned FALSE"
                + " (spurious/not-ready — windowsDrawnComplete NOT set!)");
        return;
    }
    // ── 插桩日志(BootFlow4):窗口全部画完,进入完全点亮 ──
    Slog.i("BootFlow4", "[PWP] finishWindowsDrawn: windowsDrawnComplete=true"
            + " -> finishScreenTurningOn");
    finishScreenTurningOn();
}
​
private void finishScreenTurningOn() {
    mDefaultDisplayRotation.updateOrientationListener();
​
    final ScreenOnListener listener = mDefaultDisplayPolicy.getScreenOnListener();
    if (!mDefaultDisplayPolicy.finishScreenTurningOn()) {
        // ── 插桩日志(BootFlow4):未就绪,拒绝 ──
        Slog.i("BootFlow4", "[PWP] finishScreenTurningOn: DDP returned FALSE"
                + " (spurious/not-ready, screenOnFully NOT set)");
        return; // Spurious or not ready yet.
    }
    Trace.asyncTraceEnd(Trace.TRACE_TAG_WINDOW_MANAGER, "screenTurningOn", 0);
​
    enableScreen(listener, true /* report */);
}
​
private void enableScreen(ScreenOnListener listener, boolean report) {
    final boolean enableScreen;
    final boolean awake = mDefaultDisplayPolicy.isAwake();
    synchronized (mLock) {
        // Remember the first time we draw the keyguard so we know when we're done with
        // the main part of booting and can enable the screen and hide boot messages.
        if (!mKeyguardDrawnOnce && awake) {
            mKeyguardDrawnOnce = true;      // ★ 一次性门锁
            enableScreen = true;
            // ── 插桩日志(BootFlow4):门锁第一次消费,触发使能 ──
            Slog.i("BootFlow4", "[PWP-enableScreen] FIRST keyguard-drawn: latch consumed,"
                    + " will call enableScreenIfNeeded()");
            if (mBootMessageNeedsHiding) {
                mBootMessageNeedsHiding = false;
                hideBootMessages();
            }
        } else {
            enableScreen = false;           // 第二次以后:不再触发!
            // ── 插桩日志(BootFlow4):门锁已消费,救场机会丢失 ──
            Slog.i("BootFlow4", "[PWP-enableScreen] latch ALREADY consumed"
                    + " (mKeyguardDrawnOnce=true or !awake=" + !awake + "),"
                    + " NOT calling enableScreenIfNeeded() — retrigger lost here");
        }
    }
​
    if (report && listener != null) {
        listener.onScreenOn();
    }
​
    if (enableScreen) {
        mWindowManagerFuncs.enableScreenIfNeeded();   // → WMS 的 ENABLE_SCREEN
    }
}

mKeyguardDrawnOnce 是整个流程最阴险的门锁:

  • 它保证"启动阶段只使能一次屏幕"——设计意图是避免重复使能;
  • 但副作用是:如果第一次 enableScreenIfNeeded() 的时机不对(比如 mSystemBooted 还没置位,被 WMS 门 2 挡掉),后续所有 finishScreenTurningOn() 都因为门锁已消费而不再重试——救场机会被一次性浪费。

真机日志实录(健康机,门锁第一次也是唯一一次被消费):

11-05 10:48:54.347  BootFlow4: [PWP-enableScreen] FIRST keyguard-drawn: latch consumed, will call enableScreenIfNeeded()

6.5 systemBooted:重跑亮屏链(竞争之源)

Android 14的完整实现:

public void systemBooted() {
    bindKeyguard();                       //在 systemBooted 也尝试绑 keyguard
    synchronized (mLock) {
        mSystemBooted = true;
        if (mSystemReady) {
            mKeyguardDelegate.onBootCompleted();
        }
    }
    mSideFpsEventHandler.onFingerprintSensorReady();
    startedWakingUp(Display.DEFAULT_DISPLAY_GROUP, PowerManager.WAKE_REASON_UNKNOWN);
    finishedWakingUp(Display.DEFAULT_DISPLAY_GROUP, PowerManager.WAKE_REASON_UNKNOWN);
​
    int defaultDisplayState = mDisplayManager.getDisplay(DEFAULT_DISPLAY).getState();
    boolean defaultDisplayOn = defaultDisplayState == Display.STATE_ON;
    boolean defaultScreenTurningOn = mDefaultDisplayPolicy.getScreenOnListener() != null;
    if (defaultDisplayOn || defaultScreenTurningOn) {
        // ── 插桩日志(BootFlow3):屏已亮,重跑一轮亮屏链 ──
        Slog.i("BootFlow3", "[PWP-systemBooted] display ON/turning-on (state="
                + defaultDisplayState + ", listener=" + defaultScreenTurningOn + "):"
                + " RE-RUNNING screenTurningOn + screenTurnedOn"
                + " (may reset DDP draw-complete state!)");
        // Now that system is booted, wait for keyguard and windows to be drawn before
        // updating the orientation listener, stopping the boot animation and enabling screen.
        screenTurningOn(DEFAULT_DISPLAY, mDefaultDisplayPolicy.getScreenOnListener());
        screenTurnedOn(DEFAULT_DISPLAY);
    } else {
        // ── 插桩日志(BootFlow3):屏未亮,走快速分支 ──
        Slog.i("BootFlow3", "[PWP-systemBooted] display OFF: mBootAnimationDismissable=true"
                + " + enableScreen(fast path)");
        mBootAnimationDismissable = true;
        enableScreen(null, false /* report */);
    }
}

bindKeyguard() 有幂等保护,两个触发点谁先到谁生效:

private void bindKeyguard() {
    synchronized (mLock) {
        if (mKeyguardBound) {
            return;
        }
        mKeyguardBound = true;
    }
    mKeyguardDelegate.bindService(mContext);
}
​
@Override
public void onSystemUiStarted() {
    bindKeyguard();      // AOSP U 的标准触发点:SystemUI 进程起来之后
}

为什么"重跑"是竞争之源:screenTurningOn() 第一行就会调 DisplayPolicy.screenTurnedOn() → 四个标志位全部重置(见 5.2)。如果在重跑之前,第一轮亮屏链已经走到 finishKeyguardDrawn 把 keyguardDrawComplete 置 true,重跑会把它清零;而 WMS 紧接着执行的 performEnableScreen() 查门 3 时读到 false → 被挡。这就是案例 1 中 exit@GATE3 的完整机制。

真机日志实录(健康机,enableScreenAfterBoot 内的重跑现场,注意与紧随其后的门 3 判定的时间关系):

11-05 10:48:54.031  BootFlow3: [PWP-systemBooted] display ON/turning-on (state=2, listener=false): RE-RUNNING screenTurningOn + screenTurnedOn (may reset DDP draw-complete state!)
11-05 10:48:54.031  BootFlow3: [DP] screenTurnedOn: NEW screen-on cycle, RESET state ... thread=android.ui   ← 标志被清零
11-05 10:48:54.031  BootFlow3: [PWP-screenTurningOn] hasKeyguard()=false: immediate ... (fast path)         ← 1ms 内补回
11-05 10:48:54.032  BootFlow5: [enableScreen#1] enter: ... canDismissBootAnimation=true ...                 ← 查门 3 时已恢复

健康机:fast path 在 1 毫秒内把 keyguardDrawComplete 补回 true,门 3 没被挡。若恰好在"清零 → 补回"的这 1 毫秒窗口内查询门 3,就会命中竞争(案例 1 即如此,见第 9.1 节)。

6.6 canDismissBootAnimation:门 3 的判据

public boolean canDismissBootAnimation() {
    // Allow to dismiss the boot animation if the keyguard has finished drawing,
    // or mBootAnimationDismissable has been set
    final String key = "debug.sf.nobootanimation";
    if (SystemProperties.getInt(key, 0) == 1) {
        return true;                                   // 调试开关:直接放行
    }
    final boolean keyguardDrawn = mDefaultDisplayPolicy.isKeyguardDrawComplete();
    if (!(keyguardDrawn || mBootAnimationDismissable)) {
        // ── 插桩日志(BootFlow5):只在"挡路"时打,给出分解值 ──
        Slog.i("BootFlow5", "[canDismissBootAnimation] BLOCKING: isKeyguardDrawComplete=false"
                + " mBootAnimationDismissable=false"
                + " screenOnEarly=" + mDefaultDisplayPolicy.isScreenOnEarly()
                + " awake=" + mDefaultDisplayPolicy.isAwake());
    }
    return keyguardDrawn || mBootAnimationDismissable;
}

7. 第五幕:终局(WindowManagerService 五道门)

文件:services/core/java/com/android/server/wm/WindowManagerService.java

调用链位置(见 2.1) :上游 enableScreenAfterBoot 由 AMS 链调用:AMS.ensureBootCompleted → ActivityTaskSupervisor.enableScreenAfterBoot(⑤,同进程直调)。performEnableScreen 有四个重入入口(见 2.2 表格)。下游它调用:mPolicy.systemBooted(PWP,⑤)、SurfaceControl.bootFinished(SurfaceFlinger,⑧)、mActivityManager.bootAnimationComplete(AMS,⑧)、setEventDispatchingLw(输入分发终点)。

7.1 触发者:AMS 的 ensureBootCompleted

// ActivityManagerService.java
final void ensureBootCompleted() {
    boolean booting;
    boolean enableScreen;
    synchronized (this) {
        booting = mBooting;
        mBooting = false;
        enableScreen = !mBooted;
        mBooted = true;
    }
    if (booting) {
        finishBooting();                       // 发出 BOOT_COMPLETED 等
    }
    if (enableScreen) {
        mAtmInternal.enableScreenAfterBoot(mBooted);   // ★ 进入 WMS 链路
    }
}

7.2 enableScreenAfterBoot:挂 30 秒兜底

public void enableScreenAfterBoot() {
    // ── 插桩日志(BootFlow5):30 秒计时起点 ──
    Slog.i("BootFlow5", "[enableScreen] enableScreenAfterBoot enter: mDisplayEnabled="
            + mDisplayEnabled + " mSystemBooted=" + mSystemBooted
            + " thread=" + Thread.currentThread().getName());
    synchronized (mGlobalLock) {
        if (mSystemBooted) {
            // ── 插桩日志(BootFlow5):重复调用,不再挂定时器 ──
            Slog.i("BootFlow5", "[enableScreen] enableScreenAfterBoot: mSystemBooted already true,"
                    + " return (no timer armed)");
            return;
        }
        mSystemBooted = true;
        hideBootMessagesLocked();
        // If the screen still doesn't come up after 30 seconds, give
        // up and turn it on.
        mH.sendEmptyMessageDelayed(H.BOOT_TIMEOUT, 30 * 1000);   // ★ 30 秒兜底
        // ── 插桩日志(BootFlow5):兜底定时器挂上 ──
        Slog.i("BootFlow5", "[enableScreen] BOOT_TIMEOUT armed (+30s), uptimeMs="
                + SystemClock.uptimeMillis());
    }
​
    mPolicy.systemBooted();      // 第六幕 4.5 的"重跑"就发生在这里
    performEnableScreen();
}

日志指纹:boot_progress_enable_screen: NNNNN(NNNNN = uptime 毫秒)打在进入此函数时;BOOT_TIMEOUT armed (+30s) 是我们插桩加的对应标记。

真机日志实录(健康机,30 秒计时起点):

11-05 10:48:54.027  boot_progress_enable_screen: 21361
11-05 10:48:54.027  BootFlow5: [enableScreen] enableScreenAfterBoot enter: mDisplayEnabled=false mSystemBooted=false thread=android.ui
11-05 10:48:54.030  BootFlow5: [enableScreen] BOOT_TIMEOUT armed (+30s), uptimeMs=21364

boot_progress_enable_screen 是 events 常开日志(无需插桩),与插桩的 enableScreenAfterBoot enter 同毫秒出现——它就是"30 秒死区"的计时零点。

7.3 performEnableScreen:五道门逐行拆解

// ── 插桩字段:每次进入自增,生成 enableScreen#N 序号 ──
private int mEnableScreenDebugSeq = 0;
​
private void performEnableScreen() {
    final int dbgSeq = ++mEnableScreenDebugSeq;
    final long dbgStart = SystemClock.elapsedRealtime();
    // ── 插桩日志(BootFlow5):入口快照,所有门控判据一次打全 ──
    Slog.i("BootFlow5", "[enableScreen#" + dbgSeq + "] enter: mDisplayEnabled=" + mDisplayEnabled
            + " mForceDisplayEnabled=" + mForceDisplayEnabled
            + " mSystemBooted=" + mSystemBooted
            + " mShowingBootMessages=" + mShowingBootMessages
            + " mBootAnimationStopped=" + mBootAnimationStopped
            + " canDismissBootAnimation=" + mPolicy.canDismissBootAnimation()
            + " bootanimExit=" + SystemProperties.get("service.bootanim.exit")
            + " bootanimSvc=" + SystemProperties.get("init.svc." + BOOT_ANIMATION_SERVICE)
            + " thread=" + Thread.currentThread().getName());
    synchronized (mGlobalLock) {
        // ── 门 1:已经使能过 ──
        if (mDisplayEnabled) {
            Slog.i("BootFlow5", "[enableScreen#" + dbgSeq + "] exit@GATE1: already enabled");
            return;
        }
        // ── 门 2:系统还没 boot 完 ──
        if (!mSystemBooted && !mShowingBootMessages) {
            Slog.i("BootFlow5", "[enableScreen#" + dbgSeq + "] exit@GATE2:"
                    + " !mSystemBooted && !mShowingBootMessages");
            return;
        }
        // ── 门 3:keyguard 还没画完 ──
        if (!mShowingBootMessages && !mPolicy.canDismissBootAnimation()) {
            Slog.i("BootFlow5", "[enableScreen#" + dbgSeq + "] exit@GATE3:"
                    + " canDismissBootAnimation()=false"
                    + " (decomposition in [canDismissBootAnimation] log)");
            return;
        }
        // ── 门 4:系统装饰窗还没画完 ──
        if (!mForceDisplayEnabled) {
            if (mBootWaitForWindowsStartTime < 0) {
                mBootWaitForWindowsStartTime = SystemClock.elapsedRealtime();
            }
            for (int i = mRoot.getChildCount() - 1; i >= 0; i--) {
                DisplayContent dbgDc = mRoot.getChildAt(i);
                if (dbgDc.shouldWaitForSystemDecorWindowsOnBoot()) {
                    // ── 插桩日志(BootFlow5):门 4 挡住,打印等待时长 ──
                    Slog.i("BootFlow5", "[enableScreen#" + dbgSeq + "] exit@GATE4: displayId="
                            + dbgDc.getDisplayId()
                            + " waiting for system decor windows, waitedMs="
                            + (SystemClock.elapsedRealtime()
                                    - mBootWaitForWindowsStartTime));
                    // ── 插桩日志(BootFlow5):枚举未画完的窗口,直接点名 ──
                    dbgDc.forAllWindows(w -> {
                        if (!w.isDrawn()) {
                            Slog.i("BootFlow5", "[enableScreen#" + dbgSeq + "] GATE4 undrawn window:"
                                    + " name=" + w.getName()
                                    + " hasSurface=" + w.mHasSurface
                                    + " viewVisibility=0x"
                                    + Integer.toHexString(w.mViewVisibility));
                        }
                        return false;
                    }, true /* traverseTopToBottom */);
                    return;    // 状态栏/导航栏等装饰窗未 drawn
                }
            }
            long waitTime = SystemClock.elapsedRealtime() - mBootWaitForWindowsStartTime;
            mBootWaitForWindowsStartTime = -1;
            if (waitTime > 10) {
                ProtoLog.i(WM_DEBUG_BOOT,
                        "performEnableScreen: Waited %dms for all windows to be drawn",
                        waitTime);
                // ── 插桩日志(BootFlow5):门 4 通过 ──
                Slog.i("BootFlow5", "[enableScreen#" + dbgSeq + "] GATE4 passed, waited "
                        + waitTime + "ms");
            }
        }
        // ── 过门:通知动画退出 ──
        if (!mBootAnimationStopped) {
            // ── 插桩日志(BootFlow5):全部门通过,发出退出请求 ──
            Slog.i("BootFlow5", "[enableScreen#" + dbgSeq + "] all gates passed,"
                    + " setting service.bootanim.exit=1");
            Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER, "Stop bootanim", 0);
            SystemProperties.set("service.bootanim.exit", "1");   // ★ BootAnimation 轮询的属性
            mBootAnimationStopped = true;
        }
        // ── 门 5:等动画进程真正退出 ──
        if (!mForceDisplayEnabled && !checkBootAnimationCompleteLocked()) {
            // ── 插桩日志(BootFlow5):动画进程还在跑 ──
            Slog.i("BootFlow5", "[enableScreen#" + dbgSeq + "] exit@GATE5:"
                    + " bootanimation process still running");
            return;
        }
        // ── SurfaceFlinger 收尾 ──
        if (!SurfaceControl.bootFinished()) {
            ProtoLog.w(WM_ERROR, "performEnableScreen: bootFinished() failed.");
            // ── 插桩日志(BootFlow5):SF 收尾失败 ──
            Slog.w("BootFlow5", "[enableScreen#" + dbgSeq + "] exit@BOOTFINISH:"
                    + " SurfaceControl.bootFinished() failed");
            return;
        }
​
        EventLogTags.writeWmBootAnimationDone(SystemClock.uptimeMillis());
        Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER, "Stop bootanim", 0);
        mDisplayEnabled = true;
        // ── 插桩日志(BootFlow7):通关!打印耗时与分发标志 ──
        Slog.i("BootFlow7", "[enableScreen#" + dbgSeq + "] SUCCESS: mDisplayEnabled=true,"
                + " took " + (SystemClock.elapsedRealtime() - dbgStart) + "ms,"
                + " mEventDispatchingEnabled=" + mEventDispatchingEnabled);
​
        // Enable input dispatch.  ★ 全流程终点:输入分发打开
        mInputManagerCallback.setEventDispatchingLw(mEventDispatchingEnabled);
        // ── 插桩日志(BootFlow7):输入分发使能动作已下发 ──
        Slog.i("BootFlow7", "[enableScreen#" + dbgSeq + "] INPUT DISPATCH ENABLED (touch ready)");
    }
​
    try {
        mActivityManager.bootAnimationComplete();   // 回告 AMS,触发 finishBooting
    } catch (RemoteException e) {
    }
​
    mPolicy.enableScreenAfterBoot();
    updateRotationUnchecked(false, false);
    ...
}

逐门解读:

  • 门 1:纯幂等保护,正常到达一次后整条链不再重复执行;
  • 门 2:mSystemBooted 在 enableScreenAfterBoot 里才置 true。任何更早到达的 enableScreenIfNeeded() 请求都会在这里被浪费——健康机日志里大量 enableScreenIfNeeded SKIPPED ... retrigger wasted 就是这个;
  • 门 3:判据见 6.6。!mShowingBootMessages 保证开机提示框场景不被挡;
  • 门 4:shouldWaitForSystemDecorWindowsOnBoot() 检查状态栏/导航栏等系统装饰窗是否全部 isDrawn()(有 surface 且首帧已提交)。挡住时没有任何轮询,只能靠外部触发重入;
  • service.bootanim.exit=1 在门 4 之后才设置——所以"bootanimExit 一直为 0"等价于"从未越过门 4";
  • 门 5:checkBootAnimationCompleteLocked() 检查 bootanim 进程是否还活着,而不是属性。这是本流程的第二层异步等待;
  • SurfaceControl.bootFinished() 通知 SurfaceFlinger(见第八幕);
  • 最后一行 setEventDispatchingLw() —— 输入分发使能的唯一入口。

真机日志实录——成功案例(健康机,一次通关):

11-05 10:48:54.032  BootFlow5: [enableScreen#1] enter: mDisplayEnabled=false mForceDisplayEnabled=false mSystemBooted=true mShowingBootMessages=false mBootAnimationStopped=false canDismissBootAnimation=true bootanimExit=0 bootanimSvc=stopped thread=android.ui
11-05 10:48:54.032  BootFlow5: [enableScreen#1] all gates passed, setting service.bootanim.exit=1
11-05 10:48:54.061  BootFlow7: [enableScreen#1] SUCCESS: mDisplayEnabled=true, took 30ms, mEventDispatchingEnabled=false
11-05 10:48:54.061  BootFlow7: [enableScreen#1] INPUT DISPATCH ENABLED (touch ready)

enter 行是一次完整快照:bootanimSvc=stopped → 门 5 必过;canDismissBootAnimation=true → 门 3 必过。于是无任何 exit@GATE,直接 all gates passed,30ms 后 SUCCESS。

健康机一次通关,五道门的出口日志(exit@GATE1~5)一次都没触发。这些出口被挡时的完整门控序列(exit@GATE3 → GATE4 → GATE5 → BOOT_TIMEOUT)见第 9.1 节案例 1。

7.4 门 5 的轮询实现

private boolean checkBootAnimationCompleteLocked() {
    if (SystemService.isRunning(BOOT_ANIMATION_SERVICE)) {   // "bootanim"
        // ── 插桩日志(BootFlow5):动画进程还在,安排下一次轮询 ──
        Slog.i("BootFlow5", "[enableScreen] GATE5: bootanimation service still running,"
                + " re-poll in " + BOOT_ANIMATION_POLL_INTERVAL + "ms");
        mH.removeMessages(H.CHECK_IF_BOOT_ANIMATION_FINISHED);
        mH.sendEmptyMessageDelayed(H.CHECK_IF_BOOT_ANIMATION_FINISHED,
                BOOT_ANIMATION_POLL_INTERVAL);               // 200ms(旧版 50ms)
        ProtoLog.i(WM_DEBUG_BOOT, "checkBootAnimationComplete: Waiting for anim complete");
        return false;
    }
    ProtoLog.i(WM_DEBUG_BOOT, "checkBootAnimationComplete: Animation complete!");
    return true;
}

Handler 里的轮询回调:

case CHECK_IF_BOOT_ANIMATION_FINISHED: {
    final boolean bootAnimationComplete;
    synchronized (mGlobalLock) {
        ProtoLog.i(WM_DEBUG_BOOT, "CHECK_IF_BOOT_ANIMATION_FINISHED:");
        bootAnimationComplete = checkBootAnimationCompleteLocked();
    }
    if (bootAnimationComplete) {
        performEnableScreen();    // 动画退干净了,重入一次
    }
    break;
}

健康机为什么门 5 秒过:enableScreen#1 的入口快照显示 bootanimSvc=stopped——动画进程在开机 6.7 秒已被 init 强杀(见第 3 幕),isRunning("bootanim") 直接为 false,一次轮询都不需要。若进程迟迟不退,[enableScreen] GATE5: bootanimation service still running 会每 200ms 打一次(完整空转现场见第 9.1 节案例 1)。

7.5 30 秒兜底与重入入口

public void performBootTimeout() {
    synchronized (mGlobalLock) {
        if (mDisplayEnabled) {
            return;
        }
        ProtoLog.w(WM_ERROR, "***** BOOT TIMEOUT: forcing display enabled");
        // ── 插桩日志(BootFlow5):30 秒兜底触发,打印当时状态 ──
        Slog.w("BootFlow5", "[enableScreen] BOOT_TIMEOUT fired after 30s!"
                + " canDismissBootAnimation=" + mPolicy.canDismissBootAnimation()
                + " mBootAnimationStopped=" + mBootAnimationStopped
                + " -> forcing mForceDisplayEnabled=true");
        mForceDisplayEnabled = true;      // ★ 强制标志
    }
    performEnableScreen();
}

mForceDisplayEnabled=true 的效果:门 4 的 if (!mForceDisplayEnabled) 和门 5 的 if (!mForceDisplayEnabled && ...) 双双跳过——跳过等待,强行通关。

其余两个重入入口:

case ENABLE_SCREEN: {
    performEnableScreen();
    break;
}
void enableScreenIfNeededLocked() {
    if (mDisplayEnabled) {
        return;
    }
    if (!mSystemBooted && !mShowingBootMessages) {
        // ── 插桩日志(BootFlow5):救场请求被门 2 浪费 ──
        Slog.i("BootFlow5", "[enableScreen] enableScreenIfNeeded SKIPPED:"
                + " system not booted yet (retrigger wasted at uptimeMs="
                + SystemClock.uptimeMillis() + ")");
        return;     // 门 2 的孪生判断 —— 浪费救场机会的地方
    }
    // ── 插桩日志(BootFlow5):救场请求生效,重入 performEnableScreen ──
    Slog.i("BootFlow5", "[enableScreen] enableScreenIfNeeded -> posting ENABLE_SCREEN");
    mH.sendEmptyMessage(H.ENABLE_SCREEN);
}

enableScreenIfNeeded() 是谁调的:PWP 的 enableScreen()(受 mKeyguardDrawnOnce 门锁保护,见 6.4)和 RootWindowContainer 的 surface 布局钩子。两个来源都不是可靠的"重试机制"——前者一次性,后者视实现而定。

真机日志实录(健康机,救场请求被门 2 浪费的现场):

11-05 10:48:47.281  BootFlow5: [enableScreen] enableScreenIfNeeded SKIPPED: system not booted yet (retrigger wasted at uptimeMs=14614)
11-05 10:48:47.281  BootFlow5: [enableScreen] enableScreenIfNeeded SKIPPED: system not booted yet (retrigger wasted at uptimeMs=14615)
11-05 10:48:48.516  BootFlow5: [enableScreen] enableScreenIfNeeded SKIPPED: system not booted yet (retrigger wasted at uptimeMs=15864)
...(开机 20 秒内出现十余次,全部被"系统未 boot"挡掉,直到 enableScreenAfterBoot 亲自进场)

7.6 mEventDispatchingEnabled 的维护

final InputManagerCallback mInputManagerCallback = new InputManagerCallback(this);
private boolean mEventDispatchingEnabled;
​
@Override
public void setEventDispatching(boolean enabled) {
    if (!checkCallingPermission(MANAGE_APP_TOKENS, "setEventDispatching()")) {
        throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
    }
    synchronized (mGlobalLock) {
        mEventDispatchingEnabled = enabled;
        if (mDisplayEnabled) {
            mInputManagerCallback.setEventDispatchingLw(enabled);   // 立即下发
        }
    }
}

注意:performEnableScreen() 最后一行只是把当前的 mEventDispatchingEnabled 下发。案例 3(1.log)中 SUCCESS 时刻该值为 false,真正打开输入分发是之后 256ms 由另一条路径把值置 true 并下发——所以"INPUT DISPATCH ENABLED"日志只能证明"下发动作发生了",参数值要另看。

真机日志实录(健康机,分发真正打开的时刻——SUCCESS 后 256ms,由另一条路径下发):

11-05 10:48:54.317  InputDispatcher: setInputDispatchMode: enabled=1, frozen=0

8. 第六幕:SurfaceFlinger 与输入分发使能

文件:frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp

调用链位置(见 2.1) :SurfaceFlinger::bootFinished 由 WMS 的 SurfaceControl.bootFinished() 经 native→binder 调用(⑧ 门 5 之后);它置 sys.boot_completed、再置一次 service.bootanim.exit(该属性被 bootanimation 进程轮询,见 ①)、打 sf_stop_bootanim 事件。输入分发由 WMS 的 setEventDispatchingLw 打开,真机体现为 setInputDispatchMode: enabled=1。

8.1 SurfaceFlinger::bootFinished

void SurfaceFlinger::bootFinished() {
    if (mBootFinished == true) {
        ALOGE("Extra call to bootFinished");
        return;
    }
    mBootFinished = true;
    if (mStartPropertySetThread->join() != NO_ERROR) {
        ALOGE("Join StartPropertySetThread failed!");
    }
    if (mRenderEnginePrimeCacheFuture.valid()) {
        mRenderEnginePrimeCacheFuture.get();
    }
    const nsecs_t now = systemTime();
    const nsecs_t duration = now - mBootTime;
    ALOGI("Boot is finished (%ld ms), realtime is (%lld ms)",
          long(ns2ms(duration)), (long long)android::elapsedRealtime());
​
    mFrameTracer->initialize();
    mFrameTimeline->onBootFinished();
    getRenderEngine().setEnableTracing(mFlagManager.use_skia_tracing());
​
    // wait patiently for the window manager death
    const String16 name("window");
    mWindowManager = defaultServiceManager()->getService(name);
    if (mWindowManager != 0) {
        mWindowManager->linkToDeath(...);
    }
​
    // stop boot animation
    // formerly we would just kill the process, but we now ask it to exit so it
    // can choose where to stop the animation.
    property_set("service.bootanim.exit", "1");       // ★ 双保险:SF 侧再置一次
​
    const int LOGTAG_SF_STOP_BOOTANIM = 60110;
    LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,            // ← 产生 sf_stop_bootanim 事件日志
                   ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
    ...
}

要点:service.bootanim.exit=1 有两处设置——WMS 门 4 之后(请动画进程自己退)和 SF bootFinished 里(双保险)。sf_stop_bootanim 事件日志产自 SF,因此它的出现时刻 = SurfaceControl.bootFinished() 被调用的时刻 = 门 5 通过的时刻。这正是用 events 日志定位断点的依据。

真机日志实录(健康机,sf_stop_bootanim 与 wm_boot_animation_done 紧挨出现,门 5 通过、正常通关):

11-05 10:48:54.054  sf_stop_bootanim: 21388
11-05 10:48:54.055  wm_boot_animation_done: 21389

判读:sf_stop_bootanim(21388)距 boot_progress_enable_screen(21361)仅 27ms——全程正常链路,未走兜底。若两者相差约 30 秒,说明 30 秒兜底被触发(案例 1 的兜底时刻现场见第 9.1 节)。

8.2 输入分发使能(WMS 侧终点)

// WindowManagerService.java — performEnableScreen 的最后一行
mInputManagerCallback.setEventDispatchingLw(mEventDispatchingEnabled);

在真机上体现为:

InputDispatcher: setInputDispatchMode: enabled=1, frozen=0

日志指纹对照:

events / main 日志含义
boot_progress_enable_screen: NenableScreenAfterBoot 进入,30 秒计时开始
wm_boot_animation_done: NperformEnableScreen 通关(写事件)
sf_stop_bootanim: NSurfaceControl.bootFinished 被调
screen_toggled: 1屏幕点亮状态切换
InputDispatcher: Dropped event because input dispatch is disabled.输入分发关闭期间的事件丢弃(触摸无效的实锤)
InputDispatcher: setInputDispatchMode: enabled=1分发真正打开

健康指纹:sf_stop_bootanim 应出现在 boot_progress_enable_screen 之后 1~2 秒内;两者相差 30.000 秒 = 走了兜底,链路有断点。


9. 三个真实案例对照

9.1 案例 1:恢复出厂后的 30 秒死区(Android 10,问题机)

关键日志时间线(uptime 换算):

14:46:19.425  MasterClear: !!! FACTORY RESET !!!
14:46:37.590  内核二次启动
14:47:55.243  screenTurningOn:hasKeyguard()=true     ← bind 还没跑,默认假设有锁屏
              → "no keyguard service!"(回调被暂存)→ 5 秒超时开始
14:47:57.821  bind FAILED(组件不存在)→ deviceHasKeyguard=false ← 晚了 2.5 秒
14:48:00.244  Keyguard drawn timeout(5 秒超时兜底)
14:48:10.414  boot_progress_enable_screen → 30 秒定时器挂上
14:48:17.8~40.2  用户 40+ 次点击:内核全收到,InputDispatcher 全丢弃
14:48:40.414  BOOT TIMEOUT: forcing display enabled   ← 恰好 +30.000s
14:48:40.416  sf_stop_bootanim
14:48:42.816  第一次有效点击;14:48:51 弹窗按钮被点中

插桩后的门控序列(Q 版,另一份日志):

#1  exit@GATE3: canDismissBootAnimation()=false   ← systemBooted 重跑清掉了标志
#2~#6 exit@GATE4: undrawn window: com.adayo.app.systemui(状态栏还没画完)
#7  all gates passed, setting service.bootanim.exit=1
#8~#29 exit@GATE5: bootanimation process still running   ← 动画进程不退,29 秒!
#30 SUCCESS(被 BOOT_TIMEOUT 强制)

死因链:keyguard 组件不存在(5 秒白等)→ systemBooted 重跑亮屏链引发 GATE3 竞争(1 秒)→ 状态栏未画完挡 GATE4(几百毫秒)→ bootanimation.zip 被压缩打包导致动画进程退出异常,堵死 GATE5 达 29 秒 → 30 秒兜底强制通关。三层问题叠加,每一层都在"消耗"那个一次性设计。

9.2 案例 2:同版本"正常开机"为什么也超时(7.log)

uptime 12.0s  screenTurningOn: no keyguard service(竞争只输 0.27 秒)
uptime 14.1s  状态栏 addWindow(比 enable_screen 早 6 秒!门 4 不可能挡)
uptime 20.4s  boot_progress_enable_screen
uptime 51.0s  BOOT TIMEOUT(+30.000s 整)

状态栏早已就绪、keyguard 超时也已兜底,却依然精确 +30 秒——说明卡点不在"哪道门没过",而在 "过了也没人重跑" :一次性设计 + mKeyguardDrawnOnce 门锁 + 重跑竞争,让每次开机都只能等兜底。只是没人开机就点屏,症状从未被看见。

9.3 案例 3:健康机(Android 14,1.log)

uptime ~14600  首次亮屏 hasKeyguard=true(仍输竞争,但无关大局)
uptime ~15477  Viewport 激活,触摸屏关联恢复
uptime ~17151  KSD bindService: credentialType=-1(NONE)
               → SKIP bind → deviceHasKeyguard=false(好路径)
uptime 21361   boot_progress_enable_screen → BOOT_TIMEOUT armed
uptime 21364   systemBooted 重跑 → hasKeyguard=false → fast path
uptime ~21370  enableScreen#1: canDismiss=true, bootanimSvc=stopped
               → all gates passed → bootanim.exit=1
uptime 21388   sf_stop_bootanim
uptime 21391   SUCCESS: took 30ms
uptime ~21647  setInputDispatchMode: enabled=1

为什么这台健康:① 无锁屏判定提前生效(credentialType=NONE → SKIP bind),重跑时走 fast path;② bootanimation 进程在开机 6.7 秒就被 init SIGKILL(SIGNAL_TRACE: sig=9 sender_pid=1 target_pid=386),门 5 检查时服务已是 stopped,秒过;③ 全链 30ms 完成,30 秒兜底从未触发。

遗留观察:SUCCESS 时 mEventDispatchingEnabled=false,输入真正打开在 256ms 后——"画面亮了"与"输入可用"之间仍有微小时间窗,精确以 setInputDispatchMode: enabled=1 为准。

一次通关的完整日志实录:

11-05 10:48:54.027  BootFlow5: [enableScreen] enableScreenAfterBoot enter: mDisplayEnabled=false mSystemBooted=false thread=android.ui
11-05 10:48:54.030  BootFlow5: [enableScreen] BOOT_TIMEOUT armed (+30s), uptimeMs=21364
11-05 10:48:54.031  BootFlow3: [PWP-systemBooted] display ON/turning-on ... RE-RUNNING screenTurningOn ...
11-05 10:48:54.031  BootFlow3: [PWP-screenTurningOn] hasKeyguard()=false: immediate MSG_KEYGUARD_DRAWN_COMPLETE (fast path)
11-05 10:48:54.032  BootFlow5: [enableScreen#1] enter: ... canDismissBootAnimation=true ... bootanimSvc=stopped ...
11-05 10:48:54.032  BootFlow5: [enableScreen#1] all gates passed, setting service.bootanim.exit=1
11-05 10:48:54.061  BootFlow7: [enableScreen#1] SUCCESS: mDisplayEnabled=true, took 30ms
11-05 10:48:54.061  BootFlow7: [enableScreen#1] INPUT DISPATCH ENABLED (touch ready)

9.4 三案例对照表

环节案例 1(死区)案例 2(隐性死区)案例 3(健康)
keyguard 组件不存在,bind 失败不存在,bind 失败不存在但 SKIP bind(无凭据判定提前)
首次亮屏竞争输 2.5s输 0.27s输 2.1s(无害)
门 3 竞争命中,挡 1 次命中未命中(hasKeyguard 已 false)
门 4状态栏晚到,挡几百 ms状态栏早到,不挡不挡
门 5bootanim 不退,挡 29s同左bootanim 已被 kill,秒过
BOOT_TIMEOUT触发(每次)触发(每次)从未触发
触摸可用开机后 ~50s开机后 ~50s开机后 ~21.7s

10.3 BootFlow 插桩方案(需要区分"哪道门"时)

按流程阶段编号的 tag,logcat -s BootFlow1 ... BootFlow7 一把抓全:

Tag阶段
BootFlow1开机动画进程(加载/循环)
BootFlow2keyguard 绑定判定
BootFlow3亮屏/keyguard 绘制链
BootFlow4windows drawn/完全点亮
BootFlow5performEnableScreen 五道门
BootFlow6动画退出握手
BootFlow7成功/输入分发使能

核心插桩点(五处,前文已全部给出过代码模板):

  1. WMS.performEnableScreen:入口打全量状态快照,五个 return 前分别打 exit@GATE1~5;门 4 处枚举未画完窗口(name/hasSurface/viewVisibility);
  2. WMS.enableScreenIfNeededLocked / performBootTimeout / enableScreenAfterBoot:记录被浪费的重试、30 秒计时起止;
  3. PWP.finishKeyguardDrawn / finishWindowsDrawn / finishScreenTurningOn / enableScreen:每个 TRUE/FALSE 分支 + mKeyguardDrawnOnce 门锁消费;
  4. DisplayPolicy 四个状态函数:每次重置与幂等拒绝;
  5. BootAnimation.checkExit:每次轮询读到的属性值(排"收到 exit 不退出")。

判读口诀:数字停在几,断点就在几(详见第 9 节案例日志)。

10.4 关键日志指纹速查

日志结论
bootanimation.zip is compressed; must be only stored动画 zip 打包错误,门 5 高危
Unable to start service ... KeyguardService ... not foundkeyguard 组件缺失,5 秒白等
no keyguard service!亮屏早于 bind 判定(竞争窗口开放)
Keyguard drawn timeout. Setting mKeyguardDrawComplete5 秒超时兜底触发
Dropped event because input dispatch is disabled输入分发关闭,触摸必然无效
***** BOOT TIMEOUT: forcing display enabled30 秒兜底触发(正常链路已坏)
sf_stop_bootanim 距 boot_progress_enable_screen ≈30.000s全程靠兜底通关

10. 修复清单(按收益排序)

  1. 修 bootanimation.zip:必须 STORE 打包(zip -0 -r)。案例 1 的 29 秒死等直接消失,收益最大;
  2. 无锁屏判定提前:让 bindService() 在首次亮屏前完成(把 PWP 的 bindKeyguard 触发点提前,或像健康机那样保证 credentialType=NONE 的 SKIP 路径尽早生效),消灭前 5 秒与 GATE3 竞争;
  3. 给 performEnableScreen 加周期重试:门 3/门 4 被挡时 500ms 后重发 ENABLE_SCREEN,而不是静默 return——一次性设计 + 状态重置竞争的坑被结构性绕过;
if (!mShowingBootMessages && !mPolicy.canDismissBootAnimation()) {
    if (!mH.hasMessages(H.ENABLE_SCREEN)) {
        mH.sendEmptyMessageDelayed(H.ENABLE_SCREEN, 500);   // 自愈式重试
    }
    return;
}
  1. 门 5 加轮询上限(兜底保险):bootanim 进程累计 N 秒不退出即视为完成并告警,防止"进程僵死"再次拖满 30 秒;
  2. 可选的流程洁癖:让 systemBooted() 重跑亮屏链时不重置 keyguardDrawComplete(在 DisplayPolicy 侧区分"首次亮屏"与"重跑")。

验收标准:任意一次开机,以下五条日志一次都不出现:

BOOT TIMEOUT / Keyguard drawn timeout / no keyguard service
must be only stored / Dropped event because input dispatch is disabled

且 sf_stop_bootanim 出现在 boot_progress_enable_screen 之后 1~2 秒内。


11. 总结

这条链路的本质是一次精心编排的握手:开机动画(播放方)、keyguard(锁屏画完)、状态栏导航栏(装饰窗画完)、SurfaceFlinger(渲染收尾)四方依次"报告完成",最后才把屏幕使能并打开输入分发。设计上每一环都有兜底(5 秒 keyguard 超时、30 秒 BOOT TIMEOUT),但兜底之间的衔接却依赖几个"一次性"机制(performEnableScreen 的有效执行次数、mKeyguardDrawnOnce 门锁、门 5 的轮询启动条件),任何一个时序竞争撞上它们,就会把"保底"变成"必经之路"。

排查这类问题的通用方法论:先看 events 三件套定段(enable_screen → sf_stop_bootanim 的时间差),再用门控日志定位到具体 return,最后用 dumpsys/property 确认该门控的判据卡在哪个对象(哪个窗口未 drawn、哪个进程未退出)。文中的 BootFlow 插桩方案把这三步压缩成一条 logcat 命令,数字停在几,断点就在几。

记住两个最容易踩的坑:车机无锁屏不等于 framework 知道无锁屏(要让它提前判定并 SKIP bind),bootanimation.zip 必须 STORE 打包(压缩打包会以"进程不退"的形式把门 5 堵到 30 秒兜底)。