{
  "schemaVersion": "0.11.0",
  "canonical": "https://www.pystone.net/notes/android-application-launch-process/",
  "atlas": "https://www.pystone.net/?node=android-application-launch-process#knowledge-atlas",
  "markdown": "https://www.pystone.net/notes/android-application-launch-process.md",
  "context": "https://www.pystone.net/notes/android-application-launch-process.context.json",
  "knowledgeVersion": "224c990773de.5fa8af6e39fa",
  "build": {
    "siteCommit": "224c990773de166d23a886306577dd90379529ce",
    "notesCommit": "5fa8af6e39fa3891d1b9b4832bfa6c4e0ecaaf0a",
    "builtAt": "1970-01-01T00:00:00.000Z",
    "version": "224c990773de.5fa8af6e39fa"
  },
  "id": "note:android-application-launch-process",
  "slug": "android-application-launch-process",
  "title": "Android Application 启动过程",
  "type": "note",
  "visibility": "public",
  "idStability": "rename-stable",
  "author": {
    "name": "Perrin Yong",
    "profile": "https://www.pystone.net/profile/"
  },
  "publisher": {
    "name": "Perrin Yong",
    "profile": "https://www.pystone.net/profile/"
  },
  "aliases": [],
  "summary": "Android Application 启动过程",
  "contentRole": "unspecified",
  "isMoc": false,
  "mocRecognition": "none",
  "generated": false,
  "attribution": "unspecified",
  "domain": "10-计算机、信息技术与工程",
  "tags": [],
  "mocs": [],
  "contentHash": "a0301921300407d0f797c7f1688f26479de287380a620fadfd9ee61e6d3beffe",
  "assets": [
    {
      "reference": "assets/image-20250124182509547.png",
      "url": "/media/cf291eb4298c6620d7a2.png",
      "mediaType": "image/png",
      "contentHash": "cf291eb4298c6620d7a2295076d9ca9f64ad5913ebb1e955ec62f935423a9f0a",
      "byteLength": 122550,
      "width": 1081,
      "height": 313
    },
    {
      "reference": "assets/image-20250124182114388.png",
      "url": "/media/f77bcd57eaa8e6d7448a.png",
      "mediaType": "image/png",
      "contentHash": "f77bcd57eaa8e6d7448a0b68b1fa35931d55df82cc53a159c0471ceb8bdc8da0",
      "byteLength": 205854,
      "width": 1054,
      "height": 728
    }
  ],
  "headings": [
    {
      "depth": 1,
      "text": "Android Application 启动过程",
      "anchor": "android-application-启动过程",
      "citation": "https://www.pystone.net/notes/android-application-launch-process/#android-application-%E5%90%AF%E5%8A%A8%E8%BF%87%E7%A8%8B"
    },
    {
      "depth": 3,
      "text": "1. Launcher：用户点击图标启动应用",
      "anchor": "1-launcher用户点击图标启动应用",
      "citation": "https://www.pystone.net/notes/android-application-launch-process/#1-launcher%E7%94%A8%E6%88%B7%E7%82%B9%E5%87%BB%E5%9B%BE%E6%A0%87%E5%90%AF%E5%8A%A8%E5%BA%94%E7%94%A8"
    },
    {
      "depth": 4,
      "text": "1.1 处理用户点击事件",
      "anchor": "11-处理用户点击事件",
      "citation": "https://www.pystone.net/notes/android-application-launch-process/#11-%E5%A4%84%E7%90%86%E7%94%A8%E6%88%B7%E7%82%B9%E5%87%BB%E4%BA%8B%E4%BB%B6"
    },
    {
      "depth": 4,
      "text": "1.2 构建并启动 Intent",
      "anchor": "12-构建并启动-intent",
      "citation": "https://www.pystone.net/notes/android-application-launch-process/#12-%E6%9E%84%E5%BB%BA%E5%B9%B6%E5%90%AF%E5%8A%A8-intent"
    },
    {
      "depth": 3,
      "text": "2. SystemServer：ActivityManagerService 处理启动请求",
      "anchor": "2-systemserveractivitymanagerservice-处理启动请求",
      "citation": "https://www.pystone.net/notes/android-application-launch-process/#2-systemserveractivitymanagerservice-%E5%A4%84%E7%90%86%E5%90%AF%E5%8A%A8%E8%AF%B7%E6%B1%82"
    },
    {
      "depth": 4,
      "text": "2.1 Instrumentation 向 ActivityManagerService 发送启动请求",
      "anchor": "21-instrumentation-向-activitymanagerservice-发送启动请求",
      "citation": "https://www.pystone.net/notes/android-application-launch-process/#21-instrumentation-%E5%90%91-activitymanagerservice-%E5%8F%91%E9%80%81%E5%90%AF%E5%8A%A8%E8%AF%B7%E6%B1%82"
    },
    {
      "depth": 4,
      "text": "2.2 ActivityManagerService 获取 IActivityTaskManager",
      "anchor": "22-activitymanagerservice-获取-iactivitytaskmanager",
      "citation": "https://www.pystone.net/notes/android-application-launch-process/#22-activitymanagerservice-%E8%8E%B7%E5%8F%96-iactivitytaskmanager"
    },
    {
      "depth": 4,
      "text": "2.3 ActivityManagerService 校验并处理启动请求",
      "anchor": "23-activitymanagerservice-校验并处理启动请求",
      "citation": "https://www.pystone.net/notes/android-application-launch-process/#23-activitymanagerservice-%E6%A0%A1%E9%AA%8C%E5%B9%B6%E5%A4%84%E7%90%86%E5%90%AF%E5%8A%A8%E8%AF%B7%E6%B1%82"
    },
    {
      "depth": 4,
      "text": "2.4 通过 ActivityStarter 配置启动参数",
      "anchor": "24-通过-activitystarter-配置启动参数",
      "citation": "https://www.pystone.net/notes/android-application-launch-process/#24-%E9%80%9A%E8%BF%87-activitystarter-%E9%85%8D%E7%BD%AE%E5%90%AF%E5%8A%A8%E5%8F%82%E6%95%B0"
    },
    {
      "depth": 4,
      "text": "2.5 启动目标 Activity 并处理 Activity Stack",
      "anchor": "25-启动目标-activity-并处理-activity-stack",
      "citation": "https://www.pystone.net/notes/android-application-launch-process/#25-%E5%90%AF%E5%8A%A8%E7%9B%AE%E6%A0%87-activity-%E5%B9%B6%E5%A4%84%E7%90%86-activity-stack"
    },
    {
      "depth": 3,
      "text": "3. 应用进程启动：ActivityManagerService 请求进程创建",
      "anchor": "3-应用进程启动activitymanagerservice-请求进程创建",
      "citation": "https://www.pystone.net/notes/android-application-launch-process/#3-%E5%BA%94%E7%94%A8%E8%BF%9B%E7%A8%8B%E5%90%AF%E5%8A%A8activitymanagerservice-%E8%AF%B7%E6%B1%82%E8%BF%9B%E7%A8%8B%E5%88%9B%E5%BB%BA"
    },
    {
      "depth": 4,
      "text": "3.1 检查应用进程是否存在",
      "anchor": "31-检查应用进程是否存在",
      "citation": "https://www.pystone.net/notes/android-application-launch-process/#31-%E6%A3%80%E6%9F%A5%E5%BA%94%E7%94%A8%E8%BF%9B%E7%A8%8B%E6%98%AF%E5%90%A6%E5%AD%98%E5%9C%A8"
    },
    {
      "depth": 4,
      "text": "3.2 通过 startProcessAsync() 启动新进程",
      "anchor": "32-通过-startprocessasync-启动新进程",
      "citation": "https://www.pystone.net/notes/android-application-launch-process/#32-%E9%80%9A%E8%BF%87-startprocessasync-%E5%90%AF%E5%8A%A8%E6%96%B0%E8%BF%9B%E7%A8%8B"
    },
    {
      "depth": 4,
      "text": "3.3 ActivityManagerInternal 处理进程创建请求",
      "anchor": "33-activitymanagerinternal-处理进程创建请求",
      "citation": "https://www.pystone.net/notes/android-application-launch-process/#33-activitymanagerinternal-%E5%A4%84%E7%90%86%E8%BF%9B%E7%A8%8B%E5%88%9B%E5%BB%BA%E8%AF%B7%E6%B1%82"
    },
    {
      "depth": 4,
      "text": "3.4 通过 ProcessList.startProcess() 启动进程",
      "anchor": "34-通过-processliststartprocess-启动进程",
      "citation": "https://www.pystone.net/notes/android-application-launch-process/#34-%E9%80%9A%E8%BF%87-processliststartprocess-%E5%90%AF%E5%8A%A8%E8%BF%9B%E7%A8%8B"
    },
    {
      "depth": 3,
      "text": "4. Zygote：创建应用进程",
      "anchor": "4-zygote创建应用进程",
      "citation": "https://www.pystone.net/notes/android-application-launch-process/#4-zygote%E5%88%9B%E5%BB%BA%E5%BA%94%E7%94%A8%E8%BF%9B%E7%A8%8B"
    },
    {
      "depth": 4,
      "text": "4.1 Zygote 监听并处理进程启动请求（runSelectLoop()）",
      "anchor": "41-zygote-监听并处理进程启动请求runselectloop",
      "citation": "https://www.pystone.net/notes/android-application-launch-process/#41-zygote-%E7%9B%91%E5%90%AC%E5%B9%B6%E5%A4%84%E7%90%86%E8%BF%9B%E7%A8%8B%E5%90%AF%E5%8A%A8%E8%AF%B7%E6%B1%82runselectloop"
    },
    {
      "depth": 4,
      "text": "4.2 通过 Zygote.forkAndSpecialize() 创建新进程",
      "anchor": "42-通过-zygoteforkandspecialize-创建新进程",
      "citation": "https://www.pystone.net/notes/android-application-launch-process/#42-%E9%80%9A%E8%BF%87-zygoteforkandspecialize-%E5%88%9B%E5%BB%BA%E6%96%B0%E8%BF%9B%E7%A8%8B"
    },
    {
      "depth": 4,
      "text": "4.3 Zygote 初始化子进程",
      "anchor": "43-zygote-初始化子进程",
      "citation": "https://www.pystone.net/notes/android-application-launch-process/#43-zygote-%E5%88%9D%E5%A7%8B%E5%8C%96%E5%AD%90%E8%BF%9B%E7%A8%8B"
    },
    {
      "depth": 3,
      "text": "5. 应用进程初始化：ActivityThread 启动应用",
      "anchor": "5-应用进程初始化activitythread-启动应用",
      "citation": "https://www.pystone.net/notes/android-application-launch-process/#5-%E5%BA%94%E7%94%A8%E8%BF%9B%E7%A8%8B%E5%88%9D%E5%A7%8B%E5%8C%96activitythread-%E5%90%AF%E5%8A%A8%E5%BA%94%E7%94%A8"
    },
    {
      "depth": 4,
      "text": "5.1 执行 ActivityThread.main()",
      "anchor": "51-执行-activitythreadmain",
      "citation": "https://www.pystone.net/notes/android-application-launch-process/#51-%E6%89%A7%E8%A1%8C-activitythreadmain"
    },
    {
      "depth": 4,
      "text": "5.2 初始化 Application 对象",
      "anchor": "52-初始化-application-对象",
      "citation": "https://www.pystone.net/notes/android-application-launch-process/#52-%E5%88%9D%E5%A7%8B%E5%8C%96-application-%E5%AF%B9%E8%B1%A1"
    },
    {
      "depth": 4,
      "text": "5.3 启动目标 Activity",
      "anchor": "53-启动目标-activity",
      "citation": "https://www.pystone.net/notes/android-application-launch-process/#53-%E5%90%AF%E5%8A%A8%E7%9B%AE%E6%A0%87-activity"
    },
    {
      "depth": 4,
      "text": "5.4 执行 Activity 生命周期方法",
      "anchor": "54-执行-activity-生命周期方法",
      "citation": "https://www.pystone.net/notes/android-application-launch-process/#54-%E6%89%A7%E8%A1%8C-activity-%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E6%96%B9%E6%B3%95"
    }
  ],
  "claims": [],
  "outgoing": [],
  "incoming": [
    {
      "id": "note:application-and-cloud-engineering",
      "title": "应用开发与云端工程",
      "url": "https://www.pystone.net/notes/application-and-cloud-engineering/",
      "atlas": "https://www.pystone.net/?node=application-and-cloud-engineering#knowledge-atlas",
      "label": "应用开发与云端工程",
      "origin": "explicit",
      "humanReviewed": true,
      "context": "Android开发中的“Android Application 启动过程”导航项",
      "citation": "https://www.pystone.net/notes/application-and-cloud-engineering/#android%E5%BC%80%E5%8F%91"
    }
  ],
  "contentMarkdown": "# Android Application 启动过程\n\nZygote的Java框架层中，会创建一个Server端的Socket，这个Socket用来等待ActivityManagerService来请求Zygote来创建新的应用程序进程的\nZygote进程通过fock自身创建的应用程序进程，这样应用程序程序进程就会获得Zygote进程在启动时创建的虚拟机实例, Binder线程池和消息循环.\n\n> 应用程序就可以方便的使用Binder进行进程间通信以及消息处理机制\n\n\n![](assets/image-20250124182509547.png)\n\n\n![](assets/image-20250124182114388.png)\n### 1. **Launcher：用户点击图标启动应用**\n\n#### 1.1 **处理用户点击事件**\n\n- 用户点击桌面上的应用图标，`Launcher` 的 `ItemClickHandler` 处理这个点击事件。\n- `ItemClickHandler` 调用 `onClick()` 方法，进一步触发 `startAppShortcutOrInfoActivity()` 来启动目标应用。\n\n```java\nprivate static void startAppShortcutOrInfoActivity(View v, ItemInfo item, Launcher launcher,\n\t\t@Nullable String sourceContainer) {\n\t//省略部分代码\n\n\t//执行Launcher中的方法\n\tlauncher.startActivitySafely(v, intent, item, sourceContainer);\n}\n```\n\n#### 1.2 **构建并启动 `Intent`**\n\n- 在 `startAppShortcutOrInfoActivity()` 方法中，构建一个 `Intent`，该 `Intent` 包含启动目标应用的相关配置信息。\n- 通过 `startActivity()` 启动目标应用的 `Activity`。\n\n```java\n    @Override\n    public boolean startActivitySafely(View v, Intent intent, ItemInfo item,\n            @Nullable String sourceContainer) {\n        //省略部分代码\n\n\t\t//执行父类BaseDraggingActivity的方法\n        boolean success = super.startActivitySafely(v, intent, item, sourceContainer);\n        if (success && v instanceof BubbleTextView) {\n            // This is set to the view that launched the activity that navigated the user away\n            // from launcher. Since there is no callback for when the activity has finished\n            // launching, enable the press state and keep this reference to reset the press\n            // state when we return to launcher.\n            BubbleTextView btv = (BubbleTextView) v;\n            btv.setStayPressed(true);\n            addOnResumeCallback(btv);\n        }\n        return success;\n    }\n\n```\n\n\n---\n\n### 2. **SystemServer：ActivityManagerService 处理启动请求**\n\n#### 2.1 **Instrumentation 向 ActivityManagerService 发送启动请求**\n\n\n- `Instrumentation` 通过 `execStartActivity()` 将 `Activity` 启动请求传递给 `ActivityManagerService`，开始跨进程通信。\n\n#### 2.2 **ActivityManagerService 获取 `IActivityTaskManager`**\n\n- `ActivityManagerService` 调用 `ActivityTaskManager.getService()` 获取 `IActivityTaskManager`，这个接口用于与系统的 Activity 管理服务进行远程交互。\n\n#### 2.3 **ActivityManagerService 校验并处理启动请求**\n\n- `ActivityManagerService` 在接收到启动请求后，执行一系列参数检查，确保请求合法。\n- 如果目标应用的进程未启动，`ActivityManagerService` 会通过 `ActivityStarter` 来决定是否需要启动新的进程。\n\n#### 2.4 **通过 ActivityStarter 配置启动参数**\n\n- `ActivityManagerService` 将请求交给 `ActivityStarter`，`ActivityStarter` 配置启动所需的各项参数，如 `ActivityRecord`，这是启动目标 `Activity` 的必要数据结构。\n- `ActivityStarter` 调用 `startActivityUnchecked()` 来执行启动操作。\n\n#### 2.5 **启动目标 Activity 并处理 Activity Stack**\n\n- 在 `startActivityUnchecked()` 中，调用 `startActivityInner()`，处理 `Activity Stack`，将目标 `Activity` 放到栈中，并通过 `resumeFocusedStacksTopActivities()` 确保目标 `Activity` 被移至前台，开始显示。\n\n---\n\n### 3. **应用进程启动：ActivityManagerService 请求进程创建**\n\n#### 3.1 **检查应用进程是否存在**\n\n- `ActivityManagerService` 会首先检查目标应用的进程是否已经存在。如果进程不存在，系统需要启动新的进程。\n\n```java\n\tvoid startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {\n        // Is this activity's application already running?\n        final WindowProcessController wpc =\n                mService.getProcessController(r.processName, r.info.applicationInfo.uid);\n\n        boolean knownToBeDead = false;\n        //判断app有没有启动，如果已经启动了，则直接启动Activity\n        if (wpc != null && wpc.hasThread()) {\n            try {\n                realStartActivityLocked(r, wpc, andResume, checkConfig);\n                return;\n            } catch (RemoteException e) {\n                Slog.w(TAG, \"Exception when starting activity \"\n                        + r.intent.getComponent().flattenToShortString(), e);\n            }\n\n            // If a dead object exception was thrown -- fall through to\n            // restart the application.\n            knownToBeDead = true;\n        }\n\n        r.notifyUnknownVisibilityLaunchedForKeyguardTransition();\n\n        final boolean isTop = andResume && r.isTopRunningActivity();\n        //app没有启动，说明是第一次启动，则需要先创建进程\n        mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? \"top-activity\" : \"activity\");\n    }\n\n```\n\n\n#### 3.2 **通过 `startProcessAsync()` 启动新进程**\n\n- `ActivityManagerService` 调用 `startProcessAsync()` 方法请求启动目标应用的进程。如果目标进程未启动，则执行进程创建操作。\n\n#### 3.3 **ActivityManagerInternal 处理进程创建请求**\n\n- `ActivityManagerInternal` 接收到启动进程的请求，并调用 `startProcess()` 方法进行处理，准备启动新进程。\n\n`startProcess()`是一个抽象方法，由`ActivityManagerInternal`的子类`ActivityManagerService.LocalService`实现\n\n```java\n        @Override\n        public void startProcess(String processName, ApplicationInfo info, boolean knownToBeDead,\n                boolean isTop, String hostingType, ComponentName hostingName) {\n            try {\n                if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {\n                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, \"startProcess:\"\n                            + processName);\n                }\n                synchronized (ActivityManagerService.this) {\n                    // If the process is known as top app, set a hint so when the process is\n                    // started, the top priority can be applied immediately to avoid cpu being\n                    // preempted by other processes before attaching the process of top app.\n                    //执行AMS的startProcessLocked()\n                    startProcessLocked(processName, info, knownToBeDead, 0 /* intentFlags */,\n                            new HostingRecord(hostingType, hostingName, isTop),\n                            ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE, false /* allowWhileBooting */,\n                            false /* isolated */, true /* keepIfLarge */);\n                }\n            } finally {\n                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);\n            }\n        }\n\n```\n\n#### 3.4 **通过 `ProcessList.startProcess()` 启动进程**\n\n- `ActivityManagerService` 将进程创建请求传递给 `ProcessList.startProcess()`，负责启动目标应用进程。\n\n```java\n    private Process.ProcessStartResult startProcess(HostingRecord hostingRecord, String entryPoint,\n            ProcessRecord app, int uid, int[] gids, int runtimeFlags, int zygotePolicyFlags,\n            int mountExternal, String seInfo, String requiredAbi, String instructionSet,\n            String invokeWith, long startTime) {\n        try {\n            Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, \"Start proc: \" +\n                    app.processName);\n            //请求zygote开启进程\n            checkSlow(startTime, \"startProcess: asking zygote to start proc\");\n            //省略部分代码\n\n            final Process.ProcessStartResult startResult;\n            //根据进程的类型，用不同的方式创建\n            if (hostingRecord.usesWebviewZygote()) {\n                startResult = startWebView(entryPoint,\n                        app.processName, uid, uid, gids, runtimeFlags, mountExternal,\n                        app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,\n                        app.info.dataDir, null, app.info.packageName, app.mDisabledCompatChanges,\n                        new String[]{PROC_START_SEQ_IDENT + app.startSeq});\n            } else if (hostingRecord.usesAppZygote()) {\n                final AppZygote appZygote = createAppZygoteForProcessIfNeeded(app);\n\n                // We can't isolate app data and storage data as parent zygote already did that.\n                startResult = appZygote.getProcess().start(entryPoint,\n                        app.processName, uid, uid, gids, runtimeFlags, mountExternal,\n                        app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,\n                        app.info.dataDir, null, app.info.packageName,\n                        /*zygotePolicyFlags=*/ ZYGOTE_POLICY_FLAG_EMPTY, isTopApp,\n                        app.mDisabledCompatChanges, pkgDataInfoMap, whitelistedAppDataInfoMap,\n                        false, false,\n                        new String[]{PROC_START_SEQ_IDENT + app.startSeq});\n            } else {\n                startResult = Process.start(entryPoint,\n                        app.processName, uid, uid, gids, runtimeFlags, mountExternal,\n                        app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,\n                        app.info.dataDir, invokeWith, app.info.packageName, zygotePolicyFlags,\n                        isTopApp, app.mDisabledCompatChanges, pkgDataInfoMap,\n                        whitelistedAppDataInfoMap, bindMountAppsData, bindMountAppStorageDirs,\n                        new String[]{PROC_START_SEQ_IDENT + app.startSeq});\n            }\n            checkSlow(startTime, \"startProcess: returned from zygote!\");\n            return startResult;\n        } finally {\n            Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);\n        }\n    }\n\n```\n\nhostingRecord描述了启动一个进程所需要的各种信息，根据进程类型的不同，用不同的方式创建，普通app的进程由`Process.start()`创建\n\n```java\n\t/**\n     * State associated with the zygote process.\n     * @hide\n     */\n    public static final ZygoteProcess ZYGOTE_PROCESS = new ZygoteProcess();\n\n\tpublic static ProcessStartResult start(@NonNull final String processClass,\n                                           @Nullable final String niceName,\n                                           int uid, int gid, @Nullable int[] gids,\n                                           int runtimeFlags,\n                                           int mountExternal,\n                                           int targetSdkVersion,\n                                           @Nullable String seInfo,\n                                           @NonNull String abi,\n                                           @Nullable String instructionSet,\n                                           @Nullable String appDataDir,\n                                           @Nullable String invokeWith,\n                                           @Nullable String packageName,\n                                           int zygotePolicyFlags,\n                                           boolean isTopApp,\n                                           @Nullable long[] disabledCompatChanges,\n                                           @Nullable Map<String, Pair<String, Long>>\n                                                   pkgDataInfoMap,\n                                           @Nullable Map<String, Pair<String, Long>>\n                                                   whitelistedDataInfoMap,\n                                           boolean bindMountAppsData,\n                                           boolean bindMountAppStorageDirs,\n                                           @Nullable String[] zygoteArgs) {\n        //调用zygoteProcess的方法\n        return ZYGOTE_PROCESS.start(processClass, niceName, uid, gid, gids,\n                    runtimeFlags, mountExternal, targetSdkVersion, seInfo,\n                    abi, instructionSet, appDataDir, invokeWith, packageName,\n                    zygotePolicyFlags, isTopApp, disabledCompatChanges,\n                    pkgDataInfoMap, whitelistedDataInfoMap, bindMountAppsData,\n                    bindMountAppStorageDirs, zygoteArgs);\n    }\n\n```\n`Process.start()`又调用了`ZygoteProcess.start()`\n```java\n    public final Process.ProcessStartResult start(@NonNull final String processClass,\n                                                  final String niceName,\n                                                  int uid, int gid, @Nullable int[] gids,\n                                                  int runtimeFlags, int mountExternal,\n                                                  int targetSdkVersion,\n                                                  @Nullable String seInfo,\n                                                  @NonNull String abi,\n                                                  @Nullable String instructionSet,\n                                                  @Nullable String appDataDir,\n                                                  @Nullable String invokeWith,\n                                                  @Nullable String packageName,\n                                                  int zygotePolicyFlags,\n                                                  boolean isTopApp,\n                                                  @Nullable long[] disabledCompatChanges,\n                                                  @Nullable Map<String, Pair<String, Long>>\n                                                          pkgDataInfoMap,\n                                                  @Nullable Map<String, Pair<String, Long>>\n                                                          whitelistedDataInfoMap,\n                                                  boolean bindMountAppsData,\n                                                  boolean bindMountAppStorageDirs,\n                                                  @Nullable String[] zygoteArgs) {\n        // TODO (chriswailes): Is there a better place to check this value?\n        if (fetchUsapPoolEnabledPropWithMinInterval()) {\n            informZygotesOfUsapPoolStatus();\n        }\n\n        try {\n            //调用startViaZygote()\n            return startViaZygote(processClass, niceName, uid, gid, gids,\n                    runtimeFlags, mountExternal, targetSdkVersion, seInfo,\n                    abi, instructionSet, appDataDir, invokeWith, /*startChildZygote=*/ false,\n                    packageName, zygotePolicyFlags, isTopApp, disabledCompatChanges,\n                    pkgDataInfoMap, whitelistedDataInfoMap, bindMountAppsData,\n                    bindMountAppStorageDirs, zygoteArgs);\n        } catch (ZygoteStartFailedEx ex) {\n            Log.e(LOG_TAG,\n                    \"Starting VM process through Zygote failed\");\n            throw new RuntimeException(\n                    \"Starting VM process through Zygote failed\", ex);\n        }\n    }\n\n\tprivate Process.ProcessStartResult startViaZygote(@NonNull final String processClass,\n                                                      @Nullable final String niceName,\n                                                      final int uid, final int gid,\n                                                      @Nullable final int[] gids,\n                                                      int runtimeFlags, int mountExternal,\n                                                      int targetSdkVersion,\n                                                      @Nullable String seInfo,\n                                                      @NonNull String abi,\n                                                      @Nullable String instructionSet,\n                                                      @Nullable String appDataDir,\n                                                      @Nullable String invokeWith,\n                                                      boolean startChildZygote,\n                                                      @Nullable String packageName,\n                                                      int zygotePolicyFlags,\n                                                      boolean isTopApp,\n                                                      @Nullable long[] disabledCompatChanges,\n                                                      @Nullable Map<String, Pair<String, Long>>\n                                                              pkgDataInfoMap,\n                                                      @Nullable Map<String, Pair<String, Long>>\n                                                              whitelistedDataInfoMap,\n                                                      boolean bindMountAppsData,\n                                                      boolean bindMountAppStorageDirs,\n                                                      @Nullable String[] extraArgs)\n                                                      throws ZygoteStartFailedEx {\n        //收集进程参数\n        ArrayList<String> argsForZygote = new ArrayList<>();\n\n        // --runtime-args, --setuid=, --setgid=,\n        // and --setgroups= must go first\n        argsForZygote.add(\"--runtime-args\");\n        argsForZygote.add(\"--setuid=\" + uid);\n        argsForZygote.add(\"--setgid=\" + gid);\n        argsForZygote.add(\"--runtime-flags=\" + runtimeFlags);\n        //省略部分代码\n\n        synchronized(mLock) {\n            // The USAP pool can not be used if the application will not use the systems graphics\n            // driver.  If that driver is requested use the Zygote application start path.\n            //想zygote进程发送要创建的进程参数\n            return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi),\n                                              zygotePolicyFlags,\n                                              argsForZygote);\n        }\n    }\n\n    @GuardedBy(\"mLock\")\n    private Process.ProcessStartResult zygoteSendArgsAndGetResult(\n            ZygoteState zygoteState, int zygotePolicyFlags, @NonNull ArrayList<String> args)\n            throws ZygoteStartFailedEx {\n        // Throw early if any of the arguments are malformed. This means we can\n        // avoid writing a partial response to the zygote.\n        //校验参数\n        for (String arg : args) {\n            // Making two indexOf calls here is faster than running a manually fused loop due\n            // to the fact that indexOf is a optimized intrinsic.\n            if (arg.indexOf('\\n') >= 0) {\n                throw new ZygoteStartFailedEx(\"Embedded newlines not allowed\");\n            } else if (arg.indexOf('\\r') >= 0) {\n                throw new ZygoteStartFailedEx(\"Embedded carriage returns not allowed\");\n            }\n        }\n\n        //省略部分代码\n\t\t//调用attemptZygoteSendArgsAndGetResult()\n        return attemptZygoteSendArgsAndGetResult(zygoteState, msgStr);\n    }\n\n\tprivate Process.ProcessStartResult attemptZygoteSendArgsAndGetResult(\n            ZygoteState zygoteState, String msgStr) throws ZygoteStartFailedEx {\n        try {\n            final BufferedWriter zygoteWriter = zygoteState.mZygoteOutputWriter;\n            final DataInputStream zygoteInputStream = zygoteState.mZygoteInputStream;\n\n            //向zygote进程发送数据\n            zygoteWriter.write(msgStr);\n            zygoteWriter.flush();\n\n            // Always read the entire result from the input stream to avoid leaving\n            // bytes in the stream for future process starts to accidentally stumble\n            // upon.\n            //获取zygote进程返回的启动结果\n            Process.ProcessStartResult result = new Process.ProcessStartResult();\n            result.pid = zygoteInputStream.readInt();\n            result.usingWrapper = zygoteInputStream.readBoolean();\n\n            if (result.pid < 0) {\n                throw new ZygoteStartFailedEx(\"fork() failed\");\n            }\n\n            return result;\n        } catch (IOException ex) {\n            zygoteState.close();\n            Log.e(LOG_TAG, \"IO Exception while communicating with Zygote - \"\n                    + ex.toString());\n            throw new ZygoteStartFailedEx(ex);\n        }\n    }\n\n```\n\n在最后的`attemptZygoteSendArgsAndGetResult()`方法中，通过输入流向zygote进程发送数据，实际上这里是通过socket通信来完成的，我们知道常用的进程通信的方式有两种，binder和socket，在上面方法中有一个重要的参数`ZygoteState`，它是ZygoteProcess的内部类，定义了zygote服务端的地址以及IO通道，作用就是跟zygote进程进行通信\n\n\n\n\n### 4. **Zygote：创建应用进程**\n\n#### 4.1 **Zygote 监听并处理进程启动请求（`runSelectLoop()`）**\n`runSelectLoop()` 是 Zygote 中的核心方法，它会不断轮询接收到的进程启动请求，并处理每个请求。\n```java\nRunnable runSelectLoop(String abiList) {\n    ArrayList<FileDescriptor> socketFDs = new ArrayList<>();\n    ArrayList<ZygoteConnection> peers = new ArrayList<>();\n\n    socketFDs.add(mZygoteSocket.getFileDescriptor());\n    peers.add(null);\n\n    while (true) {\n        // 轮询并等待来自客户端的连接请求\n        try {\n            ZygoteConnection connection = peers.get(pollIndex);\n\n            // 读取启动命令并执行\n            final Runnable command = connection.processOneCommand(this);\n            return command;  // 返回用于启动进程的命令\n        } catch (Exception e) {\n            // 异常处理\n        } finally {\n            // 关闭资源\n        }\n    }\n}\n\n```\n- `Zygote` 进程接收到 `ActivityManagerService` 发出的应用进程创建请求。\n\n#### 4.2 **通过 `Zygote.forkAndSpecialize()` 创建新进程**\n当 Zygote 接收到启动命令时，`processOneCommand()` 会解析命令参数，并调用 `forkAndSpecialize()` 创建新的子进程。\n子进程会进入到应用进程的初始化流程。\n```java\npublic Runnable processOneCommand(ZygoteServer zygoteServer) {\n    String[] args;\n    try {\n        args = Zygote.readArgumentList(mSocketReader);  // 从命令套接字读取启动参数\n    } catch (IOException ex) {\n        throw new IllegalStateException(\"IOException on command socket\", ex);\n    }\n\n    // 创建新进程\n    pid = Zygote.forkAndSpecialize(parsedArgs.mUid, parsedArgs.mGid, parsedArgs.mGids,\n            parsedArgs.mRuntimeFlags, rlimits, parsedArgs.mMountExternal, parsedArgs.mSeInfo,\n            parsedArgs.mNiceName, fdsToClose, fdsToIgnore, parsedArgs.mStartChildZygote,\n            parsedArgs.mInstructionSet, parsedArgs.mAppDataDir, parsedArgs.mIsTopApp,\n            parsedArgs.mPkgDataInfoList, parsedArgs.mWhitelistedDataInfoList,\n            parsedArgs.mBindMountAppDataDirs, parsedArgs.mBindMountAppStorageDirs);\n\n    try {\n        if (pid == 0) {\n            // 子进程中\n            zygoteServer.setForkChild();\n            zygoteServer.closeServerSocket();\n            IoUtils.closeQuietly(serverPipeFd);\n            return handleChildProc(parsedArgs, childPipeFd, parsedArgs.mStartChildZygote);  // 处理子进程启动\n        } else {\n            // 父进程中\n            IoUtils.closeQuietly(childPipeFd);\n            handleParentProc(pid, serverPipeFd);  // 处理父进程逻辑\n            return null;\n        }\n    } finally {\n        IoUtils.closeQuietly(childPipeFd);\n        IoUtils.closeQuietly(serverPipeFd);\n    }\n}\n\n```\n#### 4.3 **Zygote 初始化子进程**\n\n如果 `forkAndSpecialize()` 返回 `0`（表示当前是子进程），Zygote 会调用 `handleChildProc()` 来进一步处理子进程的初始化。\n\n```java\nprivate Runnable handleChildProc(ZygoteArguments parsedArgs,\n            FileDescriptor pipeFd, boolean isZygote) {\n    closeSocket();  // 关闭套接字\n\n    // 设置应用进程名称\n    Zygote.setAppProcessName(parsedArgs, TAG);\n\n    // 进行应用进程的初始化\n    if (parsedArgs.mInvokeWith != null) {\n        WrapperInit.execApplication(parsedArgs.mInvokeWith,\n                parsedArgs.mNiceName, parsedArgs.mTargetSdkVersion,\n                VMRuntime.getCurrentInstructionSet(),\n                pipeFd, parsedArgs.mRemainingArgs);\n        throw new IllegalStateException(\"WrapperInit.execApplication unexpectedly returned\");\n    } else {\n        if (!isZygote) {\n            return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,\n                    parsedArgs.mDisabledCompatChanges,\n                    parsedArgs.mRemainingArgs, null);  // 启动目标应用\n        } else {\n            return ZygoteInit.childZygoteInit(parsedArgs.mTargetSdkVersion,\n                    parsedArgs.mRemainingArgs, null);\n        }\n    }\n}\n\n```\n\n- **`zygoteInit()`**：调用 `ZygoteInit.zygoteInit()` 来初始化应用并启动目标应用的 `Activity`。\n```java\n    public static final Runnable zygoteInit(int targetSdkVersion, long[] disabledCompatChanges,\n            String[] argv, ClassLoader classLoader) {\n        if (RuntimeInit.DEBUG) {\n            Slog.d(RuntimeInit.TAG, \"RuntimeInit: Starting application from zygote\");\n        }\n\n        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, \"ZygoteInit\");\n        RuntimeInit.redirectLogStreams();\n\n        RuntimeInit.commonInit();\n        //在native层初始化\n        ZygoteInit.nativeZygoteInit();\n        //执行app的初始化，也就是调用main函数\n        return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv,\n                classLoader);\n    }\n\n```\n\n\n目标进程的创建是在native层完成，在`AndroidRuntime.cpp`中\n\n```cpp\nstatic void com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env, jobject clazz)\n{\n    gCurRuntime->onZygoteInit();\n}\n\n```\n\n`onZygoteInit()`实现在`app_main.cpp`中\n**frameworks/base/cmds/app_process/app_main.cpp**\n```cpp\n    virtual void onZygoteInit()\n    {\n        sp proc = ProcessState::self();\n        ALOGV(\"App process: starting thread pool.\\n\");\n        proc->startThreadPool();\n    }\n\n```\n\n**frameworks/native/libs/binder/ProcessState.cpp**\n```cpp\n\nvoid ProcessState::startThreadPool()\n{\n    AutoMutex _l(mLock);\n    if (!mThreadPoolStarted) {\n        mThreadPoolStarted = true;\n        spawnPooledThread(true);\n    }\n}\n\n```\n\n\n进程创建完，开始执行它的`main()`方法\n**frameworks/base/core/java/com/android/internal/os/RuntimeInit.java**\n\n```java\n\tprotected static Runnable applicationInit(int targetSdkVersion, long[] disabledCompatChanges,\n            String[] argv, ClassLoader classLoader) {\n        // If the application calls System.exit(), terminate the process\n        // immediately without running any shutdown hooks.  It is not possible to\n        // shutdown an Android application gracefully.  Among other things, the\n        // Android runtime shutdown hooks close the Binder driver, which can cause\n        // leftover running threads to crash before the process actually exits.\n        nativeSetExitWithoutCleanup(true);\n\n        VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);\n        VMRuntime.getRuntime().setDisabledCompatChanges(disabledCompatChanges);\n\n        final Arguments args = new Arguments(argv);\n\n        // The end of of the RuntimeInit event (see #zygoteInit).\n        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);\n\n        // Remaining arguments are passed to the start class's static main\n        //寻找静态main方法\n        return findStaticMain(args.startClass, args.startArgs, classLoader);\n    }\n\n    protected static Runnable findStaticMain(String className, String[] argv,\n            ClassLoader classLoader) {\n        //通过反射找到main方法，\n        Class<?> cl;\n        //打印看看是调用的哪个类的main方法\n        Log.d(\"jasonwan\",\"className=\"+className);\n\n        try {\n            cl = Class.forName(className, true, classLoader);\n        } catch (ClassNotFoundException ex) {\n            throw new RuntimeException(\n                    \"Missing class when invoking static main \" + className,\n                    ex);\n        }\n\n        Method m;\n        try {\n            m = cl.getMethod(\"main\", new Class[] { String[].class });\n        } catch (NoSuchMethodException ex) {\n            throw new RuntimeException(\n                    \"Missing static main on \" + className, ex);\n        } catch (SecurityException ex) {\n            throw new RuntimeException(\n                    \"Problem getting static main on \" + className, ex);\n        }\n\t\t//main方法必须是public static\n        int modifiers = m.getModifiers();\n        if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {\n            throw new RuntimeException(\n                    \"Main method is not public and static on \" + className);\n        }\n\n        /*\n         * This throw gets caught in ZygoteInit.main(), which responds\n         * by invoking the exception's run() method. This arrangement\n         * clears up all the stack frames that were required in setting\n         * up the process.\n         */\n        //构建一个MethodAndArgsCaller，包含main方法和其参数\n        return new MethodAndArgsCaller(m, argv);\n    }\n\n```\n\n通过反射来获得android.app.ActivityThread类\n获得ActivityThread的main函数\n\n**frameworks/base/core/java/com/android/internal/os/RuntimeInit.java**\n```java\n public static class MethodAndArgsCaller extends Exception\n            implements Runnable {\n        private final Method mMethod;\n        private final String[] mArgs;\n        public MethodAndArgsCaller(Method method, String[] args) {\n            mMethod = method;\n            mArgs = args;\n        }\n        public void run() {\n            try {\n                mMethod.invoke(null, new Object[] { mArgs });//1\n            } catch (IllegalAccessException ex) {\n                throw new RuntimeException(ex);\n            }\n            ...\n                throw new RuntimeException(ex);\n            }\n        }\n    }\n\n```\n\n---\n\n### 5. **应用进程初始化：ActivityThread 启动应用**\n\n\n#### 5.1 **执行 `ActivityThread.main()`**\n- 子进程开始执行 `ActivityThread.main()`，这是应用主线程的入口，启动应用进程并完成基本的初始化工作。\n**frameworks/base/core/java/android/app/ActivityThread.java**\n```java\n public static void main(String[] args) {\n        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, \"ActivityThreadMain\");\n        SamplingProfilerIntegration.start();\n...\n        Looper.prepareMainLooper();//1\n        ActivityThread thread = new ActivityThread();//2\n        thread.attach(false);\n        if (sMainThreadHandler == null) {\n            sMainThreadHandler = thread.getHandler();\n        }\n        if (false) {\n            Looper.myLooper().setMessageLogging(new\n                    LogPrinter(Log.DEBUG, \"ActivityThread\"));\n        }\n        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);\n        Looper.loop();//3\n        throw new RuntimeException(\"Main thread loop unexpectedly exited\");\n    }\n\n\n```\n\n在当前应用程序进程中创建消息循环\n创建ActivityThread\n调用Looper的loop，使得Looper开始工作，开始处理消息。\n\n\n#### 5.2 **初始化 `Application` 对象**\n- 在 `ActivityThread.main()` 中，系统会创建 `Application` 对象，这是每个 Android 应用的基础组件，负责初始化整个应用环境。\n\n```java\npublic void attach(boolean system) {\n    if (mSystemContext == null) {\n        mSystemContext = ContextImpl.createSystemContext(this); // 初始化系统上下文\n    }\n    if (!system) {\n        mInitialApplication = makeApplication(true, mInstrumentation); // 创建应用对象\n    }\n    ...\n}\n\n```\n\n- `Application` 是 Android 应用中唯一存在的全局对象，整个应用在生命周期内只会创建一个实例，负责应用级别的初始化任务。\n- 它通常用于处理全局初始化任务，如配置文件加载、第三方 SDK 初始化、单例模式对象的创建等。\n\n#### 5.3 **启动目标 Activity**\n- `ActivityThread` 会通过 `Instrumentation` 启动目标应用的主 `Activity`，并通过 `Activity` 生命周期管理方法确保目标 `Activity` 正常启动。\n\n```java\npublic Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {\n    ...\n    // 通过反射机制创建 Activity\n    activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);\n    ...\n}\n\n```\n- 启动过程涉及通过反射机制创建目标 `Activity` 的实例，并完成 `attach()` 和 `onCreate()` 等生命周期方法的调用。\n- `Activity` 启动后，会进入 `onStart()` 和 `onResume()` 等生命周期方法，确保 `Activity` 完全初始化并展示给用户。\n\n\n#### 5.4 **执行 `Activity` 生命周期方法**\n- `Activity` 在启动过程中会依次调用生命周期方法，如 `onCreate()`、`onStart()`、`onResume()` 等。这些方法是应用与用户进行交互时的关键时刻，负责设置界面、初始化数据和监听用户操作。\n```java\nprivate void performLifecycleSequence(ActivityClientRecord r, IntArray path, ClientTransaction transaction) {\n    ...\n    switch (state) {\n        case ON_CREATE:\n            mTransactionHandler.handleLaunchActivity(r, mPendingActions, null /* customIntent */);\n            break;\n        case ON_START:\n            mTransactionHandler.handleStartActivity(r, mPendingActions);\n            break;\n        case ON_RESUME:\n            mTransactionHandler.handleResumeActivity(r.token, false /* finalStateRequest */, r.isForward, \"LIFECYCLER_RESUME_ACTIVITY\");\n            break;\n        // 其他生命周期状态\n    }\n}\n\n```\n\n\nhttps://juejin.cn/post/7231439815647789113\nhttps://juejin.cn/post/6844903472010117133\nhttps://juejin.cn/post/7252586674578817061\n"
}
