finalProcessRecordstartProcessLocked(StringprocessName,ApplicationInfoinfo,booleanknownToBeDead,intintentFlags,StringhostingType,ComponentNamehostingName,booleanallowWhileBooting,booleanisolated,intisolatedUid,booleankeepIfLarge,StringabiOverride,StringentryPoint,String[]entryPointArgs,RunnablecrashHandler){longstartTime=SystemClock.elapsedRealtime();ProcessRecordapp;if(!isolated){// 传入的 isolated 参数为 false ,if 成立,并不是隔离的进程// 根据进程名称和用户 ID 得到应用程序进程,由于不存在,则为 null 。app=getProcessRecordLocked(processName,info.uid,keepIfLarge);checkTime(startTime,"startProcess: after getProcessRecord");// 省略部分代码}else{// If this is an isolated process, it can't re-use an existing process.app=null;}// 当进程已经被分配的 PID 时,if(app!=null&&app.pid>0){}// 应用程序进程不存在,创建新的进程if(app==null){checkTime(startTime,"startProcess: creating new process record");// 创建应用程序进程app=newProcessRecordLocked(info,processName,isolated,isolatedUid);if(app==null){}app.crashHandler=crashHandler;checkTime(startTime,"startProcess: done creating new process record");}else{// If this is a new package in the process, add the package to the listapp.addPackage(info.packageName,info.versionCode,mProcessStats);checkTime(startTime,"startProcess: added package to existing proc");}// 创建应用程序进程后,最终调用 startProcessLocked 方法startProcessLocked(app,hostingType,hostingNameStr,abiOverride,entryPoint,entryPointArgs);
privatefinalvoidstartProcessLocked(ProcessRecordapp,StringhostingType,StringhostingNameStr,StringabiOverride,StringentryPoint,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.// 在之前的函数调用中,entryPoint 参数为 null,则赋值为 android.app.ActivityThread 。booleanisActivityProcess=(entryPoint==null);if(entryPoint==null)entryPoint="android.app.ActivityThread";// 创建一个进程Process.ProcessStartResultstartResult=Process.start(entryPoint,app.processName,uid,uid,gids,debugFlags,mountExternal,app.info.targetSdkVersion,app.info.seinfo,requiredAbi,instructionSet,app.info.dataDir,entryPointArgs);// 省略部分代码app.setPid(startResult.pid);app.usingWrapper=startResult.usingWrapper;app.removed=false;app.killed=false;app.killedByAm=false;checkTime(startTime,"startProcess: starting to update pids map");synchronized(mPidsSelfLocked){// app 类型为 ProcessRecord// 将 ProcessRecord 对象保存在 ActivityManagerService 类的成员变量 mPidsSelfLocked 中this.mPidsSelfLocked.put(startResult.pid,app);if(isActivityProcess){// 向 ActivityManagerService 所运行的线程的消息队列发送 PROC_START_TIMEOUT_MSG 类型的消息// 并指定这个消息在 PROC_START_TIMEOUT 毫秒后处理Messagemsg=mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);msg.obj=app;mHandler.sendMessageDelayed(msg,startResult.usingWrapper?PROC_START_TIMEOUT_WITH_WRAPPER:PROC_START_TIMEOUT);}}}
privatefinalbooleanattachApplicationLocked(IApplicationThreadthread,intpid){ProcessRecordapp;if(pid!=MY_PID&&pid>=0){synchronized(mPidsSelfLocked){app=mPidsSelfLocked.get(pid);}}else{app=null;}finalStringprocessName=app.processName;try{AppDeathRecipientadr=newAppDeathRecipient(app,pid,thread);thread.asBinder().linkToDeath(adr,0);app.deathRecipient=adr;}catch(RemoteExceptione){app.resetPackageList(mProcessStats);startProcessLocked(app,"link fail",processName);returnfalse;}app.makeActive(thread,mProcessStats);app.curAdj=app.setAdj=-100;app.curSchedGroup=app.setSchedGroup=Process.THREAD_GROUP_DEFAULT;app.forcingToForeground=null;updateProcessForegroundLocked(app,false,false);app.hasShownUi=false;app.debugging=false;app.cached=false;app.killedByAm=false;// 移除超时消息,应用程序在规定时间内完成了启动。mHandler.removeMessages(PROC_START_TIMEOUT_MSG,app);try{// 省略部分代码,跨进程调用 ActivityThread 的方法thread.bindApplication(processName,appInfo,providers,app.instrumentationClass,profilerInfo,app.instrumentationArguments,app.instrumentationWatcher,app.instrumentationUiAutomationConnection,testMode,enableOpenGlTrace,enableTrackAllocation,isRestrictedBackupMode||!normalMode,app.persistent,newConfiguration(mConfiguration),app.compat,getCommonServicesLocked(app.isolated),mCoreSettingsObserver.getCoreSettingsLocked());}catch(Exceptione){// }booleanbadApp=false;booleandidSomething=false;// See if the top visible activity is waiting to run in this process...// 调度 Activityif(normalMode){try{if(mStackSupervisor.attachApplicationLocked(app)){didSomething=true;}}catch(Exceptione){badApp=true;}}// Find any services that should be running in this process...// 调度 Serviceif(!badApp){try{didSomething|=mServices.attachApplicationLocked(app,processName);}catch(Exceptione){badApp=true;}}// Check if a next-broadcast receiver is in this process...// 调度 Broadcast if(!badApp&&isPendingBroadcastProcessLocked(pid)){try{didSomething|=sendPendingBroadcastsLocked(app);}catch(Exceptione){// If the app died trying to launch the receiver we declare it 'bad'badApp=true;}}}// ApplicationThread 的 bindApplication 方法publicfinalvoidbindApplication(StringprocessName,ApplicationInfoappInfo,List<ProviderInfo>providers,ComponentNameinstrumentationName,ProfilerInfoprofilerInfo,BundleinstrumentationArgs,IInstrumentationWatcherinstrumentationWatcher,IUiAutomationConnectioninstrumentationUiConnection,intdebugMode,booleanenableOpenGlTrace,booleantrackAllocation,booleanisRestrictedBackupMode,booleanpersistent,Configurationconfig,CompatibilityInfocompatInfo,Map<String,IBinder>services,BundlecoreSettings){if(services!=null){// Setup the service cache in the ServiceManagerServiceManager.initServiceCache(services);}setCoreSettings(coreSettings);AppBindDatadata=newAppBindData();data.processName=processName;data.appInfo=appInfo;data.providers=providers;data.instrumentationName=instrumentationName;data.instrumentationArgs=instrumentationArgs;data.instrumentationWatcher=instrumentationWatcher;data.instrumentationUiAutomationConnection=instrumentationUiConnection;data.debugMode=debugMode;data.enableOpenGlTrace=enableOpenGlTrace;data.trackAllocation=trackAllocation;data.restrictedBackupMode=isRestrictedBackupMode;data.persistent=persistent;data.config=config;data.compatInfo=compatInfo;data.initProfilerInfo=profilerInfo;// 向 ActivityThread 的应用程序主进程发送消息sendMessage(H.BIND_APPLICATION,data);}
privatevoidhandleBindApplication(AppBindDatadata){// send up app name; do this *before* waiting for debugger// 设置进程名Process.setArgV0(data.processName);// 创建 Android 运行环境 Context .finalContextImplappContext=ContextImpl.createAppContext(this,data.info);// 初始化 Intrumentation 对象if(data.instrumentationName!=null){try{java.lang.ClassLoadercl=instrContext.getClassLoader();mInstrumentation=(Instrumentation)cl.loadClass(data.instrumentationName.getClassName()).newInstance();}catch(Exceptione){}mInstrumentation.init(this,instrContext,appContext,newComponentName(ii.packageName,ii.name),data.instrumentationWatcher,data.instrumentationUiAutomationConnection);}else{mInstrumentation=newInstrumentation();}// Allow disk access during application and provider setup. This could// block processing ordered broadcasts, but later processing would// probably end up doing the same disk access.try{// If the app is being launched for full backup or restore, bring it up in// a restricted environment with the base application class.// 创建 Application 对象Applicationapp=data.info.makeApplication(data.restrictedBackupMode,null);mInitialApplication=app;// don't bring up providers in restricted mode; they may depend on the// app's custom Application classif(!data.restrictedBackupMode){List<ProviderInfo>providers=data.providers;if(providers!=null){installContentProviders(app,providers);// For process that contains content providers, we want to// ensure that the JIT is enabled "at some point".mH.sendEmptyMessageDelayed(H.ENABLE_JIT,10*1000);}}// Do this after providers, since instrumentation tests generally start their// test thread at this point, and we don't want that racing.try{mInstrumentation.onCreate(data.instrumentationArgs);}catch(Exceptione){}try{// 执行 Application 的 onCreate 方法mInstrumentation.callApplicationOnCreate(app);}catch(Exceptione){}}finally{}}
privatevoidhandleLaunchActivity(ActivityClientRecordr,IntentcustomIntent){// Initialize before creating the activityWindowManagerGlobal.initialize();Activitya=performLaunchActivity(r,customIntent);if(a!=null){r.createdConfig=newConfiguration(mConfiguration);BundleoldState=r.state;handleResumeActivity(r.token,false,r.isForward,!r.activity.mFinished&&!r.startsNotResumed);}else{// If there was an error, for any reason, tell the activity// manager to stop us.try{ActivityManagerNative.getDefault().finishActivity(r.token,Activity.RESULT_CANCELED,null,false);}catch(RemoteExceptionex){// Ignore}}
finalvoidhandleResumeActivity(IBindertoken,booleanclearHide,booleanisForward,booleanreallyResume){// TODO Push resumeArgs into the activity for consideration// 真正执行的是 performResumeActivity 方法ActivityClientRecordr=performResumeActivity(token,clearHide);if(r!=null){// 省略和 Window 相关代码}else{try{ActivityManagerNative.getDefault().finishActivity(token,Activity.RESULT_CANCELED,null,false);}catch(RemoteExceptionex){}}}