Task.java
??? private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) { ? ? ? ... ??????? // 1.获取栈顶的activity ??????? ActivityRecord next = topRunningActivity(true /* focusableOnly */); ? ? ? ... ??????? //确保启动该activity的用户存在 ??????? if (!mAtmService.mAmInternal.hasStartedUserState(next.mUserId)) { ??????????? Slog.w(TAG, "Skipping resume of top activity " + next ??????????????????? + ": user " + next.mUserId + " is stopped"); ??????????? return false; ??????? } ? ? ? ... ? ? ? ? //暂停当前运行的activity ??????? boolean pausing = taskDisplayArea.pauseBackStacks(userLeaving, next); ??????? if (mResumedActivity != null) { ??????????? if (DEBUG_STATES) Slog.d(TAG_STATES, ??????????????????? "resumeTopActivityLocked: Pausing " + mResumedActivity); ? ? ? ? ? ?//暂停栈顶已激活的activity ??????????? pausing |=?startPausingLocked(userLeaving, false /* uiSleeping */, next); ??????? } ??????? if (pausing) { ?????????? ?if (DEBUG_SWITCH || DEBUG_STATES) Slog.v(TAG_STATES, ??????????????????? "resumeTopActivityLocked: Skip resume: need to start pausing"); ? ? ? ? ? ? ? ?... ??????????? if (next.attachedToProcess()) { ? ? ? ? ? ? ? ?... ??????????????? //启动目标Activity ??????????????? mAtmService.getAppWarningsLocked().onResumeActivity(next); ??????????????? next.app.setPendingUiCleanAndForceProcessStateUpTo(mAtmService.mTopProcessState); ??????????????? next.abortAndClearOptionsAnimation(); ??????????????? transaction.setLifecycleStateRequest( ??????????????????????? ResumeActivityItem.obtain(next.app.getReportedProcState(), ??????????????????????????????? dc.isNextTransitionForward())); ??????????????? mAtmService.getLifecycleManager().scheduleTransaction(transaction) ? ? ? ? ? ? ? ?... ??????? } else { ??????????? // 进程无关联,需要启动目标activity所在进程 ??????????? if (!next.hasBeenLaunched) { ?????? ?????????next.hasBeenLaunched = true; ??????????? } else { ??????????????? if (SHOW_APP_STARTING_PREVIEW) { ??????????????????? next.showStartingWindow(null /* prev */, false /* newTask */, ??????????????????????????? false /* taskSwich */); ????????????? ??} ??????????????? if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Restarting: " + next); ??????????? } ??????????? if (DEBUG_STATES) Slog.d(TAG_STATES, "resumeTopActivityLocked: Restarting " + next); ??????????? mStackSupervisor.startSpecificActivity(next, true, true); ??????? } ??????? return true; ??? } |
---|
获取栈顶已激活的activity进行暂停。
final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping, ??????????? ActivityRecord resuming) { ? ? ? ?... ? ? ? ??//获取栈顶已激活的activity ??????? ActivityRecord prev = mResumedActivity; ? ? ? ? ... ??????? if (prev.attachedToProcess()) { ?????????? ?if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Enqueueing pending pause: " + prev); ??????????? try { ??????????????? EventLogTags.writeWmPauseActivity(prev.mUserId, System.identityHashCode(prev), ??????????????????????? prev.shortComponentName, "userLeaving=" + userLeaving); ? ? ? ? ? ? ? ?... ? ? ? ? ? ? ??//通过Binder机制向应用进程发送消息 ??????????????? mAtmService.getLifecycleManager().scheduleTransaction(prev.app.getThread(), ??????????????????????? prev.appToken, PauseActivityItem.obtain(prev.finishing, userLeaving, ??????????????????????????????? prev.configChangeFlags, pauseImmediately)); ??????????? } catch (Exception e) { ??????????????? Slog.w(TAG, "Exception thrown during pause", e); ??????????????? mPausingActivity = null; ??????????????? mLastPausedActivity = null; ??????????????? mLastNoHistoryActivity = null; ??????????? } ??????? } else { ??????????? mPausingActivity = null; ??????????? mLastPausedActivity = null; ??????????? mLastNoHistoryActivity = null; ??????? } ? ? ? ?... ??? } |
---|
如果栈顶已激活activity的进程存在,开始执行状态转换。
ClientLifecycleManager.java。
??? void scheduleTransaction(@NonNull IApplicationThread client, @NonNull IBinder activityToken, ??????????? @NonNull ActivityLifecycleItem stateRequest) throws RemoteException { ? ? ? ?//获取ActivityThread代理 ??????? final ClientTransaction clientTransaction = transactionWithState(client, activityToken, ??????????????? stateRequest); ????????scheduleTransaction(clientTransaction); ??? } |
---|
获取activityThread代理。
??? void scheduleTransaction(ClientTransaction transaction) throws RemoteException { ??????? final IApplicationThread client = transaction.getClient(); ??????? transaction.schedule(); ??????? if (!(client instanceof Binder)) { ??????????? // 如果client不是Binder实例,则进行回收,在ActivityThread中执行 ??????????? transaction.recycle(); ??????? } ??? } |
---|
ClientTransaction.java.
??? public void schedule() throws RemoteException { ? ? ? ?mClient.scheduleTransaction(this); ??? } |
---|
按以下顺序安排事务:
1.主线程调用preExecute,触发所有需要在真正调度事务前执行完毕的工作。 2.发送事务的message到主线程。 3.主线程调用TransactionExecutor.execute,执行所有回调以及必要的生命周期事务。
mClient是ActivityThread的Binder对象,ActivityThread继承ClientTransactionHandler。
ClientTransactionHandler.java
??? void scheduleTransaction(ClientTransaction transaction) { ??????? transaction.preExecute(this); ??????? sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction); ? ?} |
---|
ActivityThread接收到消息后,会调用TransactionExecutor.execute执行生命周期转换。
TransactionExecutor.java
??? public void execute(ClientTransaction transaction) { ? ? ?... ? ? ? ? executeCallbacks(transaction); ? ? ? ??executeLifecycleState(transaction); ? ? ? ? mPendingActions.clear(); ??? } |
---|
检查目标状态并执行。
??? private void executeLifecycleState(ClientTransaction transaction) { ??????? final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest(); ??????? if (lifecycleItem == null) { ??????????? return; ??????? } ??????? final IBinder token = transaction.getActivityToken(); ??????? final ActivityClientRecord r = mTransactionHandler.getActivityClient(token); ??????? if (DEBUG_RESOLVER) { ??????????? Slog.d(TAG, tId(transaction) + "Resolving lifecycle state: " ????? ??????????????+ lifecycleItem + " for activity: " ??????????????????? + getShortActivityName(token, mTransactionHandler)); ??????? } ??????? if (r == null) { ??????????? return; ???? ???} ? ? ? ? //执行最终状态转换 ????????cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction); ??????? lifecycleItem.execute(mTransactionHandler, token, mPendingActions); ??????? lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions); ??? } |
---|
获取目标item,并执行目标item的execute以及postExecute。
PauseActivityItem.java
??? public void execute(ClientTransactionHandler client, ActivityClientRecord r, ??????????? PendingTransactionActions pendingActions) { ??????? Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityPause"); ??????? client.handlePauseActivity(r, mFinished, mUserLeaving, mConfigChanges, pendingActions, ??????????????? "PAUSE_ACTIVITY_ITEM"); ??????? Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER); ??? } |
---|
通过进程间调用,调用到ActivityThread的handlePauseActivity,再调用到performPauseActivity函数。
??? final Bundle performPauseActivity(IBinder token, boolean finished, String reason, ??????????? PendingTransactionActions pendingActions) { ??????? ActivityClientRecord r = mActivities.get(token); ??????? return r != null ??performPauseActivity(r, finished, reason, pendingActions) : null; ??? } |
---|
??? private Bundle performPauseActivity(ActivityClientRecord r, boolean finished, String reason, ??????????? PendingTransactionActions pendingActions) { ??????? if (r.paused) { ? ? ? ? ... ????????performPauseActivityIfNeeded(r,?reason); ? ? ? ? ... ??????? return shouldSaveState ? r.state : null; ??? } |
---|
??? private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) { ??????? if (r.paused) { ??????????? // You are already paused silly... ??????????? return; ??????? } ??????? reportTopResumedActivityChanged(r, false /* onTop */, "pausing"); ??????? try { ??????????? r.activity.mCalled = false; ??????????? mInstrumentation.callActivityOnPause(r.activity); ???????? ???if (!r.activity.mCalled) { ??????????????? throw new SuperNotCalledException("Activity " + safeToComponentShortString(r.intent) ??????????????????????? + " did not call through to super.onPause()"); ??????????? } ??????? } catch (SuperNotCalledException e) { ??????????? throw e; ??????? } catch (Exception e) { ??????????? if (!mInstrumentation.onException(r.activity, e)) { ??????????????? throw new RuntimeException("Unable to pause activity " ??????????????????????? + safeToComponentShortString(r.intent) + ": " + e.toString(), e); ??????????? } ??????? } ??????? r.setState(ON_PAUSE); ??? } |
---|
调用到Instrumentation的callActivityOnPause函数中,之后进一步调用到Activity的onPause函数。
PauseActivityItem.java
???? @Override ??? public void?postExecute(ClientTransactionHandler client, IBinder token, ??????????? PendingTransactionActions pendingActions) { ????? ??if (mDontReport) { ??????????? return; ??????? } ? ? ? ? //Binder调用,Activity的onPause已经执行 ??????? ActivityClient.getInstance().activityPaused(token); ??? } |
---|
调用到ActivityClientController的activityPaused,进一步调用到ActivityRecord的activityPaused。
ActivityRecord.java
??? void activityPaused(boolean timeout) { ??????? ProtoLog.v(WM_DEBUG_STATES, "Activity paused: token=%s, timeout=%b", appToken, ??????????????? timeout); ??????? if (task != null) { ??????????? removePauseTimeout(); ??????????? final ActivityRecord pausingActivity = task.getPausingActivity(); ??????????? if (pausingActivity == this) { ??????????????? ProtoLog.v(WM_DEBUG_STATES, "Moving to PAUSED: %s %s", this, ??????????????????????? (timeout ? "(due to timeout)" : " (pause complete)")); ??????????????? mAtmService.deferWindowLayout(); ??????????????? try { ??????????????????? task.completePauseLocked(true /* resumeNext */, null /* resumingActivity */); ??????????????? } finally { ??????????????????? mAtmService.continueWindowLayout(); ??????????????? } ??????????????? return; ??????????? } else { ?????????? ?????EventLogTags.writeWmFailedToPause(mUserId, System.identityHashCode(this), ??????????????????????? shortComponentName, pausingActivity != null ??????????????????????????????? ? pausingActivity.shortComponentName : "(none)"); ??????????????? if (isState(PAUSING)) { ??????????????????? setState(PAUSED, "activityPausedLocked"); ??????????????????? if (finishing) { ??????????????????????? ProtoLog.v(WM_DEBUG_STATES, ??????????????????????????????? "Executing finish of failed to pause activity: %s", this); ??????????????????????? completeFinishing("activityPausedLocked"); ??????????????????? } ??????????????? } ??????????? } ??????? } ??????? mDisplayContent.handleActivitySizeCompatModeIfNeeded(this); ??????? mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS); ??? } |
---|
Task.java
??? void completePauseLocked(boolean resumeNext, ActivityRecord resuming) { ? ? ? ... ??????? ActivityRecord prev = mPausingActivity; ? ? ? ? ? ? ? ? ... ??????????????? prev.stopFreezingScreenLocked(true /*force*/); ? ? ? ? ? ? ? ?... ??????????? mPausingActivity = null; ??????? } ??????? if (resumeNext) { ??????????? final Task topRootTask = mRootWindowContainer.getTopDisplayFocusedRootTask(); ??????????? if (topRootTask != null && !topRootTask.shouldSleepOrShutDownActivities()) { ??????????????? mRootWindowContainer.resumeFocusedTasksTopActivities(topRootTask, prev, null); ? ? ? ? ? ... ??? } |
---|
RootWindowContainer.java
??boolean resumeFocusedTasksTopActivities( ? ? ? ? ? ?... ??????????? result |= resumedOnDisplay[0]; ??????????? if (!resumedOnDisplay[0]) { ??????????????? final Task focusedRoot = display.getFocusedRootTask(); ??????????????? if (focusedRoot != null) { ??????????????????? result |= focusedRoot.resumeTopActivityUncheckedLocked(target, targetOptions); ??????????????? } else if (targetRootTask == null) { ??????????????????? result |= resumeHomeActivity(null /* prev */, "no-focusable-task", ???????????????? ???????????display.getDefaultTaskDisplayArea()); ??????????????? } ??????????? } ??????? } ??????? return result; ??? } |
---|
??? @GuardedBy("mService") ??? boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options, ??????????? boolean deferPause) { ? ? ? ? ? ? ? ? ... ??????????????????? someActivityResumed |= child.resumeTopActivityUncheckedLocked(prev, options, ??????????????????????????? deferPause); ? ? ? ? ? ? ? ?... ??? } |
---|
??? private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options, ??????????? boolean deferPause) { ? ? ? ? ? ? ...? ? ? ? ? if (next.attachedToProcess()) { ? ? ? ? ? ? ... ??????????????? mAtmService.getAppWarningsLocked().onResumeActivity(next); ??????????????? next.app.setPendingUiCleanAndForceProcessStateUpTo(mAtmService.mTopProcessState); ??????????????? next.abortAndClearOptionsAnimation(); ??????????????? transaction.setLifecycleStateRequest( ??????????????????????? ResumeActivityItem.obtain(next.app.getReportedProcState(), ??????????????????????????????? dc.isNextTransitionForward())); ??????????????? mAtmService.getLifecycleManager().scheduleTransaction(transaction); ? ? ? ? ? ? ... ??????? } else?{ ? ? ? ? ? ? ... ??????????? ProtoLog.d(WM_DEBUG_STATES, "resumeTopActivityLocked: Restarting %s", next); ??????????? mTaskSupervisor.startSpecificActivity(next, true, true); ? ? ? ?} ??????? return true; ??? } |
---|
如果目标进程与当前进程是否有关系,如果有关系直接进行转化,如果没有关联,执行startSpecificActivity。
ActivityTaskSupervisor.java
??? void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) { ??????? // Is this activity's application already running? ??????? final WindowProcessController wpc = ??????????????? mService.getProcessController(r.processName,?r.info.applicationInfo.uid); ? ? ? ? ?... ??????? boolean knownToBeDead = false; ??????? if (wpc != null && wpc.hasThread()) { ??????????? try { ????????????????realStartActivityLocked(r, wpc, andResume, checkConfig); ? ? ? ? ? ? ? ? ... ? ? ? ? ? ?} ? ? ? ... ? ? ? mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity"); ??? } |
---|
判断目标进程是否创建,如果已经创建,执行realStartActivityLocked,最后启动目标activity的进程。
? boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc, ??????????? boolean andResume, boolean checkConfig) throws RemoteException { ? ? ? ? ?... ??????????????? clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(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, 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. ??????????????? final ActivityLifecycleItem lifecycleItem; ??????????????? if (andResume) { ??????????????????? lifecycleItem =?ResumeActivityItem.obtain(isTransitionForward); ??????????????? } else { ??????????????????? lifecycleItem = PauseActivityItem.obtain(); ??????????????? } ??????????????? clientTransaction.setLifecycleStateRequest(lifecycleItem); ??????????????? // Schedule transaction. ????????????? ??mService.getLifecycleManager().scheduleTransaction(clientTransaction); ? ? ? ? ? ? ? ? ... ??????? return true; ??? } |
---|
调用LaunchActivityItem.java,启动应用程序。
启动进程:
ActivityTaskManagerService.java
? ??void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop, ??????????? String hostingType) { ??????? try { ??????????? if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) { ??????????????? Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:" ??????????????????????? + activity.processName); ??????????? } ??????????? final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess, ??????????????????? mAmInternal, activity.processName,?activity.info.applicationInfo, knownToBeDead, ??????????????????? isTop, hostingType, activity.intent.getComponent()); ??????????? mH.sendMessage(m); ??????? } finally { ??????????? Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER); ??????? } ??? } |
---|
通过进程间通信,调用到AMS的startProcessLocked。
ActivityManagerService.java
??? final ProcessRecord startProcessLocked(String processName, ??????????? ApplicationInfo info, boolean knownToBeDead, int intentFlags, ??????????? HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting, ??????????? boolean isolated) { ??????? return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags, ??????????????? hostingRecord, zygotePolicyFlags, allowWhileBooting, isolated, 0 /* isolatedUid */, ??????????????? null /* ABI override */, null /* entryPoint */, ??????????????? null /* entryPointArgs */, null /* crashHandler */); ??? } |
---|
ProcessList.java
?@GuardedBy("mService") ??? ProcessRecord startProcessLocked(String processName, ApplicationInfo info, ??????????? boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord, ??????????? int zygotePolicyFlags, boolean allowWhileBooting, boolean isolated, int isolatedUid, ??????????? String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) { ? ? ? ? ... ??????? ProcessRecord predecessor = null; ??????? if (app != null && app.getPid() > 0) { ? ? ? ? ? ? ? ? ... ????????????????return?app; ??????????? } ? ? ? ? ... ??????? final boolean success = ????????????????startProcessLocked(app, hostingRecord, zygotePolicyFlags, abiOverride); ??????? checkSlow(startTime, "startProcess: done starting proc!"); ??????? return success ? app : null; ??? } |
---|
??? boolean startProcessLocked(HostingRecord hostingRecord, String entryPoint, ProcessRecord app, ??????????? int uid, int[] gids, int runtimeFlags, int zygotePolicyFlags, int mountExternal, ??????????? String seInfo, String requiredAbi, String instructionSet, String invokeWith, ??????????? long startTime) { ? ? ? ? ... ??????? if (mService.mConstants.FLAG_PROCESS_START_ASYNC) { ??????????? if (DEBUG_PROCESSES) Slog.i(TAG_PROCESSES, ??????????????????? "Posting procStart msg for " + app.toShortString()); ??????????? mService.mProcStartHandler.post(() -> handleProcessStart( ??????????????????? app, entryPoint, gids, runtimeFlags, zygotePolicyFlags, mountExternal, ??????????????????? requiredAbi, instructionSet, invokeWith, startSeq)); ??????????? return true; ??????? } else { ??????????? try { ??????????????? final Process.ProcessStartResult startResult =?startProcess(hostingRecord, ??????????????????????? entryPoint, app, ??????????????????????? uid, gids, runtimeFlags, zygotePolicyFlags, mountExternal, seInfo, ??????????????????????? requiredAbi, instructionSet, invokeWith, startTime); ??????????????? handleProcessStartedLocked(app, startResult.pid, startResult.usingWrapper, ??????????????????????? startSeq, false); ??????????? } catch (RuntimeException e) { ??????????????? Slog.e(ActivityManagerService.TAG, "Failure starting process " ??????????????????????? + app.processName, e); ??????????????? app.setPendingStart(false); ??????????????? mService.forceStopPackageLocked(app.info.packageName, UserHandle.getAppId(app.uid), ??????????????????????? false, false, true, false, false, app.userId, "start failure"); ??????????? } ??????????? return app.getPid() > 0; ??????? } ??? } |
---|
??? private Process.ProcessStartResult startProcess(HostingRecord hostingRecord, String entryPoint, ??????????? ProcessRecord app, int uid, int[] gids, int runtimeFlags, int zygotePolicyFlags, ?????? ?????int mountExternal, String seInfo, String requiredAbi, String instructionSet, ??????????? String invokeWith, long startTime) { ? ? ? ? ? ? ... ??????????? final Process.ProcessStartResult startResult; ??????? ????boolean regularZygote = false; ??????????? if (hostingRecord.usesWebviewZygote()) { ??????????????? startResult = startWebView(entryPoint, ??????????????????????? app.processName, uid, uid, gids, runtimeFlags, mountExternal, ????????????????????????app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet, ????????????????????????app.info.dataDir, null,?app.info.packageName, ??????????????????????? app.getDisabledCompatChanges(), ??????????????????????? new String[]{PROC_START_SEQ_IDENT + app.getStartSeq()}); ??????????? } else if (hostingRecord.usesAppZygote()) { ??????????????? final AppZygote appZygote = createAppZygoteForProcessIfNeeded(app); ??????????????? // zogyte启动进程 ????? ??????????startResult = appZygote.getProcess().start(entryPoint, ??????????????????????? app.processName, uid, uid, gids, runtimeFlags, mountExternal, ????????????????????????app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet, ???????????????? ???????app.info.dataDir, null,?app.info.packageName, ??????????????????????? /*zygotePolicyFlags=*/ ZYGOTE_POLICY_FLAG_EMPTY, isTopApp, ??????????????????????? app.getDisabledCompatChanges(), pkgDataInfoMap, allowlistedAppDataInfoMap, ???????????????????? ???false, false, ??????????????????????? new String[]{PROC_START_SEQ_IDENT + app.getStartSeq()}); ??????????? } else { ??????????????? regularZygote = true; ??????????????? startResult = Process.start(entryPoint, ??????????????????????? app.processName, uid, uid, gids, runtimeFlags, mountExternal, ????????????????????????app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet, ????????????????????????app.info.dataDir, invokeWith,?app.info.packageName, zygotePolicyFlags, ??????????????????????? isTopApp, app.getDisabledCompatChanges(), pkgDataInfoMap, ??????????????????????? allowlistedAppDataInfoMap, bindMountAppsData, bindMountAppStorageDirs, ??????????????????????? new String[]{PROC_START_SEQ_IDENT + app.getStartSeq()}); ??????????? } ? ? ? ?... ??? } |
---|
通过Zogyte进程启动应用程序进程,之后会实例化ActivityThread,反射获取main函数。
ActivityThread.java
??? public static void main(String[] args) { ??????? Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain"); ? ? ? ?... ??????? ActivityThread thread = new ActivityThread(); ??????? thread.attach(false, startSeq); ? ? ? ... ??? } |
---|
??? private void attach(boolean system, long startSeq) { ??????? sCurrentActivityThread = this; ??????? mConfigurationController = new ConfigurationController(this); ??????? mSystemThread = system; ??????? if (!system) { ? ? ? ? ? //应用进程 ??????????? android.ddm.DdmHandleAppName.setAppName("<pre-initialized>", ??????????????????????????????????????????????????? UserHandle.myUserId()); ??????????? RuntimeInit.setApplicationObject(mAppThread.asBinder()); ??????????? final IActivityManager mgr = ActivityManager.getService(); ??????????? try { ??????????????? mgr.attachApplication(mAppThread, startSeq); ? ? ? ? ? ?... ??????? } else { ? ? ? ? ??//系统进程 ??????????? android.ddm.DdmHandleAppName.setAppName("system_process", ??????????????????? UserHandle.myUserId()); ??????????? try { ??????????????? mInstrumentation = new Instrumentation(); ??????????????? mInstrumentation.basicInit(this); ??????????????? ContextImpl context = ContextImpl.createAppContext( ??????????????????????? this, getSystemContext().mPackageInfo); ??????????????? mInitialApplication = context.mPackageInfo.makeApplication(true, null); ??????????????? mInitialApplication.onCreate(); ? ? ? ? ? ?... ??????? } ? ? ? ? ... ??? } |
---|
判断是系统进程还是应用进程,如果是应用进程,调用AMS.attachApplication。
ActivityManagerService.java
??? @GuardedBy("this") ??? private boolean attachApplicationLocked(@NonNull IApplicationThread thread, ??????????? int pid, int callingUid, long startSeq) { ? ? ? ... ??????????????? thread.bindApplication(processName, appInfo, providerList, ??????????????????????? instr2.mClass, ??????????????????????? profilerInfo, instr2.mArguments, ??????????????????????? instr2.mWatcher, ??????????????????????? instr2.mUiAutomationConnection, testMode, ??????????????????????? mBinderTransactionTrackingEnabled, enableTrackAllocation, ??????????????????????? isRestrictedBackupMode || !normalMode, app.isPersistent(), ??????????????????????? new Configuration(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(), ??????????????????????? new Configuration(app.getWindowProcessController().getConfiguration()), ? ??????????????????????app.getCompat(), getCommonServicesLocked(app.isolated), ??????????????????????? mCoreSettingsObserver.getCoreSettingsLocked(), ??????????????????????? buildSerial, autofillOptions, contentCaptureOptions, ??????????????????????? app.getDisabledCompatChanges(), serializedSystemFontMap); ??????????? } ... ??????? // See if the top visible activity is waiting to run in this process... ??????? if (normalMode) { ??????????? try { ??????????????? didSomething = mAtmInternal.attachApplication(app.getWi ??? boolean attachApplication(WindowProcessController app) throws RemoteException { ??????? boolean didSomething = false; ??????? for (int displayNdx = getChildCount() - 1; displayNdx >= 0; --displayNdx) { ??????????? mTmpRemoteException = null; ??????????? mTmpBoolean = false; // Set to true if an activity was started. ??????????? final DisplayContent display = getChildAt(displayNdx); ??????????? display.forAllRootTasks(rootTask -> { ??????????????? if (mTmpRemoteException != null) { ??????????????????? return; ??????????????? } ??????????????? if (rootTask.getVisibility(null /*starting*/) == TASK_VISIBILITY_INVISIBLE) { ?? ?????????????????return; ??????????????? } ??????????????? final PooledFunction c = PooledLambda.obtainFunction( ??????????????????????? RootWindowContainer::startActivityForAttachedApplicationIfNeeded, this, ??????????????????????? PooledLambda.__(ActivityRecord.class), app, ??????????????????????? rootTask.topRunningActivity()); ??????????????? rootTask.forAllActivities(c); ??????????????? c.recycle(); ??????????? }); ??????????? if (mTmpRemoteException != null) { ??????????????? throw mTmpRemoteException; ??????????? } ??????????? didSomething |= mTmpBoolean; ??????? } ??????? if (!didSomething) { ??????????? ensureActivitiesVisible(null, 0, false /* preserve_windows */); ??????? } ??????? return didSomething; ??? } ndowProcessController()); ??????????? } catch (Exception e) { ??????????????? Slog.wtf(TAG, "Exception thrown launching activities in " + app, e); ??????????????? badApp = true; ?????? ?????} ??????? } ? ?} |
---|
之后会通过进程间调用调用到ATMS的attachApplication,进一步调用到RootWindowContainer的attachApplication。
ActivityTaskManagerService.java
??? boolean attachApplication(WindowProcessController app) throws RemoteException { ??????? boolean didSomething = false; ? ? ? ? ... ??????????????? final PooledFunction c = PooledLambda.obtainFunction( ??????????????????????? RootWindowContainer::startActivityForAttachedApplicationIfNeeded, this, ??????????????????????? PooledLambda.__(ActivityRecord.class), app, ??????????????????????? rootTask.topRunningActivity()); ??????????????? rootTask.forAllActivities(c); ? ? ? ? ? ? ... ??? } |
---|
??? private boolean startActivityForAttachedApplicationIfNeeded(ActivityRecord r, ??????????? WindowProcessController app, ActivityRecord top) { ??????? if (r.finishing || !r.okToShowLocked() || !r.visibleIgnoringKeyguard || r.app != null ??????????????? || app.mUid !=?r.info.applicationInfo.uid || !app.mName.equals(r.processName)) { ??????????? return false; ??????? } ??????? try { ??????????? if (mTaskSupervisor.realStartActivityLocked(r, app, ??????????????????? top == r && r.isFocusable() /*andResume*/, true /*checkConfig*/)) { ??????????????? mTmpBoolean = true; ??????????? } ??????? } catch (RemoteException e) { ??????????? Slog.w(TAG, "Exception in new application when starting activity " ??????????????????? + top.intent.getComponent().flattenToShortString(), e); ??????????? mTmpRemoteException = e; ??????????? return true; ??????? } ??????? return false; ??? } |
---|
再次调用到realStartActivityLocked,此时进程已启动,开始执行activity的状态转换。
整个流程为:
1.获取栈顶已激活的Activity,并进行暂停,暂停流程分为两步:
- 调用主线程的handlePauseActivity进行处理,之后再次通过Instrument调用到Activity的onPause函数。
- 暂停结束后,通过进程间通信,再次调用到Task的resumeTopActivityInnerLocked。
2.在resumeTopActivityInnerLocked中判断目标activity与当前进程是否有关联,若有关联,直接恢复目标activity,否则启动目标activity所在的进程。
3.判断目标进程是否已启动,如果目标进程启动,调用realStartActivityLocked进行状态转换,否则,通过Zogyte启动新进程。
4.新进程启动后,创建ActivityThread的实例,并进入main函数,通过进程间通信调用到ActivityManagerService的attachAppliaction函数,再进一步调用到attachAppliactionLocked进行进程间通信,通过ActivityThread的bindApplication绑定应用程序,之后再次通过进程间调用,通知ATMS调用到realStartActivityLocked进行状态转换。
流程图:
?
|