Android 8.1 启动流程详解:从 Zygote 到 SystemUI 到底经历了什么

1 阅读8分钟

1. 引言

很多人对 Android 启动的认知停留在「按下电源键 → 出现开机动画 → 进入桌面」这个黑盒过程。但如果要排查开机慢、黑屏、SystemUI 崩溃、开机动画卡死这类问题,就必须搞清楚从内核启动到 SystemUI 显示出来的完整链路。

本文以 Android 8.1(Oreo MR1) 为基准,聚焦于 Zygote 启动之后到 SystemUI 进程被拉起并显示界面 这一段流程,把 init、Zygote、SystemServer、AMS、PMS、WMS、SystemUI 之间的调用关系串起来。

说明:不同厂商 ROM 会在这一链路上做定制(尤其是 SystemUI 的启动时机与开机动画的退出时机),本文以 AOSP 主线代码为准。

2. 起点:init 进程拉起 Zygote

2.1 init.rc 中的 zygote 服务定义

Android 8.1 中 Zygote 由 init 通过 rc 文件启动,定义在 system/core/rootdir/init.zygote32.rc(这里存在多个init.zygote是由于系统支持64/32位导致,分析32位即可):

service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server
class main
priority -20
user root
group root readproc
socket zygote stream 660 root system
onrestart write /sys/android_power/request_state wake
onrestart write /sys/power/state on
onrestart restart audioserver
onrestart restart cameraserver
onrestart restart media
onrestart restart netd
onrestart restart wificond
writepid /dev/cpuset/foreground/tasks

几个关键点:

  • --zygote:告诉 app_process 走 Zygote 分支,而不是普通 Java 程序。
  • --start-system-server:Zygote 初始化完成后要 fork 出 SystemServer。
  • socket zygote stream 660 root system:创建名为 zygote 的 Unix Domain Socket,这是后续 AMS 请求 fork 应用的通道。

2.2 app_process 到 ZygoteInit

app_process 的 main 函数在 frameworks/base/cmds/app_process/app_main.cpp,最终会调用到 AndroidRuntime::start,再反射调用 com.android.internal.os.ZygoteInit.main:

// frameworks/base/cmds/app_process/app_main.cpp
int main(int argc, char* const argv[])
{
      //省略部分
    AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv));//进行AppRuntime的构造
    // Process command line arguments
    // ignore argv[0]
    argc--;
    argv++;
  //省略。。。
    bool zygote = false;
    bool startSystemServer = false;
    bool application = false;
    String8 niceName;
    String8 className;

    ++i;  // Skip unused "parent dir" argument.
    while (i < argc) {
        const char* arg = argv[i++];
        if (strcmp(arg, "--zygote") == 0) {
            zygote = true;//变量zygote设置
            niceName = ZYGOTE_NICE_NAME;
        } else if (strcmp(arg, "--start-system-server") == 0) {
            startSystemServer = true;
        } else if (strcmp(arg, "--application") == 0) {
            application = true;
        } else if (strncmp(arg, "--nice-name=", 12) == 0) {
            niceName.setTo(arg + 12);
        } else if (strncmp(arg, "--", 2) != 0) {
            className.setTo(arg);
            break;
        } else {
            --i;
            break;
        }
    }
	//省略
    Vector<String8> args;
    if (!className.isEmpty()) {
	//省略
        runtime.setClassNameAndArgs(className, argc - i, argv + i);
	//省略
    } else {//省略}

    if (!niceName.isEmpty()) {
        runtime.setArgv0(niceName.string(), true /* setProcName */);
    }

    if (zygote) {
    	//进入这里进行java类的启动
        runtime.start("com.android.internal.os.ZygoteInit", args, zygote);
    } else if (className) {
        runtime.start("com.android.internal.os.RuntimeInit", args, zygote);
    } else {
        fprintf(stderr, "Error: no class name or --zygote supplied.\n");
        app_usage();
        LOG_ALWAYS_FATAL("app_process: no class name or --zygote supplied.");
    }

// frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
public static void main(String argv[]) {
    ZygoteServer zygoteServer = new ZygoteServer();

    // 1. 标记当前线程为可被 SIGCHLD 唤醒
    ZygoteHooks.startZygoteNoThreadCreation();

    try {
        // 2. 解析参数,判断是否 start-system-server
        boolean startSystemServer = false;
        String socketName = "zygote";
        for (int i = 1; i < argv.length; i++) {
            if ("start-system-server".equals(argv[i])) {
                startSystemServer = true;
            } else if (argv[i].startsWith(SOCKET_NAME_ARG)) {
                socketName = argv[i].substring(SOCKET_NAME_ARG.length());
            }
        }

        // 3. 注册 Socket,供 AMS 后续请求 fork
        zygoteServer.registerServerSocket(socketName);

        // 4. 预加载资源(classes / resources / text resources)
        preload();

        // 5. fork 出 SystemServer
        if (startSystemServer) {
            Runnable r = forkSystemServer(abiList, socketName, zygoteServer);
            if (r != null) {
                r.run();
                return;
            }
        }

        // 6. 进入循环,等待 AMS 的 fork 请求
        zygoteServer.runSelectLoop(abiList);
    } catch (Throwable ex) {
        Log.e(TAG, "System zygote died with exception", ex);
        throw ex;
    } finally {
        zygoteServer.closeServerSocket();
    }
}

3 Zygote fork 出 SystemServer

3.1 forkSystemServer 的关键动作

// ZygoteInit.java
private static Runnable forkSystemServer(String abiList, String socketName,
        ZygoteServer zygoteServer) {
    long capabilities = posixCapabilitiesAsBits(
        OsConstants.CAP_IPC_LOCK,
        OsConstants.CAP_KILL,
        OsConstants.CAP_NET_ADMIN,
        OsConstants.CAP_NET_BIND_SERVICE,
        OsConstants.CAP_NET_BROADCAST,
        OsConstants.CAP_NET_RAW,
        OsConstants.CAP_SYS_MODULE,
        OsConstants.CAP_SYS_NICE,
        OsConstants.CAP_SYS_PTRACE,
        OsConstants.CAP_SYS_TIME,
        OsConstants.CAP_SYS_TTY_CONFIG,
        OsConstants.CAP_WAKE_ALARM
    );
    /* Containers run without this capability, so avoid setting it in that case */
    if (!SystemProperties.getBoolean(PROPERTY_RUNNING_IN_CONTAINER, false)) {
        capabilities |= posixCapabilitiesAsBits(OsConstants.CAP_BLOCK_SUSPEND);
    }
    /* Hardcoded command line to start the system server */
    String args[] = {
        "--setuid=1000",
        "--setgid=1000",
        "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1023,1032,3001,3002,3003,3006,3007,3009,3010",
        "--capabilities=" + capabilities + "," + capabilities,
        "--nice-name=system_server",
        "--runtime-args",
        "com.android.server.SystemServer",
    };
    ZygoteConnection.Arguments parsedArgs = null;

    int pid;

    try {
        parsedArgs = new ZygoteConnection.Arguments(args);
        ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
        ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);

        /* Request to fork the system server process */
        pid = Zygote.forkSystemServer(
                parsedArgs.uid, parsedArgs.gid,
                parsedArgs.gids,
                parsedArgs.debugFlags,
                null,
                parsedArgs.permittedCapabilities,
                parsedArgs.effectiveCapabilities);
    } catch (IllegalArgumentException ex) {
        throw new RuntimeException(ex);
    }

    /* For child process */
    if (pid == 0) {
        if (hasSecondZygote(abiList)) {
            waitForSecondaryZygote(socketName);
        }

        zygoteServer.closeServerSocket();
        return handleSystemServerProcess(parsedArgs);
    }

    return null;
}

注意 --setuid=1000:SystemServer 以 system 用户 运行,这是它能访问大量系统资源的前提。

handleSystemServerProcess会调用zygoteInit,zygoteInit调用RuntimeInit.applicationInit最后被调用到findStaticMain从而拉起SystemServer,这里的className为解析出来的com.android.server.SystemServer

private static Runnable findStaticMain(String className, String[] argv,
        ClassLoader classLoader) {
    Class<?> cl;
    try {
        cl = Class.forName(className, true, classLoader);
    } catch (ClassNotFoundException ex) {
        throw new RuntimeException(
                "Missing class when invoking static main " + className,
                ex);
    }

    Method m;
    try {
        m = cl.getMethod("main", new Class[] { String[].class });
    } catch (NoSuchMethodException ex) {
        throw new RuntimeException(
                "Missing static main on " + className, ex);
    } catch (SecurityException ex) {
        throw new RuntimeException(
                "Problem getting static main on " + className, ex);
    }

    int modifiers = m.getModifiers();
    if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
        throw new RuntimeException(
                "Main method is not public and static on " + className);
    }

    /*
     * This throw gets caught in ZygoteInit.main(), which responds
     * by invoking the exception's run() method. This arrangement
     * clears up all the stack frames that were required in setting
     * up the process.
     */
    return new MethodAndArgsCaller(m, argv);
}

3.2 SystemServer.main 入口

// frameworks/base/services/java/com/android/server/SystemServer.java
public static void main(String[] args) {
    new SystemServer().run();
}

private void run() {
    try {
        // 1. 设置时区、语言等基础属性
        SystemProperties.set("persist.sys.language", ...);

        // 2. 准备主线程 Looper
        Looper.prepareMainLooper();
        Looper.getMainLooper().setSlowLogThresholdMs(100 * 1000, 200 * 1000);

        // 3. 加载 native 库
        System.loadLibrary("android_servers");

        // 4. 创建系统上下文
        createSystemContext();

        // 5. 创建 SystemServiceManager
        mSystemServiceManager = new SystemServiceManager(mSystemContext);
        mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
        LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);

        // 6. 启动各类服务
        try {
            startBootstrapServices();
            startCoreServices();
            startOtherServices();
        } catch (Throwable ex) {
            throw ex;
        }

        // 7. 进入主线程消息循环
        Looper.loop();
    } catch (Throwable ex) {
        Log.e("System", "******************************************");
        Log.e("System", "************ Failure starting system services", ex);
        throw ex;
    }
}

4. SystemServer 启动三大阶段

SystemServer 的服务启动被划分为三个阶段,顺序不能乱,因为存在强依赖。

4.1 startBootstrapServices:引导服务

这一阶段启动的是「其他服务都依赖它」的核心服务:

服务作用
Installer与 installd 通信,负责 APK 安装
ActivityManagerService四大组件管理、进程管理
PowerManagerService电源管理
LightsService指示灯
DisplayManagerService显示管理
PackageManagerService包管理,扫描 APK
UserManagerService多用户管理
SensorService传感器

其中 PMS 的构造过程 会扫描 /system/app、/system/priv-app、/data/app 下的所有 APK,解析 AndroidManifest,这一步在冷启动时非常耗时。

4.2 startCoreServices:核心服务

private void startCoreServices() {
    mSystemServiceManager.startService(BatteryService.class);
    mSystemServiceManager.startService(UsageStatsService.class);
    mActivityManagerService.setUsageStatsManager(
            LocalServices.getService(UsageStatsManagerInternal.class));
    mSystemServiceManager.startService(WebViewUpdateService.class);
}

4.3 startOtherServices:其他服务

这是最长的一个阶段,包含 WMS、InputManagerService、WindowManagerService、NetworkManagementService、NotificationManagerService 等上百个服务。

其中与 SystemUI 启动直接相关的是:

// 启动 WindowManagerService
wm = WindowManagerService.main(context, inputManager,
        mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,
        !mFirstBoot, mOnlyCore, new PhoneWindowManager());
ServiceManager.addService(Context.WINDOW_SERVICE, wm);

// 启动 InputManagerService
inputManager = new InputManagerService(context);

// 启动 StatusBarManagerService
statusBar = new StatusBarManagerService(context, wm);
ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);

5. 关键节点:AMS.systemReady 触发 SystemUI 启动

5.1 systemReady 的调用时机

在 startOtherServices 的末尾,SystemServer 会依次调用各服务的 systemReady():

// 通知 AMS 系统就绪
mActivityManagerService.systemReady(() -> {
    Slog.i(TAG, "Making services ready");
    mSystemServiceManager.startBootPhase(
            SystemService.PHASE_ACTIVITY_MANAGER_READY);
    try {
        mActivityManagerService.startObservingNativeCrashes();
    } catch (Throwable e) {
        reportWtf("observing native crashes", e);
    }

    // 启动 SystemUI
    startSystemUi(context, windowManagerF);

    // 启动 Watchdog
    ...
}, BOOT_TIMINGS_TRACE_LOG);

5.2 startSystemUi 的实现

// SystemServer.java
private static void startSystemUi(Context context, WindowManagerService windowManager) {
    Intent intent = new Intent();
    intent.setComponent(new ComponentName("com.android.systemui",
            "com.android.systemui.SystemUIService"));
    intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
    // 以 system 用户身份启动
    context.startServiceAsUser(intent, UserHandle.SYSTEM);
    windowManager.onSystemUiStarted();
}

这里有两个关键点:

  1. 通过 startServiceAsUser 启动:走的是标准 AMS 启动 Service 流程,最终会请求 Zygote fork 出 SystemUI 进程。
  2. windowManager.onSystemUiStarted():通知 WMS 系统 UI 已启动,WMS 会据此调整窗口策略(例如允许 SystemUI 的窗口显示在锁屏之上)。

6. AMS 如何请求 Zygote fork 进程

startServiceAsUser 最终会走到 ActivityManagerService.startProcessLocked,通过 Process.start 与 Zygote 的 Socket 通信:

// Process.java
public static ProcessStartResult start(...) {
    return zygoteProcess.start(...);
}

// ZygoteProcess.java
public final Process.ProcessStartResult start(...) {
    // 通过 openZygoteSocketIfNeeded 建立连接
    // 写入参数:uid、gid、nice-name、entry-point 等
    // Zygote 端 ZygoteConnection.runOnce 读取参数并 fork
}

Zygote 收到请求后,在 ZygoteConnection.handleChildProc 中完成:

  • handleChildProc → ZygoteInit.zygoteInit → RuntimeInit.applicationInit
  • 反射调用 android.app.ActivityThread.main
  • 创建 Application,最终回调到 SystemUI Application.onCreate

7. SystemUI 进程的启动过程

7.1 SystemUI 的 AndroidManifest

<application
    android:name=".SystemUIApplication"
    android:persistent="true"
    android:allowClearUserData="false"
    android:allowBackup="false"
    android:label="@string/app_label"
    android:process="com.android.systemui">

    <service
        android:name=".SystemUIService"
        android:exported="true"
        android:process="com.android.systemui" />
</application>

android:persistent="true" 表示这是常驻进程,被系统杀死后会被 AMS 自动重启。

7.2 SystemUIApplication.onCreate

// frameworks/base/packages/SystemUI/src/com/android/systemui/SystemUIApplication.java
public void onCreate() {
    super.onCreate();
    // 1. 设置主题
    setTheme(R.style.Theme_SystemUI);

    // 2. 启动 SystemUIService
    startService(new Intent(this, SystemUIService.class));

    // 3. 初始化各组件
    final SystemUI[] services = mServices;
    for (int i = 0; i < services.length; i++) {
        services[i].start();
    }
}

7.3 SystemUIService.onCreate

// SystemUIService.java
public void onCreate() {
    super.onCreate();
    // 1. 获取所有 SystemUI 组件
    SystemUI[] services = SystemUIFactory.getInstance().getSystemUIServiceComponents(getResources());

    // 2. 逐个启动
    for (SystemUI ui : services) {
        ui.start();
    }
}

getSystemUIServiceComponents 返回的组件列表(Android 8.1)大致包括:

  • NotificationListener
  • SystemBars(包含 StatusBar、NavigationBar)
  • Recents
  • VolumeUI
  • StackDivider
  • KeyboardUI
  • SystemUIRootComponent
  • ScreenDecorations
  • PowerUI
  • KeyguardViewMediator(锁屏)

7.4 StatusBar 的创建

SystemBars.start() 会创建 StatusBar,进而创建 StatusBarWindowManager、StatusBarIconController 等,最终通过 WindowManager.addView 把状态栏窗口添加到 WMS:

// StatusBar.java
protected void makeStatusBarView() {
    // 1. 加载布局
    final StatusBarWindowView statusBarWindow = (StatusBarWindowView) View.inflate(context,
            R.layout.super_status_bar, null);

    // 2. 创建窗口管理器
    mStatusBarWindowManager = new StatusBarWindowManager(context);

    // 3. 添加窗口
    mStatusBarWindowManager.add(statusBarWindow, mState);
}

窗口添加成功后,WMS 会触发 SurfaceFlinger 合成,状态栏才真正显示在屏幕上。

8. 开机动画的退出时机

很多人会疑惑:SystemUI 都起来了,为什么开机动画还在转?关键在于 bootanim 的退出条件。

SurfaceFlinger 在 startBootAnim 之后,会等待 systemReady 信号:

// frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp
void SurfaceFlinger::bootFinished() {
    // 通知 bootanim 退出
    property_set("service.bootanim.exit", "1");
}

而 bootFinished() 的触发点在 WindowManagerService:

// WindowManagerService.java
public void systemReady() {
    ...
    // 通知 SurfaceFlinger 开机动画可以退出
    mPolicy.systemReady();
    ...
}

实际调用链是:AMS.systemReady → WMS.systemReady → SurfaceFlinger.bootFinished → 设置 service.bootanim.exit=1 → bootanim 进程退出。

所以 开机动画的退出与 SystemUI 的启动是并行推进的,并不严格等待 SystemUI 完全显示。这也是为什么某些机型会出现「开机动画消失后短暂黑屏」的现象。

9. 完整时序总结

sequenceDiagram
    participant Init as &#34;init&#34;
    participant Zygote as &#34;Zygote&#34;
    participant SS as &#34;SystemServer&#34;
    participant AMS as &#34;AMS&#34;
    participant WMS as &#34;WMS&#34;
    participant SF as &#34;SurfaceFlinger&#34;
    participant SUI as &#34;SystemUI&#34;

    Init->>Zygote: &#34;启动 app_process --zygote&#34;
    Zygote->>Zygote: &#34;preload 类与资源&#34;
    Zygote->>SS: &#34;fork 并执行 SystemServer.main&#34;
    SS->>SS: &#34;startBootstrapServices&#34;
    SS->>SS: &#34;startCoreServices&#34;
    SS->>SS: &#34;startOtherServices&#34;
    SS->>AMS: &#34;systemReady()&#34;
    AMS->>SUI: &#34;startServiceAsUser(SystemUIService)&#34;
    AMS->>Zygote: &#34;Socket 请求 fork SystemUI&#34;
    Zygote->>SUI: &#34;fork 并 attach&#34;
    SUI->>SUI: &#34;Application.onCreate&#34;
    SUI->>SUI: &#34;SystemUIService 启动各组件&#34;
    SUI->>WMS: &#34;addView(StatusBar)&#34;
    SS->>WMS: &#34;systemReady()&#34;
    WMS->>SF: &#34;bootFinished()&#34;
    SF->>SF: &#34;service.bootanim.exit=1&#34;

10. 常见问题排查思路

10.1 开机卡在开机动画

  • 检查 logcat 中 SystemServer 是否打印 Failure starting system services。
  • 检查 Zygote 是否崩溃:logcat -b crash。
  • 检查 PMS 扫描是否卡住:搜索 PackageManager 相关日志。

10.2 SystemUI 反复重启

  • 查看 dumpsys activity processes | grep systemui 确认进程状态。
  • 检查是否发生 ANR in com.android.systemui。
  • 检查 persistent 进程是否被 LowMemoryKiller 误杀。

10.3 状态栏不显示

  • 确认 StatusBarWindowManager.add 是否被调用。
  • 检查 WMS 中是否存在 StatusBar 窗口:dumpsys window windows | grep StatusBar。
  • 检查 windowManager.onSystemUiStarted() 是否被调用。

11. 小结

从 Zygote 到 SystemUI,Android 8.1 的启动链路可以概括为:

  1. init 通过 rc 文件拉起 Zygote,创建 Socket 通道。
  2. Zygote 预加载类与资源,fork 出 SystemServer。
  3. SystemServer 分三阶段启动上百个系统服务,其中 PMS、AMS、WMS 是核心。
  4. AMS.systemReady 通过 startServiceAsUser 触发 SystemUI 启动。
  5. SystemUI 进程由 Zygote fork,加载各组件,通过 WMS 添加状态栏等窗口。
  6. WMS.systemReady 通知 SurfaceFlinger 退出开机动画。

理解这条链路,才能在面对开机异常、SystemUI 崩溃、黑屏等问题时快速定位到具体环节。