美文网首页
App启动全部过程

App启动全部过程

作者: zhi5ai | 来源:发表于2018-12-13 13:18 被阅读9次

    源码-app_main.cpp

    int main(int argc, char* const argv[])
    {
        if (!LOG_NDEBUG) {
          String8 argv_String;
          for (int i = 0; i < argc; ++i) {
            argv_String.append("\"");
            argv_String.append(argv[i]);
            argv_String.append("\" ");
          }
          ALOGV("app_process main with argv: %s", argv_String.string());
        }
        AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv));
        // Process command line arguments
        // ignore argv[0]
        argc--;
        argv++;
        // Everything up to '--' or first non '-' arg goes to the vm.
        //
        // The first argument after the VM args is the "parent dir", which
        // is currently unused.
        //
        // After the parent dir, we expect one or more the following internal
        // arguments :
        //
        // --zygote : Start in zygote mode
        // --start-system-server : Start the system server.
        // --application : Start in application (stand alone, non zygote) mode.
        // --nice-name : The nice name for this process.
        //
        // For non zygote starts, these arguments will be followed by
        // the main class name. All remaining arguments are passed to
        // the main method of this class.
        //
        // For zygote starts, all remaining arguments are passed to the zygote.
        // main function.
        //
        // Note that we must copy argument string values since we will rewrite the
        // entire argument block when we apply the nice name to argv0.
        //
        // As an exception to the above rule, anything in "spaced commands"
        // goes to the vm even though it has a space in it.
        const char* spaced_commands[] = { "-cp", "-classpath" };
        // Allow "spaced commands" to be succeeded by exactly 1 argument (regardless of -s).
        bool known_command = false;
        int i;
        for (i = 0; i < argc; i++) {
            if (known_command == true) {
              runtime.addOption(strdup(argv[i]));
              // The static analyzer gets upset that we don't ever free the above
              // string. Since the allocation is from main, leaking it doesn't seem
              // problematic. NOLINTNEXTLINE
              ALOGV("app_process main add known option '%s'", argv[i]);
              known_command = false;
              continue;
            }
            for (int j = 0;
                 j < static_cast<int>(sizeof(spaced_commands) / sizeof(spaced_commands[0]));
                 ++j) {
              if (strcmp(argv[i], spaced_commands[j]) == 0) {
                known_command = true;
                ALOGV("app_process main found known command '%s'", argv[i]);
              }
            }
            if (argv[i][0] != '-') {
                break;
            }
            if (argv[i][1] == '-' && argv[i][2] == 0) {
                ++i; // Skip --.
                break;
            }
            runtime.addOption(strdup(argv[i]));
            // The static analyzer gets upset that we don't ever free the above
            // string. Since the allocation is from main, leaking it doesn't seem
            // problematic. NOLINTNEXTLINE
            ALOGV("app_process main add option '%s'", argv[i]);
        }
        // Parse runtime arguments.  Stop at first unrecognized option.
        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;
                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()) {
            // We're not in zygote mode, the only argument we need to pass
            // to RuntimeInit is the application argument.
            //
            // The Remainder of args get passed to startup class main(). Make
            // copies of them before we overwrite them with the process name.
            args.add(application ? String8("application") : String8("tool"));
            runtime.setClassNameAndArgs(className, argc - i, argv + i);
            if (!LOG_NDEBUG) {
              String8 restOfArgs;
              char* const* argv_new = argv + i;
              int argc_new = argc - i;
              for (int k = 0; k < argc_new; ++k) {
                restOfArgs.append("\"");
                restOfArgs.append(argv_new[k]);
                restOfArgs.append("\" ");
              }
              ALOGV("Class name = %s, args = %s", className.string(), restOfArgs.string());
            }
        } else {
            // We're in zygote mode.
            maybeCreateDalvikCache();
            if (startSystemServer) {
                args.add(String8("start-system-server"));
            }
            char prop[PROP_VALUE_MAX];
            if (property_get(ABI_LIST_PROPERTY, prop, NULL) == 0) {
                LOG_ALWAYS_FATAL("app_process: Unable to determine ABI list from property %s.",
                    ABI_LIST_PROPERTY);
                return 11;
            }
            String8 abiFlag("--abi-list=");
            abiFlag.append(prop);
            args.add(abiFlag);
            // In zygote mode, pass all remaining arguments to the zygote
            // main() method.
            for (; i < argc; ++i) {
                args.add(String8(argv[i]));
            }
        }
        if (!niceName.isEmpty()) {
            runtime.setArgv0(niceName.string(), true /* setProcName */);
        }
        if (zygote) {
            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.");
        }
    }
    

    源码-ZygoteInit.java

    public static void main(String argv[]) {
            ZygoteServer zygoteServer = new ZygoteServer();
            // Mark zygote start. This ensures that thread creation will throw
            // an error.
            ZygoteHooks.startZygoteNoThreadCreation();
            // Zygote goes into its own process group.
            try {
                Os.setpgid(0, 0);
            } catch (ErrnoException ex) {
                throw new RuntimeException("Failed to setpgid(0,0)", ex);
            }
            final Runnable caller;
            try {
                // Report Zygote start time to tron unless it is a runtime restart
                if (!"1".equals(SystemProperties.get("sys.boot_completed"))) {
                    MetricsLogger.histogram(null, "boot_zygote_init",
                            (int) SystemClock.elapsedRealtime());
                }
                String bootTimeTag = Process.is64Bit() ? "Zygote64Timing" : "Zygote32Timing";
                TimingsTraceLog bootTimingsTraceLog = new TimingsTraceLog(bootTimeTag,
                        Trace.TRACE_TAG_DALVIK);
                bootTimingsTraceLog.traceBegin("ZygoteInit");
                RuntimeInit.enableDdms();
                boolean startSystemServer = false;
                String socketName = "zygote";
                String abiList = null;
                boolean enableLazyPreload = false;
                for (int i = 1; i < argv.length; i++) {
                    if ("start-system-server".equals(argv[i])) {
                        startSystemServer = true;
                    } else if ("--enable-lazy-preload".equals(argv[i])) {
                        enableLazyPreload = true;
                    } else if (argv[i].startsWith(ABI_LIST_ARG)) {
                        abiList = argv[i].substring(ABI_LIST_ARG.length());
                    } else if (argv[i].startsWith(SOCKET_NAME_ARG)) {
                        socketName = argv[i].substring(SOCKET_NAME_ARG.length());
                    } else {
                        throw new RuntimeException("Unknown command line argument: " + argv[i]);
                    }
                }
                if (abiList == null) {
                    throw new RuntimeException("No ABI list supplied.");
                }
                zygoteServer.registerServerSocketFromEnv(socketName);
                // In some configurations, we avoid preloading resources and classes eagerly.
                // In such cases, we will preload things prior to our first fork.
                if (!enableLazyPreload) {
                    bootTimingsTraceLog.traceBegin("ZygotePreload");
                    EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,
                        SystemClock.uptimeMillis());
                    preload(bootTimingsTraceLog);
                    EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,
                        SystemClock.uptimeMillis());
                    bootTimingsTraceLog.traceEnd(); // ZygotePreload
                } else {
                    Zygote.resetNicePriority();
                }
                // Do an initial gc to clean up after startup
                bootTimingsTraceLog.traceBegin("PostZygoteInitGC");
                gcAndFinalize();
                bootTimingsTraceLog.traceEnd(); // PostZygoteInitGC
                bootTimingsTraceLog.traceEnd(); // ZygoteInit
                // Disable tracing so that forked processes do not inherit stale tracing tags from
                // Zygote.
                Trace.setTracingEnabled(false, 0);
                Zygote.nativeSecurityInit();
                // Zygote process unmounts root storage spaces.
                Zygote.nativeUnmountStorageOnInit();
                ZygoteHooks.stopZygoteNoThreadCreation();
                if (startSystemServer) {
                    Runnable r = forkSystemServer(abiList, socketName, zygoteServer);  //fork 出SystemServer子进程
                    // {@code r == null} in the parent (zygote) process, and {@code r != null} in the
                    // child (system_server) process.
                    if (r != null) {
                        r.run();
                        return;
                    }
                }
                Log.i(TAG, "Accepting command socket connections");
                // The select loop returns early in the child process after a fork and
                // loops forever in the zygote.
                caller = zygoteServer.runSelectLoop(abiList);
            } catch (Throwable ex) {
                Log.e(TAG, "System zygote died with exception", ex);
                throw ex;
            } finally {
                zygoteServer.closeServerSocket();
            }
            // We're in the child process and have exited the select loop. Proceed to execute the
            // command.
            if (caller != null) {
                caller.run();
            }
        }
    
    static void preload(TimingsTraceLog bootTimingsTraceLog) {
            Log.d(TAG, "begin preload");
            bootTimingsTraceLog.traceBegin("BeginPreload");
            beginPreload();
            bootTimingsTraceLog.traceEnd(); // BeginPreload
            bootTimingsTraceLog.traceBegin("PreloadClasses");
            preloadClasses();
            bootTimingsTraceLog.traceEnd(); // PreloadClasses
            bootTimingsTraceLog.traceBegin("PreloadResources");
            preloadResources();
            bootTimingsTraceLog.traceEnd(); // PreloadResources
            Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "PreloadAppProcessHALs");
            nativePreloadAppProcessHALs();
            Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
            Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "PreloadOpenGL");
            preloadOpenGL();
            Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
            preloadSharedLibraries();
            preloadTextResources();
            // Ask the WebViewFactory to do any initialization that must run in the zygote process,
            // for memory sharing purposes.
            WebViewFactory.prepareWebViewInZygote();
            endPreload();
            warmUpJcaProviders();
            Log.d(TAG, "end preload");
            sPreloadComplete = true;
        }
    
     /**
         * Prepare the arguments and forks for the system server process.
         *
         * Returns an {@code Runnable} that provides an entrypoint into system_server code in the
         * child process, and {@code null} in the parent.
         */
        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,
                OsConstants.CAP_BLOCK_SUSPEND
            );
            /* Containers run without some capabilities, so drop any caps that are not available. */
            StructCapUserHeader header = new StructCapUserHeader(
                    OsConstants._LINUX_CAPABILITY_VERSION_3, 0);
            StructCapUserData[] data;
            try {
                data = Os.capget(header);
            } catch (ErrnoException ex) {
                throw new RuntimeException("Failed to capget()", ex);
            }
            capabilities &= ((long) data[0].effective) | (((long) data[1].effective) << 32);
            /* 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,1024,1032,1065,3001,3002,3003,3006,3007,3009,3010",
                "--capabilities=" + capabilities + "," + capabilities,
                "--nice-name=system_server",
                "--runtime-args",
                "--target-sdk-version=" + VMRuntime.SDK_VERSION_CUR_DEVELOPMENT,
                "com.android.server.SystemServer",
            };
            ZygoteConnection.Arguments parsedArgs = null;
            int pid;
            try {
                parsedArgs = new ZygoteConnection.Arguments(args);
                ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
                ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);
                boolean profileSystemServer = SystemProperties.getBoolean(
                        "dalvik.vm.profilesystemserver", false);
                if (profileSystemServer) {
                    parsedArgs.runtimeFlags |= Zygote.PROFILE_SYSTEM_SERVER;
                }
                /* Request to fork the system server process */
                pid = Zygote.forkSystemServer(
                        parsedArgs.uid, parsedArgs.gid,
                        parsedArgs.gids,
                        parsedArgs.runtimeFlags,
                        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;
        }
    
    /**
         * Finish remaining work for the newly forked system server process.
         */
        private static Runnable handleSystemServerProcess(ZygoteConnection.Arguments parsedArgs) {
            // set umask to 0077 so new files and directories will default to owner-only permissions.
            Os.umask(S_IRWXG | S_IRWXO);
            if (parsedArgs.niceName != null) {
                Process.setArgV0(parsedArgs.niceName);
            }
            final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
            if (systemServerClasspath != null) {
                performSystemServerDexOpt(systemServerClasspath);
                // Capturing profiles is only supported for debug or eng builds since selinux normally
                // prevents it.
                boolean profileSystemServer = SystemProperties.getBoolean(
                        "dalvik.vm.profilesystemserver", false);
                if (profileSystemServer && (Build.IS_USERDEBUG || Build.IS_ENG)) {
                    try {
                        prepareSystemServerProfile(systemServerClasspath);
                    } catch (Exception e) {
                        Log.wtf(TAG, "Failed to set up system server profile", e);
                    }
                }
            }
            if (parsedArgs.invokeWith != null) {
                String[] args = parsedArgs.remainingArgs;
                // If we have a non-null system server class path, we'll have to duplicate the
                // existing arguments and append the classpath to it. ART will handle the classpath
                // correctly when we exec a new process.
                if (systemServerClasspath != null) {
                    String[] amendedArgs = new String[args.length + 2];
                    amendedArgs[0] = "-cp";
                    amendedArgs[1] = systemServerClasspath;
                    System.arraycopy(args, 0, amendedArgs, 2, args.length);
                    args = amendedArgs;
                }
                WrapperInit.execApplication(parsedArgs.invokeWith,
                        parsedArgs.niceName, parsedArgs.targetSdkVersion,
                        VMRuntime.getCurrentInstructionSet(), null, args);
                throw new IllegalStateException("Unexpected return from WrapperInit.execApplication");
            } else {
                ClassLoader cl = null;
                if (systemServerClasspath != null) {
                    cl = createPathClassLoader(systemServerClasspath, parsedArgs.targetSdkVersion);
                    Thread.currentThread().setContextClassLoader(cl);
                }
                /*
                 * Pass the remaining arguments to SystemServer.
                 */
                return ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);
            }
            /* should never reach here */
        }
    
    public static final Runnable zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) {
            if (RuntimeInit.DEBUG) {
                Slog.d(RuntimeInit.TAG, "RuntimeInit: Starting application from zygote");
            }
            Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");
            RuntimeInit.redirectLogStreams();
            RuntimeInit.commonInit();
            ZygoteInit.nativeZygoteInit();  // 注释 1
            return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader); // 注释 2
        }
    
    private static final native void nativeZygoteInit();
    

    AndroidRuntime.cpp

    static AndroidRuntime* gCurRuntime = NULL;
    
    /*
     * Code written in the Java Programming Language calls here from main().
     */
    static void com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
    {
        gCurRuntime->onZygoteInit();
    }
    
    /*
     * JNI registration.
     */
    int register_com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env)
    {
        const JNINativeMethod methods[] = {
            { "nativeZygoteInit", "()V",
                (void*) com_android_internal_os_ZygoteInit_nativeZygoteInit },
        };
        return jniRegisterNativeMethods(env, "com/android/internal/os/ZygoteInit",
            methods, NELEM(methods));
    }
    

    app_main.cpp

    virtual void onZygoteInit()
        {
            sp<ProcessState> proc = ProcessState::self();
            ALOGV("App process: starting thread pool.\n");
            proc->startThreadPool();
        }
    

    ProcessState

    void ProcessState::startThreadPool()
    {
        AutoMutex _l(mLock);
        if (!mThreadPoolStarted) {
            mThreadPoolStarted = true;
            spawnPooledThread(true);
        }
    }
    
    void ProcessState::spawnPooledThread(bool isMain)
    {
        if (mThreadPoolStarted) {
            String8 name = makeBinderThreadName();
            ALOGV("Spawning new pooled thread, name=%s\n", name.string());
            sp<Thread> t = new PoolThread(isMain);
            t->run(name.string());
        }
    }
    

    可以看出ZygoteInit.java的nativeZygoteInit方法主要就启动了Binder线程池。

    private static void applicationInit(int targetSdkVersion, String[] argv)
                throws ZygoteInit.MethodAndArgsCaller {
            // If the application calls System.exit(), terminate the process
            // immediately without running any shutdown hooks.  It is not possible to
            // shutdown an Android application gracefully.  Among other things, the
            // Android runtime shutdown hooks close the Binder driver, which can cause
            // leftover running threads to crash before the process actually exits.
            nativeSetExitWithoutCleanup(true);
            // We want to be fairly aggressive about heap utilization, to avoid
            // holding on to a lot of memory that isn't needed.
            VMRuntime.getRuntime().setTargetHeapUtilization(0.75f);
            VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);
            final Arguments args;
            try {
                args = new Arguments(argv);
            } catch (IllegalArgumentException ex) {
                Slog.e(TAG, ex.getMessage());
                // let the process exit
                return;
            }
            // Remaining arguments are passed to the start class's static main
            invokeStaticMain(args.startClass, args.startArgs);
        }
    

    源码-SystemServer.java

    /**
         * The main entry point from zygote.
         */
        public static void main(String[] args) {
            new SystemServer().run();
        }
    
    private void run() {
            try {
                traceBeginAndSlog("InitBeforeStartServices");
                // If a device's clock is before 1970 (before 0), a lot of
                // APIs crash dealing with negative numbers, notably
                // java.io.File#setLastModified, so instead we fake it and
                // hope that time from cell towers or NTP fixes it shortly.
                if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
                    Slog.w(TAG, "System clock is before 1970; setting to 1970.");
                    SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
                }
                //
                // Default the timezone property to GMT if not set.
                //
                String timezoneProperty =  SystemProperties.get("persist.sys.timezone");
                if (timezoneProperty == null || timezoneProperty.isEmpty()) {
                    Slog.w(TAG, "Timezone not set; setting to GMT.");
                    SystemProperties.set("persist.sys.timezone", "GMT");
                }
                // If the system has "persist.sys.language" and friends set, replace them with
                // "persist.sys.locale". Note that the default locale at this point is calculated
                // using the "-Duser.locale" command line flag. That flag is usually populated by
                // AndroidRuntime using the same set of system properties, but only the system_server
                // and system apps are allowed to set them.
                //
                // NOTE: Most changes made here will need an equivalent change to
                // core/jni/AndroidRuntime.cpp
                if (!SystemProperties.get("persist.sys.language").isEmpty()) {
                    final String languageTag = Locale.getDefault().toLanguageTag();
                    SystemProperties.set("persist.sys.locale", languageTag);
                    SystemProperties.set("persist.sys.language", "");
                    SystemProperties.set("persist.sys.country", "");
                    SystemProperties.set("persist.sys.localevar", "");
                }
                // The system server should never make non-oneway calls
                Binder.setWarnOnBlocking(true);
                // The system server should always load safe labels
                PackageItemInfo.setForceSafeLabels(true);
                // Default to FULL within the system server.
                SQLiteGlobal.sDefaultSyncMode = SQLiteGlobal.SYNC_MODE_FULL;
                // Deactivate SQLiteCompatibilityWalFlags until settings provider is initialized
                SQLiteCompatibilityWalFlags.init(null);
                // Here we go!
                Slog.i(TAG, "Entered the Android system server!");
                int uptimeMillis = (int) SystemClock.elapsedRealtime();
                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, uptimeMillis);
                if (!mRuntimeRestart) {
                    MetricsLogger.histogram(null, "boot_system_server_init", uptimeMillis);
                }
                // In case the runtime switched since last boot (such as when
                // the old runtime was removed in an OTA), set the system
                // property so that it is in sync. We can | xq oqi't do this in
                // libnativehelper's JniInvocation::Init code where we already
                // had to fallback to a different runtime because it is
                // running as root and we need to be the system user to set
                // the property. http://b/11463182
                SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
                // Mmmmmm... more memory!
                VMRuntime.getRuntime().clearGrowthLimit();
                // The system server has to run all of the time, so it needs to be
                // as efficient as possible with its memory usage.
                VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
                // Some devices rely on runtime fingerprint generation, so make sure
                // we've defined it before booting further.
                Build.ensureFingerprintProperty();
                // Within the system server, it is an error to access Environment paths without
                // explicitly specifying a user.
                Environment.setUserRequired(true);
                // Within the system server, any incoming Bundles should be defused
                // to avoid throwing BadParcelableException.
                BaseBundle.setShouldDefuse(true);
                // Within the system server, when parceling exceptions, include the stack trace
                Parcel.setStackTraceParceling(true);
                // Ensure binder calls into the system always run at foreground priority.
                BinderInternal.disableBackgroundScheduling(true);
                // Increase the number of binder threads in system_server
                BinderInternal.setMaxThreads(sMaxBinderThreads);
                // Prepare the main looper thread (this thread).
                android.os.Process.setThreadPriority(
                    android.os.Process.THREAD_PRIORITY_FOREGROUND);
                android.os.Process.setCanSelfBackground(false);
                Looper.prepareMainLooper();
                Looper.getMainLooper().setSlowLogThresholdMs(
                        SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
                // Initialize native services.
                System.loadLibrary("android_servers");
                // Check whether we failed to shut down last time we tried.
                // This call may not return.
                performPendingShutdown();
                // Initialize the system context.
                createSystemContext();
                // Create the system service manager.
                mSystemServiceManager = new SystemServiceManager(mSystemContext);
                mSystemServiceManager.setStartInfo(mRuntimeRestart,
                        mRuntimeStartElapsedTime, mRuntimeStartUptime);
                LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
                // Prepare the thread pool for init tasks that can be parallelized
                SystemServerInitThreadPool.get();
            } finally {
                traceEnd();  // InitBeforeStartServices
            }
            // Start services.
            try {
                traceBeginAndSlog("StartServices");
                startBootstrapServices();
                startCoreServices();
                startOtherServices();
                SystemServerInitThreadPool.shutdown();
            } catch (Throwable ex) {
                Slog.e("System", "******************************************");
                Slog.e("System", "************ Failure starting system services", ex);
                throw ex;
            } finally {
                traceEnd();
            }
            StrictMode.initVmDefaults(null);
            if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
                int uptimeMillis = (int) SystemClock.elapsedRealtime();
                MetricsLogger.histogram(null, "boot_system_server_ready", uptimeMillis);
                final int MAX_UPTIME_MILLIS = 60 * 1000;
                if (uptimeMillis > MAX_UPTIME_MILLIS) {
                    Slog.wtf(SYSTEM_SERVER_TIMING_TAG,
                            "SystemServer init took too long. uptimeMillis=" + uptimeMillis);
                }
            }
            // Diagnostic to ensure that the system is in a base healthy state. Done here as a common
            // non-zygote process.
            if (!VMRuntime.hasBootImageSpaces()) {
                Slog.wtf(TAG, "Runtime is not running with a boot image!");
            }
            // Loop forever.
            Looper.loop();
            throw new RuntimeException("Main thread loop unexpectedly exited");
        }
    
    
    private void createSystemContext() {
            ActivityThread activityThread = ActivityThread.systemMain(); // 获取ActivityThread对象
            mSystemContext = activityThread.getSystemContext();  // 获取系统的Context
            mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);  //  设置主题
            final Context systemUiContext = activityThread.getSystemUiContext();
            systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
        }
    

    --ActivityThread.java systemMain()

    @UnsupportedAppUsage
        public static ActivityThread systemMain() {
            // The system process on low-memory devices do not get to use hardware
            // accelerated drawing, since this can add too much overhead to the
            // process.
            if (!ActivityManager.isHighEndGfx()) {
                ThreadedRenderer.disable(true);
            } else {
                ThreadedRenderer.enableForegroundTrimming();
            }
            ActivityThread thread = new ActivityThread();
            thread.attach(true, 0);
            return thread;
        }
    
    /**
         * Starts the small tangle of critical services that are needed to get
         * the system off the ground.  These services have complex mutual dependencies
         * which is why we initialize them all in one place here.  Unless your service
         * is also entwined in these dependencies, it should be initialized in one of
         * the other functions.
         */
        private void startBootstrapServices() {
            Slog.i(TAG, "Reading configuration...");
            final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig";
            traceBeginAndSlog(TAG_SYSTEM_CONFIG);
            SystemServerInitThreadPool.get().submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);
            traceEnd();
            // Wait for installd to finish starting up so that it has a chance to
            // create critical directories such as /data/user with the appropriate
            // permissions.  We need this to complete before we initialize other services.
            traceBeginAndSlog("StartInstaller");
            Installer installer = mSystemServiceManager.startService(Installer.class);
            traceEnd();
            // In some cases after launching an app we need to access device identifiers,
            // therefore register the device identifier policy before the activity manager.
            traceBeginAndSlog("DeviceIdentifiersPolicyService");
            mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
            traceEnd();
            // Activity manager runs the show.
            traceBeginAndSlog("StartActivityManager");
            mActivityManagerService = mSystemServiceManager.startService(
                    ActivityManagerService.Lifecycle.class).getService();
            mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
            mActivityManagerService.setInstaller(installer);
            traceEnd();
            // Power manager needs to be started early because other services need it.
            // Native daemons may be watching for it to be registered so it must be ready
            // to handle incoming binder calls immediately (including being able to verify
            // the permissions for those calls).
            traceBeginAndSlog("StartPowerManager");
            mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
            traceEnd();
            // Now that the power manager has been started, let the activity manager
            // initialize power management features.
            traceBeginAndSlog("InitPowerManagement");
            mActivityManagerService.initPowerManagement();
            traceEnd();
            // Bring up recovery system in case a rescue party needs a reboot
            traceBeginAndSlog("StartRecoverySystemService");
            mSystemServiceManager.startService(RecoverySystemService.class);
            traceEnd();
            // Now that we have the bare essentials of the OS up and running, take
            // note that we just booted, which might send out a rescue party if
            // we're stuck in a runtime restart loop.
            RescueParty.noteBoot(mSystemContext);
            // Manages LEDs and display backlight so we need it to bring up the display.
            traceBeginAndSlog("StartLightsService");
            mSystemServiceManager.startService(LightsService.class);
            traceEnd();
            traceBeginAndSlog("StartSidekickService");
            // Package manager isn't started yet; need to use SysProp not hardware feature
            if (SystemProperties.getBoolean("config.enable_sidekick_graphics", false)) {
                mSystemServiceManager.startService(WEAR_SIDEKICK_SERVICE_CLASS);
            }
            traceEnd();
            // Display manager is needed to provide display metrics before package manager
            // starts up.
            traceBeginAndSlog("StartDisplayManager");
            mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
            traceEnd();
            // We need the default display before we can initialize the package manager.
            traceBeginAndSlog("WaitForDisplay");
            mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
            traceEnd();
            // Only run "core" apps if we're encrypting the device.
            String cryptState = VoldProperties.decrypt().orElse("");
            if (ENCRYPTING_STATE.equals(cryptState)) {
                Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
                mOnlyCore = true;
            } else if (ENCRYPTED_STATE.equals(cryptState)) {
                Slog.w(TAG, "Device encrypted - only parsing core apps");
                mOnlyCore = true;
            }
            // Start the package manager.
            if (!mRuntimeRestart) {
                MetricsLogger.histogram(null, "boot_package_manager_init_start",
                        (int) SystemClock.elapsedRealtime());
            }
            traceBeginAndSlog("StartPackageManagerService");
            mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
                    mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
            mFirstBoot = mPackageManagerService.isFirstBoot();
            mPackageManager = mSystemContext.getPackageManager();
            traceEnd();
            if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
                MetricsLogger.histogram(null, "boot_package_manager_init_ready",
                        (int) SystemClock.elapsedRealtime());
            }
            // Manages A/B OTA dexopting. This is a bootstrap service as we need it to rename
            // A/B artifacts after boot, before anything else might touch/need them.
            // Note: this isn't needed during decryption (we don't have /data anyways).
            if (!mOnlyCore) {
                boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt",
                        false);
                if (!disableOtaDexopt) {
                    traceBeginAndSlog("StartOtaDexOptService");
                    try {
                        OtaDexoptService.main(mSystemContext, mPackageManagerService);
                    } catch (Throwable e) {
                        reportWtf("starting OtaDexOptService", e);
                    } finally {
                        traceEnd();
                    }
                }
            }
            traceBeginAndSlog("StartUserManagerService");
            mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
            traceEnd();
            // Initialize attribute cache used to cache resources from packages.
            traceBeginAndSlog("InitAttributerCache");
            AttributeCache.init(mSystemContext);
            traceEnd();
            // Set up the Application instance for the system process and get started.
            traceBeginAndSlog("SetSystemProcess");
            mActivityManagerService.setSystemProcess();
            traceEnd();
            // DisplayManagerService needs to setup android.display scheduling related policies
            // since setSystemProcess() would have overridden policies due to setProcessGroup
            mDisplayManagerService.setupSchedulerPolicies();
            // Manages Overlay packages
            traceBeginAndSlog("StartOverlayManagerService");
            OverlayManagerService overlayManagerService = new OverlayManagerService(
                    mSystemContext, installer);
            mSystemServiceManager.startService(overlayManagerService);
            traceEnd();
            if (SystemProperties.getInt("persist.sys.displayinset.top", 0) > 0) {
                // DisplayManager needs the overlay immediately.
                overlayManagerService.updateSystemUiContext();
                LocalServices.getService(DisplayManagerInternal.class).onOverlayChanged();
            }
            // The sensor service needs access to package manager service, app ops
            // service, and permissions service, therefore we start it after them.
            // Start sensor service in a separate thread. Completion should be checked
            // before using it.
            mSensorServiceStart = SystemServerInitThreadPool.get().submit(() -> {
                TimingsTraceLog traceLog = new TimingsTraceLog(
                        SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
                traceLog.traceBegin(START_SENSOR_SERVICE);
                startSensorService();
                traceLog.traceEnd();
            }, START_SENSOR_SERVICE);
        }
    

    SystemServer中调用ActivityManagerService.setSystemProcess(), 将ActivityManagerService存储到ServiceManager中进行管理。
    源码-ActivityManagerService.java

    public void setSystemProcess() {
            try {
                ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
                        DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
                ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
                ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
                        DUMP_FLAG_PRIORITY_HIGH);
                ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
                ServiceManager.addService("dbinfo", new DbBinder(this));
                if (MONITOR_CPU_USAGE) {
                    ServiceManager.addService("cpuinfo", new CpuBinder(this),
                            /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
                }
                ServiceManager.addService("permission", new PermissionController(this));
                ServiceManager.addService("processinfo", new ProcessInfoService(this));
                ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
                        "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
                mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
                synchronized (this) {
                    ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0);
                    app.persistent = true;
                    app.pid = MY_PID;
                    app.maxAdj = ProcessList.SYSTEM_ADJ;
                    app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
                    synchronized (mPidsSelfLocked) {
                        mPidsSelfLocked.put(app.pid, app);
                    }
                    updateLruProcessLocked(app, false, null);
                    updateOomAdjLocked();
                }
            } catch (PackageManager.NameNotFoundException e) {
                throw new RuntimeException(
                        "Unable to find android system package", e);
            }
            // Start watching app ops after we and the package manager are up and running.
            mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null,
                    new IAppOpsCallback.Stub() {
                        @Override public void opChanged(int op, int uid, String packageName) {
                            if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) {
                                if (mAppOpsService.checkOperation(op, uid, packageName)
                                        != AppOpsManager.MODE_ALLOWED) {
                                    runInBackgroundDisabled(uid);
                                }
                            }
                        }
                    });
        }
    

    源码-SystemServiceManager.java

    /**
         * Starts a service by class name.
         *
         * @return The service instance.
         */
        @SuppressWarnings("unchecked")
        public SystemService startService(String className) {
            final Class<SystemService> serviceClass;
            try {
                serviceClass = (Class<SystemService>)Class.forName(className);
            } catch (ClassNotFoundException ex) {
                Slog.i(TAG, "Starting " + className);
                throw new RuntimeException("Failed to create service " + className
                        + ": service class not found, usually indicates that the caller should "
                        + "have called PackageManager.hasSystemFeature() to check whether the "
                        + "feature is available on this device before trying to start the "
                        + "services that implement it", ex);
            }
            return startService(serviceClass);
        }
        /**
         * Creates and starts a system service. The class must be a subclass of
         * {@link com.android.server.SystemService}.
         *
         * @param serviceClass A Java class that implements the SystemService interface.
         * @return The service instance, never null.
         * @throws RuntimeException if the service fails to start.
         */
        @SuppressWarnings("unchecked")
        public <T extends SystemService> T startService(Class<T> serviceClass) {
            try {
                final String name = serviceClass.getName();
                Slog.i(TAG, "Starting " + name);
                Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + name);
                // Create the service.
                if (!SystemService.class.isAssignableFrom(serviceClass)) {
                    throw new RuntimeException("Failed to create " + name
                            + ": service must extend " + SystemService.class.getName());
                }
                final T service;
                try {
                    Constructor<T> constructor = serviceClass.getConstructor(Context.class);
                    service = constructor.newInstance(mContext);
                } catch (InstantiationException ex) {
                    throw new RuntimeException("Failed to create service " + name
                            + ": service could not be instantiated", ex);
                } catch (IllegalAccessException ex) {
                    throw new RuntimeException("Failed to create service " + name
                            + ": service must have a public constructor with a Context argument", ex);
                } catch (NoSuchMethodException ex) {
                    throw new RuntimeException("Failed to create service " + name
                            + ": service must have a public constructor with a Context argument", ex);
                } catch (InvocationTargetException ex) {
                    throw new RuntimeException("Failed to create service " + name
                            + ": service constructor threw an exception", ex);
                }
                startService(service);
                return service;
            } finally {
                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
            }
        }
        public void startService(@NonNull final SystemService service) {
            // Register it.
            mServices.add(service);
            // Start it.
            long time = SystemClock.elapsedRealtime();
            try {
                service.onStart();
            } catch (RuntimeException ex) {
                throw new RuntimeException("Failed to start service " + service.getClass().getName()
                        + ": onStart threw an exception", ex);
            }
            warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
        }
    

    源码-ActivityManagerService.java

    public static final class Lifecycle extends SystemService {
            private final ActivityManagerService mService;
            public Lifecycle(Context context) {
                super(context);
                mService = new ActivityManagerService(context);
            }
            @Override
            public void onStart() {
                mService.start();
            }
            @Override
            public void onBootPhase(int phase) {
                mService.mBootPhase = phase;
                if (phase == PHASE_SYSTEM_SERVICES_READY) {
                    mService.mBatteryStatsService.systemServicesReady();
                    mService.mServices.systemServicesReady();
                }
            }
            @Override
            public void onCleanupUser(int userId) {
                mService.mBatteryStatsService.onCleanupUser(userId);
            }
            public ActivityManagerService getService() {
                return mService;
            }
        }
    
    
    
     private void start() {
            Process.removeAllProcessGroups();
            mProcessCpuThread.start();
            mBatteryStatsService.publish(mContext);
            mAppOpsService.publish(mContext);
            Slog.d("AppOps", "AppOpsService published");
            LocalServices.addService(ActivityManagerInternal.class, new LocalService());
        }
    
     private final class LocalService extends ActivityManagerInternal {
            @Override
            public void goingToSleep() {
                ActivityManagerService.this.goingToSleep();
            }
            @Override
            public void wakingUp() {
                ActivityManagerService.this.wakingUp();
            }
            @Override
            public int startIsolatedProcess(String entryPoint, String[] entryPointArgs,
                    String processName, String abiOverride, int uid, Runnable crashHandler) {
                return ActivityManagerService.this.startIsolatedProcess(entryPoint, entryPointArgs,
                        processName, abiOverride, uid, crashHandler);
            }
        }
    
    int startIsolatedProcess(String entryPoint, String[] entryPointArgs,
                String processName, String abiOverride, int uid, Runnable crashHandler) {
            synchronized(this) {
                ApplicationInfo info = new ApplicationInfo();
                // In general the ApplicationInfo.uid isn't neccesarily equal to ProcessRecord.uid.
                // For isolated processes, the former contains the parent's uid and the latter the
                // actual uid of the isolated process.
                // In the special case introduced by this method (which is, starting an isolated
                // process directly from the SystemServer without an actual parent app process) the
                // closest thing to a parent's uid is SYSTEM_UID.
                // The only important thing here is to keep AI.uid != PR.uid, in order to trigger
                // the |isolated| logic in the ProcessRecord constructor.
                info.uid = Process.SYSTEM_UID;
                info.processName = processName;
                info.className = entryPoint;
                info.packageName = "android";
                ProcessRecord proc = startProcessLocked(processName, info /* info */,
                        false /* knownToBeDead */, 0 /* intentFlags */, ""  /* hostingType */,
                        null /* hostingName */, true /* allowWhileBooting */, true /* isolated */,
                        uid, true /* keepIfLarge */, abiOverride, entryPoint, entryPointArgs,
                        crashHandler);
                return proc != null ? proc.pid : 0;
            }
        }
    
        private final void startProcessLocked(ProcessRecord app, String hostingType,
                String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) {
               ...
     // Start the process.  It will either succeed and return a result containing
                // the PID of the new process, or else throw a RuntimeException.
                boolean isActivityProcess = (entryPoint == null);
                if (entryPoint == null) entryPoint = "android.app.ActivityThread";
                checkTime(startTime, "startProcess: asking zygote to start proc");
                Process.ProcessStartResult startResult = Process.start(entryPoint,
                        app.processName, uid, uid, gids, debugFlags, mountExternal,
                        app.info.targetSdkVersion, app.info.seinfo, requiredAbi, instructionSet,
                        app.info.dataDir, entryPointArgs);
                ...
    

    源码-Process.java

    源码-ActivityThread.java

    public static void main(String[] args) {
            Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
            // CloseGuard defaults to true and can be quite spammy.  We
            // disable it here, but selectively enable it later (via
            // StrictMode) on debug builds, but using DropBox, not logs.
            CloseGuard.setEnabled(false);
            Environment.initForCurrentUser();
            // Set the reporter for event logging in libcore
            EventLogger.setReporter(new EventLoggingReporter());
            // Make sure TrustedCertificateStore looks in the right place for CA certificates
            final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
            TrustedCertificateStore.setDefaultUserDirectory(configDir);
            Process.setArgV0("<pre-initialized>");
            Looper.prepareMainLooper(); //初始化Looper
            // Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
            // It will be in the format "seq=114"
            long startSeq = 0;
            if (args != null) {
                for (int i = args.length - 1; i >= 0; --i) {
                    if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
                        startSeq = Long.parseLong(
                                args[i].substring(PROC_START_SEQ_IDENT.length()));
                    }
                }
            }
            ActivityThread thread = new ActivityThread();  //实例化一个ActivityThread
            thread.attach(false, startSeq);
            if (sMainThreadHandler == null) {
                sMainThreadHandler = thread.getHandler();
            }
            if (false) {
                Looper.myLooper().setMessageLogging(new
                        LogPrinter(Log.DEBUG, "ActivityThread"));
            }
            // End of event ActivityThreadMain.
            Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
            Looper.loop();  //主线程进入无限循环状态,等待接收信息
            throw new RuntimeException("Main thread loop unexpectedly exited");
        }
    
    1. 初始化主线程的Looper,主Handler。并使主线程进入等待接收Message消息的无限循环状态。
    2. 调用attach() 方法,发送出初始化Application的消息。
     @UnsupportedAppUsage
        private void attach(boolean system, long startSeq) {
            sCurrentActivityThread = this;
            mSystemThread = system;
            if (!system) {
                ...
                final IActivityManager mgr = ActivityManager.getService();
                try {
                    mgr.attachApplication(mAppThread, startSeq);
                } catch (RemoteException ex) {
                    throw ex.rethrowFromSystemServer();
                }       
            } 
           ...
            ViewRootImpl.addConfigCallback(configChangedCallback);
        }
    
    /**
         * @hide
         */
        public static IActivityManager getService() {
            return IActivityManagerSingleton.get();
        }
    
        private static final Singleton<IActivityManager> IActivityManagerSingleton =
                new Singleton<IActivityManager>() {
                    @Override
                    protected IActivityManager create() {
                        final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
                        final IActivityManager am = IActivityManager.Stub.asInterface(b);
                        return am;
                    }
                };
    
    
    

    源码-Activity.java
    API26中启动Activity时候,和AMS通信机制已经被改成AIDL方式

    @Override
        public void startActivity(Intent intent) {
            startActivityForResult(intent, -1);
        }
    
    public void startActivityForResult(Intent intent, int requestCode) {
            if (mParent == null) {
                Instrumentation.ActivityResult ar =
                    mInstrumentation.execStartActivity(
                        this, mMainThread.getApplicationThread(), mToken, this,
                        intent, requestCode);
                if (ar != null) {
                    mMainThread.sendActivityResult(
                        mToken, mEmbeddedID, requestCode, ar.getResultCode(),
                        ar.getResultData());
                }
                if (requestCode >= 0) {
                    // If this start is requesting a result, we can avoid making
                    // the activity visible until the result is received.  Setting
                    // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
                    // activity hidden during this time, to avoid flickering.
                    // This can only be done when a result is requested because
                    // that guarantees we will get information back when the
                    // activity is finished, no matter what happens to it.
                    mStartedActivity = true;
                }
            } else {
                mParent.startActivityFromChild(this, intent, requestCode);
            }
        }
    

    源码-Instrumentation.java

    @UnsupportedAppUsage
        public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, String target,
            Intent intent, int requestCode, Bundle options) {
            IApplicationThread whoThread = (IApplicationThread) contextThread;
            if (mActivityMonitors != null) {
                synchronized (mSync) {
                    final int N = mActivityMonitors.size();
                    for (int i=0; i<N; i++) {
                        final ActivityMonitor am = mActivityMonitors.get(i);
                        ActivityResult result = null;
                        if (am.ignoreMatchingSpecificIntents()) {
                            result = am.onStartActivity(intent);
                        }
                        if (result != null) {
                            am.mHits++;
                            return result;
                        } else if (am.match(who, null, intent)) {
                            am.mHits++;
                            if (am.isBlocking()) {
                                return requestCode >= 0 ? am.getResult() : null;
                            }
                            break;
                        }
                    }
                }
            }
            try {
                intent.migrateExtraStreamToClipData();
                intent.prepareToLeaveProcess(who);
                int result = ActivityManager.getService()
                    .startActivity(whoThread, who.getBasePackageName(), intent,
                            intent.resolveTypeIfNeeded(who.getContentResolver()),
                            token, target, requestCode, 0, null, options);
                checkStartActivityResult(result, intent);
            } catch (RemoteException e) {
                throw new RuntimeException("Failure from system", e);
            }
            return null;
        }
    

    源码-ActivityManager.java

    /**
         * @hide
         */
        @UnsupportedAppUsage
        public static IActivityManager getService() {
            return IActivityManagerSingleton.get();
        }
        @UnsupportedAppUsage
        private static final Singleton<IActivityManager> IActivityManagerSingleton =
                new Singleton<IActivityManager>() {
                    @Override
                    protected IActivityManager create() {
                        final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE); //获取到IBinder类型的ActivityManagerService的引用
                        final IActivityManager am = IActivityManager.Stub.asInterface(b);
                        return am;
                    }
                };
    
    public abstract class Singleton<T> {
        @UnsupportedAppUsage
        private T mInstance;
        protected abstract T create();
        @UnsupportedAppUsage
        public final T get() {
            synchronized (this) {
                if (mInstance == null) {
                    mInstance = create();
                }
                return mInstance;
            }
        }
    }
    

    ServiceManager.java

    /**
         * Cache for the "well known" services, such as WM and AM.
         */
        private static HashMap<String, IBinder> sCache = new HashMap<String, IBinder>();
    
    /**
         * Returns a reference to a service with the given name.
         *
         * @param name the name of the service to get
         * @return a reference to the service, or <code>null</code> if the service doesn't exist
         */
        public static IBinder getService(String name) {
            try {
                IBinder service = sCache.get(name);
                if (service != null) {
                    return service;
                } else {
                    return Binder.allowBlocking(rawGetService(name));
                }
            } catch (RemoteException e) {
                Log.e(TAG, "error in getService", e);
            }
            return null;
        }
    

    源码-ActivityManagerService.java

    @Override
        public final int startActivity(IApplicationThread caller, String callingPackage,
                Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
                int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
            return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
                    resultWho, requestCode, startFlags, profilerInfo, bOptions,
                    UserHandle.getCallingUserId());
        }
        @Override
        public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
                Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
                int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
            return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
                    resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
                    true /*validateIncomingUser*/);
        }
        public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
                Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
                int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
                boolean validateIncomingUser) {
            enforceNotIsolatedCaller("startActivity");
            userId = mActivityStartController.checkTargetUser(userId, validateIncomingUser,
                    Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
            // TODO: Switch to user app stacks here.
            return mActivityStartController.obtainStarter(intent, "startActivityAsUser")
                    .setCaller(caller)
                    .setCallingPackage(callingPackage)
                    .setResolvedType(resolvedType)
                    .setResultTo(resultTo)
                    .setResultWho(resultWho)
                    .setRequestCode(requestCode)
                    .setStartFlags(startFlags)
                    .setProfilerInfo(profilerInfo)
                    .setActivityOptions(bOptions)
                    .setMayWait(userId)
                    .execute();
        }
    

    源码-ActivityStartController.java

    /**
         * @return A starter to configure and execute starting an activity. It is valid until after
         *         {@link ActivityStarter#execute} is invoked. At that point, the starter should be
         *         considered invalid and no longer modified or used.
         */
        ActivityStarter obtainStarter(Intent intent, String reason) {
            return mFactory.obtain().setIntent(intent).setReason(reason);
        }
    

    源码-ActivityStarter.java:485

    /**
         * Starts an activity based on the request parameters provided earlier.
         * @return The starter result.
         */
        int execute() {
            try {
                // TODO(b/64750076): Look into passing request directly to these methods to allow
                // for transactional diffs and preprocessing.
                if (mRequest.mayWait) {
                    return startActivityMayWait(mRequest.caller, mRequest.callingUid,
                            mRequest.callingPackage, mRequest.intent, mRequest.resolvedType,
                            mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
                            mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,
                            mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig,
                            mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId,
                            mRequest.inTask, mRequest.reason,
                            mRequest.allowPendingRemoteAnimationRegistryLookup,
                            mRequest.originatingPendingIntent);
                } else {
                    return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,
                            mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo,
                            mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
                            mRequest.resultWho, mRequest.requestCode, mRequest.callingPid,
                            mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid,
                            mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions,
                            mRequest.ignoreTargetSecurity, mRequest.componentSpecified,
                            mRequest.outActivity, mRequest.inTask, mRequest.reason,
                            mRequest.allowPendingRemoteAnimationRegistryLookup,
                            mRequest.originatingPendingIntent);
                }
            } finally {
                onExecutionComplete();
            }
        }
    
    
    private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
                    IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                    int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
                    ActivityRecord[] outActivity) {
            int result = START_CANCELED;
            try {
                mService.mWindowManager.deferSurfaceLayout();
                result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                        startFlags, doResume, options, inTask, outActivity);
            } finally {
                // If we are not able to proceed, disassociate the activity from the task. Leaving an
                // activity in an incomplete state can lead to issues, such as performing operations
                // without a window container.
                final ActivityStack stack = mStartActivity.getStack();
                if (!ActivityManager.isStartResultSuccessful(result) && stack != null) {
                    stack.finishActivityLocked(mStartActivity, RESULT_CANCELED,
                            null /* intentResultData */, "startActivity", true /* oomAdj */);
                }
                mService.mWindowManager.continueSurfaceLayout();
            }
            postStartActivityProcessing(r, result, mTargetStack);
            return result;
        }
    

    相关文章

      网友评论

          本文标题:App启动全部过程

          本文链接:https://www.haomeiwen.com/subject/gxcphqtx.html