ActivityThread应用进程
android12-release
- Zygote进程
- SystemServer进程(即system_server)
- Launcher启动过程、AMS:startActivity桌面启动应用 缺少具体应用进程启动
1. 涉及进程
Zygote进程:init进程 fork 第一个Java进程,Zygote是所有Java进程的父进程,包括system_server进程以及所有的App进程都是Zygote的子进程,注意这里说的是子进程,而非子线程。system_server进程:启动和管理整个Java framework中服务。Launcher/APP进程:应用进程之间;应用进程内部处理。
2. 时序图

2.1 简明流程图

- Launcher/App发起:当从桌面启动应用,则发起进程便是Launcher所在进程;当从某App内启动远程进程,则发送进程便是该App所在进程。发起进程先通过
binder发送消息给system_server进程。 system_server进程:调用Process.start()方法,通过socket向zygote进程发送创建新进程的请求。zygote进程:在执行ZygoteInit.main()后便进入zygoteServer.runSelectLoop()循环体内,当有客户端连接时便会执行ZygoteConnection.processCommand()方法,最后fork出新的应用进程。新进程:执行handleChildProc()方法,最后调用ActivityThread.main()方法。
3. Launcher进程启动APP Activity
Launcher -->
Instrumentation--> AMS/ATMS
最终调用ActivityTaskSupervisor.startSpecificActivity,冷启动执行mService.startProcessAsync()先fork应用进程
ActivityTaskSupervisor.startSpecificActivity对应ActivityRecord没有运行ActivityThreadmService.startProcessAsync()通过ATMS调用到AMS中startProcess()

4. system_server进程中调用Process.start()方法
4.1 ProcessList中判断
frameworks/base/services/core/java/com/android/server/am/ProcessList.java
getProcessRecordLocked(processName, info.uid)判断是否已启动ProcessRecord

app==null创建app = newProcessRecordLocked(info, processName, isolated, isolatedUid, hostingRecord)startProcessLocked()重载方法层层调用
4.2 Process通过socket连接到Zygote
frameworks/base/core/java/android/os/Process.java
frameworks/base/core/java/android/os/ZygoteProcess.java
-
调用
startResult = Process.start()

-
argsForZygote数组保存了进程的uid、gid、groups、target-sdk-version、nice-name等一系列参数。 -
openZygoteSocketIfNeeded(abi)根据当前的abi来选择与zygote还是zygote64来进行通信。通过socket向Zygote进程发送消息。
private Process.ProcessStartResult startViaZygote(@NonNull final String processClass,@Nullable final String niceName,final int uid, final int gid,@Nullable final int[] gids,int runtimeFlags, int mountExternal,int targetSdkVersion,@Nullable String seInfo,@NonNull String abi,@Nullable String instructionSet,@Nullable String appDataDir,@Nullable String invokeWith,boolean startChildZygote,@Nullable String packageName,int zygotePolicyFlags,boolean isTopApp,@Nullable long[] disabledCompatChanges,@Nullable Map<String, Pair<String, Long>>pkgDataInfoMap,@Nullable Map<String, Pair<String, Long>>allowlistedDataInfoList,boolean bindMountAppsData,boolean bindMountAppStorageDirs,@Nullable String[] extraArgs)throws ZygoteStartFailedEx {ArrayList<String> argsForZygote = new ArrayList<>();// --runtime-args, --setuid=, --setgid=,// and --setgroups= must go firstargsForZygote.add("--runtime-args");argsForZygote.add("--setuid=" + uid);argsForZygote.add("--setgid=" + gid);// ... ...if (niceName != null) {argsForZygote.add("--nice-name=" + niceName);}// ... ...argsForZygote.add(processClass);if (extraArgs != null) {Collections.addAll(argsForZygote, extraArgs);}synchronized(mLock) {// The USAP pool can not be used if the application will not use the systems graphics// driver. If that driver is requested use the Zygote application start path.return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi),zygotePolicyFlags,argsForZygote);}
}
5. zygote进程中fork()\RuntimeInit.applicationInit()
5.1 fork()
frameworks/base/core/jni/com_android_internal_os_Zygote.cpp
相关日志
Zygote : Forked child process 26092
am_proc_start: [0,26092,10264,com.tencent.mobileqq,pre-top-activity,{com.tencent.mobileqq/com.tencent.mobileqq.activity.SplashActivity}]
am_proc_bound: [0,26092,com.tencent.mobileqq]
// Utility routine to fork a process from the zygote.
pid_t zygote::ForkCommon(JNIEnv* env, bool is_system_server,const std::vector<int>& fds_to_close,const std::vector<int>& fds_to_ignore,bool is_priority_fork,bool purge) {SetSignalHandlers();// Curry a failure function.auto fail_fn = std::bind(zygote::ZygoteFailure, env,is_system_server ? "system_server" : "zygote",nullptr, _1);// Temporarily block SIGCHLD during forks. The SIGCHLD handler might// log, which would result in the logging FDs we close being reopened.// This would cause failures because the FDs are not allowlisted.//// Note that the zygote process is single threaded at this point.BlockSignal(SIGCHLD, fail_fn);// ... ...pid_t pid = fork();if (pid == 0) {// ... ...} else {ALOGD("Forked child process %d", pid);}// ... ...return pid;
}
bionic/libc/bionic/fork.cpp
bionic/libc/bionic/pthread_atfork.cpp
fork()采用copy on write技术,这是linux创建进程的标准方法,调用一次,返回两次,返回值有3种类型。
- 父进程中,fork返回新创建的子进程的pid;
- 子进程中,fork返回0;
- 当出现错误时,fork返回负数。(当进程数超过上限或者系统内存不足时会出错)
int fork() {__bionic_atfork_run_prepare();int result = __clone_for_fork();if (result == 0) {// Disable fdsan and fdtrack post-fork, so we don't falsely trigger on processes that// fork, close all of their fds, and then exec.android_fdsan_set_error_level(ANDROID_FDSAN_ERROR_LEVEL_DISABLED);android_fdtrack_set_globally_enabled(false);// Reset the stack_and_tls VMA name so it doesn't end with a tid from the// parent process.__set_stack_and_tls_vma_name(true);__bionic_atfork_run_child();} else {__bionic_atfork_run_parent();}return result;
}
5.2 新创建APP进程进入handleChildProc
closeSocket()关闭Zygote socket连接Zygote.setAppProcessName(parsedArgs, TAG)设置APP进程名称ZygoteInit.zygoteInit() - ZygoteInit.nativeZygoteInit()JNI到app_main.cpp中AppRuntime的onZygoteInit()启动APP进程线程池proc->startThreadPool(),就是Binder线程

RuntimeInit.applicationInit()经过class反射调用到ActivityThread.main
private Runnable handleChildProc(ZygoteArguments parsedArgs,FileDescriptor pipeFd, boolean isZygote) {/** By the time we get here, the native code has closed the two actual Zygote* socket connections, and substituted /dev/null in their place. The LocalSocket* objects still need to be closed properly.*/closeSocket();Zygote.setAppProcessName(parsedArgs, TAG);// End of the postFork event.Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);if (parsedArgs.mInvokeWith != null) {WrapperInit.execApplication(parsedArgs.mInvokeWith,parsedArgs.mNiceName, parsedArgs.mTargetSdkVersion,VMRuntime.getCurrentInstructionSet(),pipeFd, parsedArgs.mRemainingArgs);// Should not get here.throw new IllegalStateException("WrapperInit.execApplication unexpectedly returned");} else {if (!isZygote) {return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,parsedArgs.mDisabledCompatChanges,parsedArgs.mRemainingArgs, null /* classLoader */);} else {return ZygoteInit.childZygoteInit(parsedArgs.mRemainingArgs /* classLoader */);}}
}
5.2 RuntimeInit.applicationInit()反射调用到ActivityThread.main
- 此处args.startClass为
android.app.ActivityThread
protected static Runnable applicationInit(int targetSdkVersion, long[] disabledCompatChanges,String[] argv, ClassLoader classLoader) {// 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);VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);VMRuntime.getRuntime().setDisabledCompatChanges(disabledCompatChanges);final Arguments args = new Arguments(argv);// The end of of the RuntimeInit event (see #zygoteInit).Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);// Remaining arguments are passed to the start class's static mainreturn findStaticMain(args.startClass, args.startArgs, classLoader);}
- 反射调用到ActivityThread.main()
Class<?> cl = Class.forName(className, true, classLoader);
Method m = cl.getMethod("main", new Class[] { String[].class });
mMethod.invoke(null, new Object[] { mArgs });
6. ActivityThread.main
- 如果是startActivity则将要进入Activity的onCreate/onStart/onResume等生命周期。
- 如果是startService则将要进入Service的onCreate等生命周期。
frameworks/base/core/java/android/app/ActivityThread.java
public static void main(String[] args) {Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");// Install selective syscall interceptionAndroidOs.install();// 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();// Make sure TrustedCertificateStore looks in the right place for CA certificatesfinal File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());TrustedCertificateStore.setDefaultUserDirectory(configDir);// Call per-process mainline module initialization.initializeMainlineModules();Process.setArgV0("<pre-initialized>");Looper.prepareMainLooper();// 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();thread.attach(false, startSeq);if (sMainThreadHandler == null) {sMainThreadHandler = thread.getHandler();}if (false) {Looper.myLooper().setMessageLogging(newLogPrinter(Log.DEBUG, "ActivityThread"));}// End of event ActivityThreadMain.Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);Looper.loop();throw new RuntimeException("Main thread loop unexpectedly exited");}












