publicfinalvoidbindApplication(String processName,ApplicationInfo appInfo,List<ProviderInfo> providers,ComponentName instrumentationName,ProfilerInfo profilerInfo,Bundle instrumentationArgs,IInstrumentationWatcher instrumentationWatcher,IUiAutomationConnection instrumentationUiConnection,int debugMode,boolean enableBinderTracking,boolean trackAllocation,boolean isRestrictedBackupMode,boolean persistent,Configuration config,CompatibilityInfo compatInfo,Map services,Bundle coreSettings,String buildSerial,boolean autofillCompatibilityEnabled){if(services !=null){if(false){// Test code to make sure the app could see the passed-in services.for(Object oname : services.keySet()){if(services.get(oname)==null){continue;// AM just passed in a null service.}String name =(String) oname;// See b/79378449 about the following exemption.switch(name){case"package":caseContext.WINDOW_SERVICE:continue;}if(ServiceManager.getService(name)==null){Log.wtf(TAG,"Service "+ name +" should be accessible by this app");}}}// Setup the service cache in the ServiceManagerServiceManager.initServiceCache(services);}setCoreSettings(coreSettings);// 將各種數據保存下載AppBindData data =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.enableBinderTracking = enableBinderTracking;data.trackAllocation = trackAllocation;data.restrictedBackupMode = isRestrictedBackupMode;data.persistent = persistent;data.config = config;data.compatInfo = compatInfo;data.initProfilerInfo = profilerInfo;data.buildSerial = buildSerial;data.autofillCompatibilityEnabled = autofillCompatibilityEnabled;// 發送handler消息sendMessage(H.BIND_APPLICATION, data);}
接下來看看 Handler 接收 H.BIND_APPLICATION 消息是怎么處理的。
publicvoidhandleMessage(Message msg){if(DEBUG_MESSAGES)Slog.v(TAG,">>> handling: "+codeToString(msg.what));switch(msg.what){case BIND_APPLICATION:Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,"bindApplication");AppBindData data =(AppBindData)msg.obj;handleBindApplication(data);Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);break;
ActivityThread 中的 handleBindApplication(data);
privatevoidhandleBindApplication(AppBindData data){// ... 只貼出主要代碼try{// If the app is being launched for full backup or restore, bring it up in// 創建 applicationapp = data.info.makeApplication(data.restrictedBackupMode,null);// Propagate autofill compat stateapp.setAutofillCompatibilityEnabled(data.autofillCompatibilityEnabled);mInitialApplication = app;// don't bring up providers in restricted mode; they may depend on the// app's custom Application classif(!data.restrictedBackupMode){if(!ArrayUtils.isEmpty(data.providers)){installContentProviders(app, data.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(Exception e){thrownewRuntimeException("Exception thrown in onCreate() of "+ data.instrumentationName +": "+ e.toString(), e);}try{// 調用 appilcation 的 onCreate方法mInstrumentation.callApplicationOnCreate(app);}catch(Exception e){if(!mInstrumentation.onException(app, e)){thrownewRuntimeException("Unable to create application "+ app.getClass().getName()+": "+ e.toString(), e);}}}finally{// If the app targets < O-MR1, or doesn't change the thread policy// during startup, clobber the policy to maintain behavior of b/36951662if(data.appInfo.targetSdkVersion <Build.VERSION_CODES.O_MR1||StrictMode.getThreadPolicy().equals(writesAllowedPolicy)){StrictMode.setThreadPolicy(savedPolicy);}}}
voidscheduleTransaction(ClientTransaction transaction)throwsRemoteException{finalIApplicationThread client = transaction.getClient();transaction.schedule();if(!(client instanceofBinder)){// If client is not an instance of Binder - it's a remote call and at this point it is// safe to recycle the object. All objects used for local calls will be recycled after// the transaction is executed on client in ActivityThread.transaction.recycle();}}
/** Prepare and schedule transaction for execution. */voidscheduleTransaction(ClientTransaction transaction){transaction.preExecute(this);// 發送 HandlersendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);}
看一下 Handler 的 EXECUTE_TRANSACTION
case EXECUTE_TRANSACTION:finalClientTransaction transaction =(ClientTransaction) msg.obj;mTransactionExecutor.execute(transaction);if(isSystem()){// Client transactions inside system process are recycled on the client side// instead of ClientLifecycleManager to avoid being cleared before this// message is handled.transaction.recycle();}// TODO(lifecycler): Recycle locally scheduled transactions.break;
publicvoidexecuteCallbacks(ClientTransaction transaction){finalList<ClientTransactionItem> callbacks = transaction.getCallbacks();if(callbacks ==null){// No callbacks to execute, return early.return;}log("Resolving callbacks");finalIBinder token = transaction.getActivityToken();ActivityClientRecord r = mTransactionHandler.getActivityClient(token);// In case when post-execution state of the last callback matches the final state requested// for the activity in this transaction, we won't do the last transition here and do it when// moving to final state instead (because it may contain additional parameters from server).finalActivityLifecycleItem finalStateRequest = transaction.getLifecycleStateRequest();finalint finalState = finalStateRequest !=null? finalStateRequest.getTargetState(): UNDEFINED;// Index of the last callback that requests some post-execution state.finalint lastCallbackRequestingState =lastCallbackRequestingState(transaction);finalint size = callbacks.size();for(int i =0; i < size;++i){finalClientTransactionItem item = callbacks.get(i);log("Resolving callback: "+ item);finalint postExecutionState = item.getPostExecutionState();finalint closestPreExecutionState = mHelper.getClosestPreExecutionState(r,item.getPostExecutionState());if(closestPreExecutionState != UNDEFINED){cycleToPath(r, closestPreExecutionState);}// 執行了 item.execute 就是 LaunchActivityItem 的 executeitem.execute(mTransactionHandler, token, mPendingActions);item.postExecute(mTransactionHandler, token, mPendingActions);if(r ==null){// Launch activity request will create an activity record.r = mTransactionHandler.getActivityClient(token);}if(postExecutionState != UNDEFINED && r !=null){// Skip the very last transition and perform it by explicit state request instead.finalboolean shouldExcludeLastTransition =i == lastCallbackRequestingState && finalState == postExecutionState;cycleToPath(r, postExecutionState, shouldExcludeLastTransition);}}}
@OverridepublicActivityhandleLaunchActivity(ActivityClientRecord r,PendingTransactionActions pendingActions,Intent customIntent){// ... // 得到 activity 對象finalActivity a =performLaunchActivity(r, customIntent);if(a !=null){r.createdConfig =newConfiguration(mConfiguration);reportSizeConfigurations(r);if(!r.activity.mFinished && pendingActions !=null){pendingActions.setOldState(r.state);pendingActions.setRestoreInstanceState(true);pendingActions.setCallOnPostCreate(true);}}else{// If there was an error, for any reason, tell the activity manager to stop us.try{ActivityManager.getService().finishActivity(r.token,Activity.RESULT_CANCELED,null,Activity.DONT_FINISH_TASK_WITH_ACTIVITY);}catch(RemoteException ex){throw ex.rethrowFromSystemServer();}}return a;}
privatevoidexecuteLifecycleState(ClientTransaction transaction){// ...// Cycle to the state right before the final requested state.// 這里會繼續根據state調用其他的生命周期cycleToPath(r, lifecycleItem.getTargetState(),true/* excludeLastState */);// Execute the final transition with proper parameters.lifecycleItem.execute(mTransactionHandler, token, mPendingActions);lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);}
booleanresumeFocusedStackTopActivityLocked(ActivityStack targetStack,ActivityRecord target,ActivityOptions targetOptions){if(!readyToResume()){returnfalse;}if(targetStack !=null&&isFocusedStack(targetStack)){return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);}finalActivityRecord r = mFocusedStack.topRunningActivityLocked();if(r ==null||!r.isState(RESUMED)){mFocusedStack.resumeTopActivityUncheckedLocked(null,null);}elseif(r.isState(RESUMED)){// Kick off any lingering app transitions form the MoveTaskToFront operation.mFocusedStack.executeAppTransition(targetOptions);}returnfalse;}
booleanresumeTopActivityUncheckedLocked(ActivityRecord prev,ActivityOptions options){if(mStackSupervisor.inResumeTopActivity){// Don't even start recursing.returnfalse;}boolean result =false;try{// Protect against recursion.mStackSupervisor.inResumeTopActivity =true;// 調用 resumeTopActivityInnerLocked result =resumeTopActivityInnerLocked(prev, options);finalActivityRecord next =topRunningActivityLocked(true/* focusableOnly */);if(next ==null||!next.canTurnScreenOn()){checkReadyForSleep();}}finally{mStackSupervisor.inResumeTopActivity =false;}return result;}
finalbooleanrealStartActivityLocked(ActivityRecord r,ProcessRecord app,boolean andResume,boolean checkConfig)throwsRemoteException{mService.getLifecycleManager().scheduleTransaction(clientTransaction);}voidscheduleTransaction(ClientTransaction transaction)throwsRemoteException{finalIApplicationThread client = transaction.getClient();transaction.schedule();if(!(client instanceofBinder)){// If client is not an instance of Binder - it's a remote call and at this point it is// safe to recycle the object. All objects used for local calls will be recycled after// the transaction is executed on client in ActivityThread.transaction.recycle();}}
publicvoidhandleMessage(Message msg){switch(msg.what){case EXECUTE_TRANSACTION:finalClientTransaction transaction =(ClientTransaction) msg.obj;mTransactionExecutor.execute(transaction);if(isSystem()){// Client transactions inside system process are recycled on the client side// instead of ClientLifecycleManager to avoid being cleared before this// message is handled.transaction.recycle();}// TODO(lifecycler): Recycle locally scheduled transactions.break;}}
voidstartSpecificActivityLocked(ActivityRecord r,boolean andResume,boolean checkConfig){// Is this activity's application already running?ProcessRecord app = mService.getProcessRecordLocked(r.processName,r.info.applicationInfo.uid,true);getLaunchTimeTracker().setLaunchTime(r);if(app !=null&& app.thread !=null){try{if((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS)==0||!"android".equals(r.info.packageName)){// Don't add this if it is a platform component that is marked// to run in multiple processes, because this is actually// part of the framework so doesn't make sense to track as a// separate apk in the process.app.addPackage(r.info.packageName, r.info.applicationInfo.longVersionCode,mService.mProcessStats);}// real startrealStartActivityLocked(r, app, andResume, checkConfig);return;}catch(RemoteException e){Slog.w(TAG,"Exception when starting activity "+ r.intent.getComponent().flattenToShortString(), e);}// If a dead object exception was thrown -- fall through to// restart the application.}mService.startProcessLocked(r.processName, r.info.applicationInfo,true,0,"activity", r.intent.getComponent(),false,false,true);}
realStartActivityLocked
finalbooleanrealStartActivityLocked(ActivityRecord r,ProcessRecord app,boolean andResume,boolean checkConfig)throwsRemoteException{// ...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.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,r.persistentState, results, newIntents, mService.isNextTransitionForward(),profilerInfo));// Set desired final state.finalActivityLifecycleItem lifecycleItem;if(andResume){lifecycleItem =ResumeActivityItem.obtain(mService.isNextTransitionForward());}else{lifecycleItem =PauseActivityItem.obtain();}// 設置生命周期的狀態clientTransaction.setLifecycleStateRequest(lifecycleItem);// 執行生命周期的調用mService.getLifecycleManager().scheduleTransaction(clientTransaction);// ... }
voidscheduleTransaction(ClientTransaction transaction)throwsRemoteException{finalIApplicationThread client = transaction.getClient();transaction.schedule();if(!(client instanceofBinder)){// If client is not an instance of Binder - it's a remote call and at this point it is// safe to recycle the object. All objects used for local calls will be recycled after// the transaction is executed on client in ActivityThread.transaction.recycle();}}
case EXECUTE_TRANSACTION:finalClientTransaction transaction =(ClientTransaction) msg.obj;mTransactionExecutor.execute(transaction);if(isSystem()){// Client transactions inside system process are recycled on the client side// instead of ClientLifecycleManager to avoid being cleared before this// message is handled.transaction.recycle();}