com/android/internal/os/Zygote.java
staticintforkAndSpecialize(int uid,int gid,int[] gids,int runtimeFlags,int[][] rlimits,int mountExternal,String seInfo,String niceName,int[] fdsToClose,int[] fdsToIgnore,boolean startChildZygote,String instructionSet,String appDataDir,boolean isTopApp,String[] pkgDataInfoList,String[] allowlistedDataInfoList,boolean bindMountAppDataDirs,boolean bindMountAppStorageDirs){ZygoteHooks.preFork();int pid =nativeForkAndSpecialize(
uid, gid, gids, runtimeFlags, rlimits, mountExternal, seInfo, niceName, fdsToClose,
fdsToIgnore, startChildZygote, instructionSet, appDataDir, isTopApp,
pkgDataInfoList, allowlistedDataInfoList, bindMountAppDataDirs,
bindMountAppStorageDirs);if(pid ==0){// Note that this event ends at the end of handleChildProc,Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,"PostFork");// If no GIDs were specified, don't make any permissions changes based on groups.if(gids !=null&& gids.length >0){NetworkUtilsInternal.setAllowNetworkingForProcess(containsInetGid(gids));}}// Set the Java Language thread priority to the default value for new apps.Thread.currentThread().setPriority(Thread.NORM_PRIORITY);ZygoteHooks.postForkCommon();return pid;}
com/android/internal/os/RuntimeInit.java
protectedstaticRunnablefindStaticMain(String className,String[] argv,ClassLoader classLoader){Class<?> cl;try{
cl =Class.forName(className,true, classLoader);}catch(ClassNotFoundException ex){thrownewRuntimeException("Missing class when invoking static main "+ className,
ex);}Method m;try{
m = cl.getMethod("main",newClass[]{String[].class});// main函数}catch(NoSuchMethodException ex){thrownewRuntimeException("Missing static main on "+ className, ex);}catch(SecurityException ex){thrownewRuntimeException("Problem getting static main on "+ className, ex);}int modifiers = m.getModifiers();if(!(Modifier.isStatic(modifiers)&&Modifier.isPublic(modifiers))){thrownewRuntimeException("Main method is not public and static on "+ className);}/*
* This throw gets caught in ZygoteInit.main(), which responds
* by invoking the exception's run() method. This arrangement
* clears up all the stack frames that were required in setting
* up the process.
*/returnnewMethodAndArgsCaller(m, argv);}
android/app/ActivityThread.java
privatevoidattach(boolean system,long startSeq){
sCurrentActivityThread =this;
mConfigurationController =newConfigurationController(this);
mSystemThread = system;if(!system){android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",UserHandle.myUserId());RuntimeInit.setApplicationObject(mAppThread.asBinder());finalIActivityManager mgr =ActivityManager.getService();try{
mgr.attachApplication(mAppThread, startSeq);// 调用AMS的attachApplication函数}catch(RemoteException ex){throw ex.rethrowFromSystemServer();}// 省略...}else{// Don't set application object here -- if the system crashes,// we can't display an alert, we just want to die die die.android.ddm.DdmHandleAppName.setAppName("system_process",UserHandle.myUserId());try{
mInstrumentation =newInstrumentation();
mInstrumentation.basicInit(this);ContextImpl context =ContextImpl.createAppContext(this,getSystemContext().mPackageInfo);
mInitialApplication = context.mPackageInfo.makeApplication(true,null);
mInitialApplication.onCreate();}catch(Exception e){thrownewRuntimeException("Unable to instantiate Application():"+ e.toString(), e);}}// 省略...}
com/android/server/am/ActivityManagerService.java
@GuardedBy("this")privatebooleanattachApplicationLocked(@NonNullIApplicationThread thread,int pid,int callingUid,long startSeq){// Find the application record that is being attached... either via// the pid if we are running in multiple processes, or just pull the// next app record if we are emulating process with anonymous threads.ProcessRecord app;long startTime =SystemClock.uptimeMillis();long bindApplicationTimeMillis;if(pid != MY_PID && pid >=0){synchronized(mPidsSelfLocked){
app = mPidsSelfLocked.get(pid);// 获取ProcessRecord对象}// 省略异常校验代码...}else{
app =null;}// 省略异常校验代码...finalString processName = app.processName;try{AppDeathRecipient adr =newAppDeathRecipient(
app, pid, thread);
thread.asBinder().linkToDeath(adr,0);// binder died 异常回调绑定
app.setDeathRecipient(adr);}catch(RemoteException e){
app.resetPackageList(mProcessStats);
mProcessList.startProcessLocked(app,newHostingRecord("link fail", processName),
ZYGOTE_POLICY_FLAG_EMPTY);returnfalse;}// 省略代码....try{// 省略代码....checkTime(startTime,"attachApplicationLocked: immediately before bindApplication");
bindApplicationTimeMillis =SystemClock.elapsedRealtime();
mAtmInternal.preBindApplication(app.getWindowProcessController());finalActiveInstrumentation instr2 = app.getActiveInstrumentation();if(mPlatformCompat !=null){
mPlatformCompat.resetReporting(app.info);}finalProviderInfoList providerList =ProviderInfoList.fromList(providers);if(app.getIsolatedEntryPoint()!=null){// This is an isolated process which should just call an entry point instead of// being bound to an application.
thread.runIsolatedEntryPoint(
app.getIsolatedEntryPoint(), app.getIsolatedEntryPointArgs());}elseif(instr2 !=null){// APP自定义ActiveInstrumentation对象时,一般用于开发人员测试场景,启动流程
thread.bindApplication(processName, appInfo, providerList,
instr2.mClass,
profilerInfo, instr2.mArguments,
instr2.mWatcher,
instr2.mUiAutomationConnection, testMode,
mBinderTransactionTrackingEnabled, enableTrackAllocation,
isRestrictedBackupMode ||!normalMode, app.isPersistent(),newConfiguration(app.getWindowProcessController().getConfiguration()),
app.getCompat(),getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked(),
buildSerial, autofillOptions, contentCaptureOptions,
app.getDisabledCompatChanges(), serializedSystemFontMap);}else{// 默认情况下的流程
thread.bindApplication(processName, appInfo, providerList,null, profilerInfo,null,null,null, testMode,
mBinderTransactionTrackingEnabled, enableTrackAllocation,
isRestrictedBackupMode ||!normalMode, app.isPersistent(),newConfiguration(app.getWindowProcessController().getConfiguration()),
app.getCompat(),getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked(),
buildSerial, autofillOptions, contentCaptureOptions,
app.getDisabledCompatChanges(), serializedSystemFontMap);}// 省略代码...}catch(Exception e){// 省略异常流程...returnfalse;}// 省略启动Activity 或者 Service 流程...returntrue;}
com/android/server/am/ActivityManagerService.java
@GuardedBy("this")privatebooleanattachApplicationLocked(@NonNullIApplicationThread thread,int pid,int callingUid,long startSeq){// 省略bindApplication流程...boolean badApp =false;boolean didSomething =false;// See if the top visible activity is waiting to run in this process...if(normalMode){// 如果是正常启动流程try{// 最终调用到ActivityTaskSupervisor的realStartActivityLocked函数
didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());}catch(Exception e){Slog.wtf(TAG,"Exception thrown launching activities in "+ app, e);
badApp =true;}}// Find any services that should be running in this process...if(!badApp){try{// 启动Service流程
didSomething |= mServices.attachApplicationLocked(app, processName);checkTime(startTime,"attachApplicationLocked: after mServices.attachApplicationLocked");}catch(Exception e){Slog.wtf(TAG,"Exception thrown starting services in "+ app, e);
badApp =true;}}// 省略流程...if(!didSomething){updateOomAdjLocked(app,OomAdjuster.OOM_ADJ_REASON_PROCESS_BEGIN);// 更新进程优先级checkTime(startTime,"attachApplicationLocked: after updateOomAdjLocked");}// 省略代码...returntrue;}
booleanrealStartActivityLocked(ActivityRecord r,WindowProcessController proc,boolean andResume,boolean checkConfig)throwsRemoteException{// 省略代码...try{// 省略代码...try{// 省略准备参数的代码...// Create activity launch transaction.finalClientTransaction clientTransaction =ClientTransaction.obtain(
proc.getThread(), r.appToken);finalboolean isTransitionForward = r.isTransitionForward();
clientTransaction.addCallback(LaunchActivityItem.obtain(newIntent(r.intent),System.identityHashCode(r), r.info,// TODO: Have this take the merged configuration instead of separate global// and override configs.
mergedConfiguration.getGlobalConfiguration(),
mergedConfiguration.getOverrideConfiguration(), r.compat,
r.getFilteredReferrer(r.launchedFromPackage), task.voiceInteractor,
proc.getReportedProcState(), r.getSavedState(), r.getPersistentSavedState(),
results, newIntents, r.takeOptions(), isTransitionForward,
proc.createProfilerInfoIfNeeded(), r.assistToken, activityClientController,
r.createFixedRotationAdjustmentsIfNeeded(), r.shareableActivityToken,
r.getLaunchedFromBubble()));// Set desired final state.finalActivityLifecycleItem lifecycleItem;if(andResume){
lifecycleItem =ResumeActivityItem.obtain(isTransitionForward);// ActivityResume状态}else{
lifecycleItem =PauseActivityItem.obtain();}
clientTransaction.setLifecycleStateRequest(lifecycleItem);// 设置生命周期对象// Schedule transaction. 真正transaction流程,启动Activity
mService.getLifecycleManager().scheduleTransaction(clientTransaction);// 省略代码...}catch(RemoteException e){if(r.launchFailed){// This is the second time we failed -- finish activity and give up.Slog.e(TAG,"Second failure launching "+ r.intent.getComponent().flattenToShortString()+", giving up", e);
proc.appDied("2nd-crash");
r.finishIfPossible("2nd-crash",false/* oomAdj */);returnfalse;}// This is the first time we failed -- restart process and// retry.
r.launchFailed =true;
proc.removeActivity(r,true/* keepAssociation */);throw e;}}finally{endDeferResume();
proc.resumeConfigurationDispatch();}// 省略代码...returntrue;}