Understand the Activity startup process and efficient collaboration from startActivity to ATMS

Understand the Activity startup process and efficient collaboration from startActivity to ATMS

In the Android system, to start an Activity, whether you start the Activity from within an application or through a desktop program (Launcher), you need to initiate a start request by calling the startActivity method.

Initiation of a start request

  1. 「Start Activity inside the application」:

When a new Activity needs to be started within an application, the developer will call the startActivity method and pass an Intent object containing the target Activity information.

This Intent object can specify the class name of the Activity to be started, the data to be passed, the additional extras, etc.

After calling startActivity, the system will begin to process the start request and perform subsequent operations according to the Activity startup process.

  1. 「Launcher starts Activity」:
  • Launcher is a desktop program of the Android system. It is responsible for displaying installed application icons and providing an entry point for users to interact with applications.

  • When the user clicks an application icon from the Launcher, the Launcher creates a new Intent that starts the application's main Activity (usually the root Activity).

  • The Launcher then calls the startActivity method and passes the Intent to the system to start the target Activity.

In both cases, the launch request is initiated by calling the startActivity method. This method triggers a series of operations, including passing the launch request to ActivityTaskManagerService (ATMS), thread switching and message processing, and finally completing the initialization and display of the Activity. Whether it is startActivity or startActivityForResult, the end is to call startActivityForResult.

picture

 public class Activity extends ContextThemeWrapper implements LayoutInflater.Factory2, Window.Callback, KeyEvent.Callback, OnCreateContextMenuListener, ComponentCallbacks2, Window.OnWindowDismissedCallback, AutofillManager.AutofillClient, ContentCaptureManager.ContentCaptureClient { @Override public void startActivity(Intent intent, @Nullable Bundle options) { //... if (options != null) { startActivityForResult(intent, -1, options); } else { startActivityForResult(intent, -1); } } public void startActivityForResult(@RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) { // mParent 是Activity类型,是当前Activity的父类if (mParent == null) { options = transferSpringboardActivityOptions(options); // 调用Instrumentation.execStartActivity启动activity Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity( this, mMainThread.getApplicationThread(), mToken, this, intent, requestCode, options); //... } else { //... } } }

The Instrumentation.execStartActivity method is called in startActivityForResult. The mInstrumentation in Activity is initialized in the attach() method and passed in by ActivityThread. Its function is to start the activity through a remote service call, connect ActivityThread and activity, and handle activity life cycle callbacks.

 // Instrumentation主要用来监控应用程序和系统的交互,比如调用ATMS启动activity,回调生命周期public class Instrumentation { public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options) { //... try { //... // 通过ATMS远程调用startActivity int result = ActivityTaskManager.getService().startActivity(whoThread, who.getOpPackageName(), who.getAttributionTag(), intent, intent.resolveTypeIfNeeded(who.getContentResolver()), token, target != null ? target.mEmbeddedID : null, requestCode, 0, null, options); checkStartActivityResult(result, intent); } catch (RemoteException e) { throw new RuntimeException("Failure from system", e); } return null; } /** * 根据result判断当前能否启动activity,不能则抛出异常*/ public static void checkStartActivityResult(int res, Object intent) { if (!ActivityManager.isStartResultFatalError(res)) { return; } switch (res) { case ActivityManager.START_INTENT_NOT_RESOLVED: case ActivityManager.START_CLASS_NOT_FOUND: if (intent instanceof Intent && ((Intent)intent).getComponent() != null) // 没有在manifest中声明throw new ActivityNotFoundException( "Unable to find explicit activity class " + ((Intent)intent).getComponent().toShortString() + "; have you declared this activity in your AndroidManifest.xml?"); throw new ActivityNotFoundException( "No Activity found to handle " + intent); case ActivityManager.START_PERMISSION_DENIED: throw new SecurityException("Not allowed to start activity " + intent); case ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT: throw new AndroidRuntimeException( "FORWARD_RESULT_FLAG used while also requesting a result"); case ActivityManager.START_NOT_ACTIVITY: throw new IllegalArgumentException( "PendingIntent is not an activity"); case ActivityManager.START_NOT_VOICE_COMPATIBLE: throw new SecurityException( "Starting under voice control not allowed for: " + intent); case ActivityManager.START_VOICE_NOT_ACTIVE_SESSION: throw new IllegalStateException( "Session calling startVoiceActivity does not match active session"); case ActivityManager.START_VOICE_HIDDEN_SESSION: throw new IllegalStateException( "Cannot start voice activity on a hidden session"); case ActivityManager.START_ASSISTANT_NOT_ACTIVE_SESSION: throw new IllegalStateException( "Session calling startAssistantActivity does not match active session"); case ActivityManager.START_ASSISTANT_HIDDEN_SESSION: throw new IllegalStateException( "Cannot start assistant activity on a hidden session"); case ActivityManager.START_CANCELED: throw new AndroidRuntimeException("Activity could not be started for " + intent); default: throw new AndroidRuntimeException("Unknown error code " + res + " when starting " + intent); } } }
 @SystemService(Context.ACTIVITY_TASK_SERVICE) public class ActivityTaskManager { /** * IActivityTaskManager是一个Binder,用于和system_server进程中的ActivityTaskManagerService通信*/ public static IActivityTaskManager getService() { return IActivityTaskManagerSingleton.get(); } private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton = new Singleton<IActivityTaskManager>() { @Override protected IActivityTaskManager create() { final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE); return IActivityTaskManager.Stub.asInterface(b); } }; }

When a request reaches ATMS, ATMS will first check whether the request is legal, including checking the validity of the Intent, permissions, etc. Once the request is verified to be valid, ATMS will further process the request.

During the processing, ATMS will decide how to respond to the launch request based on the current system state and task stack. For example, it may decide to create a new Activity instance or bring an existing Activity instance to the foreground. ATMS also interacts with ActivityManagerService (AMS) to coordinate the lifecycle management of application components. AMS is responsible for tracking and managing the lifecycle of these components to ensure that they run as expected.

Activity initialization and life cycle management

When the Activity start request reaches ActivityTaskManagerService (ATMS) and is verified as valid, ATMS will notify the corresponding application process to initialize the Activity.

 // /frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java public class ActivityTaskManagerService extends IActivityTaskManager.Stub { public final int startActivity(IApplicationThread caller, String callingPackage, String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) { return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, UserHandle.getCallingUserId()); } private int startActivityAsUser(IApplicationThread caller, String callingPackage, @Nullable String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) { assertPackageMatchesCallingUid(callingPackage); // 判断调用者进程是否被隔离enforceNotIsolatedCaller("startActivityAsUser"); // 检查调用者权限userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser, Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser"); return getActivityStartController().obtainStarter(intent, "startActivityAsUser") .setCaller(caller) .setCallingPackage(callingPackage) .setCallingFeatureId(callingFeatureId) .setResolvedType(resolvedType) .setResultTo(resultTo) .setResultWho(resultWho) .setRequestCode(requestCode) .setStartFlags(startFlags) .setProfilerInfo(profilerInfo) .setActivityOptions(bOptions) .setUserId(userId) .execute(); } }

ATMS finally calls the startActivityAsUser method through a series of methods. It first checks the caller's permissions, then creates the ActivityStarter class through getActivityStartController().obtainStarter, sets the parameters to the ActivityStarter.Request class, and finally executes the ActivityStarter.execute() method.

 // /frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java class ActivityStarter { int execute() { try { //... int res; synchronized (mService.mGlobalLock) { //... res = executeRequest(mRequest); //... } } finally { onExecutionComplete(); } } private int executeRequest(Request request) { // 判断启动的理由不为空if (TextUtils.isEmpty(request.reason)) { throw new IllegalArgumentException("Need to specify a reason."); } // 获取调用的进程WindowProcessController callerApp = null; if (caller != null) { callerApp = mService.getProcessController(caller); if (callerApp != null) { // 获取调用进程的pid和uid并赋值callingPid = callerApp.getPid(); callingUid = callerApp.mInfo.uid; } else { err = ActivityManager.START_PERMISSION_DENIED; } } final int userId = aInfo != null && aInfo.applicationInfo != null ? UserHandle.getUserId(aInfo.applicationInfo.uid) : 0; ActivityRecord sourceRecord = null; ActivityRecord resultRecord = null; if (resultTo != null) { // 获取调用者所在的ActivityRecord sourceRecord = mRootWindowContainer.isInAnyStack(resultTo); if (sourceRecord != null) { if (requestCode >= 0 && !sourceRecord.finishing) { //requestCode = -1 则不进入resultRecord = sourceRecord; } } } final int launchFlags = intent.getFlags(); if ((launchFlags & Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0 && sourceRecord != null) { // activity执行结果的返回由源Activity转换到新Activity, 不需要返回结果则不会进入该分支} if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) { // 从Intent中无法找到相应的Component err = ActivityManager.START_INTENT_NOT_RESOLVED; } if (err == ActivityManager.START_SUCCESS && aInfo == null) { // 从Intent中无法找到相应的ActivityInfo err = ActivityManager.START_CLASS_NOT_FOUND; } //执行后resultStack = null final ActivityStack resultStack = resultRecord == null ? null : resultRecord.getRootTask(); //权限检查if (mService.mController != null) { try { Intent watchIntent = intent.cloneFilter(); abort |= !mService.mController.activityStarting(watchIntent, aInfo.applicationInfo.packageName); } catch (RemoteException e) { mService.mController = null; } } if (abort) { //权限检查不满足,才进入该分支则直接返回; return START_ABORTED; if (aInfo != null) { if (mService.getPackageManagerInternalLocked().isPermissionsReviewRequired( aInfo.packageName, userId)) { // 向PKMS获取启动Activity的ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId, 0, computeResolveFilterUid( callingUid, realCallingUid, request.filterCallingUid)); // 向PKMS获取启动Activity的ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, null /*profilerInfo*/); } } // 创建即将要启动的Activity的描述类ActivityRecord final ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid, callingPackage, callingFeatureId, intent, resolvedType, aInfo, mService.getGlobalConfiguration(), resultRecord, resultWho, requestCode, request.componentSpecified, voiceSession != null, mSupervisor, checkedOptions, sourceRecord); mLastStartActivityRecord = r; // 调用startActivityUnchecked mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession, request.voiceInteractor, startFlags, true /* doResume */, checkedOptions, inTask, restrictedBgActivity, intentGrants); if (request.outActivity != null) { request.outActivity[0] = mLastStartActivityRecord; } return mLastStartActivityResult; } }

Call the executeRequest method in ActivityStarter to perform a series of checks, including process check, intent check, permission check, and obtaining the ActivityInfo information of the started Activity from PKMS. Then, call the startActivityUnchecked method to start task stack management for the activity to be started.

 private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags, boolean doResume, ActivityOptions options, Task inTask, boolean restrictedBgActivity, NeededUriGrants intentGrants) { try { result = startActivityInner(r, sourceRecord, voiceSession, voiceInteractor, startFlags, doResume, options, inTask, restrictedBgActivity, intentGrants); } finally { //... } //... return result; } ActivityRecord mStartActivity; private ActivityStack mSourceStack; private ActivityStack mTargetStack; private Task mTargetTask; // 主要处理栈管理相关的逻辑int startActivityInner(final ActivityRecord r, ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags, boolean doResume, ActivityOptions options, Task inTask, boolean restrictedBgActivity, NeededUriGrants intentGrants) { // 初始化启动Activity的各种配置,在初始化前会重置各种配置再进行配置, // 这些配置包括:ActivityRecord、Intent、Task和LaunchFlags(启动的FLAG)等等setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession, voiceInteractor, restrictedBgActivity); // 给不同的启动模式计算出mLaunchFlags computeLaunchingTaskFlags(); // 主要作用是设置ActivityStack computeSourceStack(); // 将mLaunchFlags设置给Intent mIntent.setFlags(mLaunchFlags); // 确定是否应将新活动插入现有任务。如果不是,则返回null, // 或者返回带有应将新活动添加到其中的任务的ActivityRecord。 final Task reusedTask = getReusableTask(); // 如果reusedTask为null,则计算是否存在可以使用的任务栈final Task targetTask = reusedTask != null ? reusedTask : computeTargetTask(); final boolean newTask = targetTask == null; // 启动Activity是否需要新创建栈mTargetTask = targetTask; computeLaunchParams(r, sourceRecord, targetTask); // 检查是否允许在给定任务或新任务上启动活动。 int startResult = isAllowedToStart(r, newTask, targetTask); if (startResult != START_SUCCESS) { return startResult; } final ActivityStack topStack = mRootWindowContainer.getTopDisplayFocusedStack(); if (topStack != null) { // 检查正在启动的活动是否与当前位于顶部的活动相同,并且应该只启动一次startResult = deliverToCurrentTopIfNeeded(topStack, intentGrants); if (startResult != START_SUCCESS) { return startResult; } } if (mTargetStack == null) { // 复用或者创建堆栈mTargetStack = getLaunchStack(mStartActivity, mLaunchFlags, targetTask, mOptions); } if (newTask) { // 新建一个task final Task taskToAffiliate = (mLaunchTaskBehind && mSourceRecord != null) ? mSourceRecord.getTask() : null; setNewTask(taskToAffiliate); if (mService.getLockTaskController().isLockTaskModeViolation( mStartActivity.getTask())) { Slog.e(TAG, "Attempted Lock Task Mode violation mStartActivity=" + mStartActivity); return START_RETURN_LOCK_TASK_MODE_VIOLATION; } } else if (mAddingToTask) { // 复用之前的task addOrReparentStartingActivity(targetTask, "adding to task"); } // 检查是否需要触发过渡动画和开始窗口mTargetStack.startActivityLocked(mStartActivity, topStack != null ? topStack.getTopNonFinishingActivity() : null, newTask, mKeepCurTransition, mOptions); if (mDoResume) { // 调用RootWindowContainer的resumeFocusedStacksTopActivities方法mRootWindowContainer.resumeFocusedStacksTopActivities( mTargetStack, mStartActivity, mOptions); } return START_SUCCESS; } private void setInitialState(ActivityRecord r, ActivityOptions options, Task inTask, boolean doResume, int startFlags, ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, boolean restrictedBgActivity) { reset(false /* clearRequest */); mStartActivity = r; mIntent = r.intent; mSourceRecord = sourceRecord; mLaunchMode = r.launchMode; // 启动Flags mLaunchFlags = adjustLaunchFlagsToDocumentMode( r, LAUNCH_SINGLE_INSTANCE == mLaunchMode, LAUNCH_SINGLE_TASK == mLaunchMode, mIntent.getFlags()); mInTask = inTask; // ... } private void computeLaunchingTaskFlags() { if (mInTask == null) { if (mSourceRecord == null) { if ((mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) == 0 && mInTask == null) { mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK; } } else if (mSourceRecord.launchMode == LAUNCH_SINGLE_INSTANCE) { mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK; } else if (isLaunchModeOneOf(LAUNCH_SINGLE_INSTANCE, LAUNCH_SINGLE_TASK)) { mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK; } } } // 设置ActivityStack private void computeSourceStack() { if (mSourceRecord == null) { mSourceStack = null; return; } if (!mSourceRecord.finishing) { mSourceStack = mSourceRecord.getRootTask(); return; } if ((mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) == 0) { mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK; mNewTaskInfo = mSourceRecord.info; final Task sourceTask = mSourceRecord.getTask(); mNewTaskIntent = sourceTask != null ? sourceTask.intent : null; } mSourceRecord = null; mSourceStack = null; } private Task getReusableTask() { // If a target task is specified, try to reuse that one if (mOptions != null && mOptions.getLaunchTaskId() != INVALID_TASK_ID) { Task launchTask = mRootWindowContainer.anyTaskForId(mOptions.getLaunchTaskId()); if (launchTask != null) { return launchTask; } return null; } //标志位,如果为true,说明要放入已经存在的栈, // 可以看出,如果是设置了FLAG_ACTIVITY_NEW_TASK 而没有设置FLAG_ACTIVITY_MULTIPLE_TASK, // 或者设置了singleTask以及singleInstance boolean putIntoExistingTask = ((mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0 && (mLaunchFlags & FLAG_ACTIVITY_MULTIPLE_TASK) == 0) || isLaunchModeOneOf(LAUNCH_SINGLE_INSTANCE, LAUNCH_SINGLE_TASK); // 重新检验putIntoExistingTask &= mInTask == null && mStartActivity.resultTo == null; ActivityRecord intentActivity = null; if (putIntoExistingTask) { if (LAUNCH_SINGLE_INSTANCE == mLaunchMode) { //如果是singleInstance,那么就找看看之前存在的该实例,找不到就为null intentActivity = mRootWindowContainer.findActivity(mIntent, mStartActivity.info, mStartActivity.isActivityTypeHome()); } else if ((mLaunchFlags & FLAG_ACTIVITY_LAUNCH_ADJACENT) != 0) { // For the launch adjacent case we only want to put the activity in an existing // task if the activity already exists in the history. intentActivity = mRootWindowContainer.findActivity(mIntent, mStartActivity.info, !(LAUNCH_SINGLE_TASK == mLaunchMode)); } else { // Otherwise find the best task to put the activity in. intentActivity = mRootWindowContainer.findTask(mStartActivity, mPreferredTaskDisplayArea); } } if (intentActivity != null && (mStartActivity.isActivityTypeHome() || intentActivity.isActivityTypeHome()) && intentActivity.getDisplayArea() != mPreferredTaskDisplayArea) { // Do not reuse home activity on other display areas. intentActivity = null; } return intentActivity != null ? intentActivity.getTask() : null; } // 计算启动的Activity的栈private Task computeTargetTask() { if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask && (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) { // 返回null,应该新创建一个Task,而不是使用现有的Task return null; } else if (mSourceRecord != null) { // 使用源Activity的task return mSourceRecord.getTask(); } else if (mInTask != null) { // 使用启动时传递的task return mInTask; } else { // 理论上的可能,不可能走到这里final ActivityStack stack = getLaunchStack(mStartActivity, mLaunchFlags, null /* task */, mOptions); final ActivityRecord top = stack.getTopNonFinishingActivity(); if (top != null) { return top.getTask(); } else { // Remove the stack if no activity in the stack. stack.removeIfPossible(); } } return null; }

In the startActivityInner method, the ActivityRecord of the activity to be started is determined based on the startup mode and flag conditions to add it to the existing Task stack or create a new Task stack. After preparing the Task stack for the Activity, call the RootWindowContainer.resumeFocusedStacksTopActivities method.

 class RootWindowContainer extends WindowContainer<DisplayContent> implements DisplayManager.DisplayListener { boolean resumeFocusedStacksTopActivities( ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) { //... boolean result = false; if (targetStack != null && (targetStack.isTopStackInDisplayArea() || getTopDisplayFocusedStack() == targetStack)) { // 调用ActivityStack.resumeTopActivityUncheckedLocked result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions); } //... return result; } } class ActivityStack extends Task { boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) { if (mInResumeTopActivity) { // Don't even start recurscheduleTransactionsing. return false; } boolean result = false; try { mInResumeTopActivity = true; // 继续调用resumeTopActivityInnerLocked result = resumeTopActivityInnerLocked(prev, options); final ActivityRecord next = topRunningActivity(true /* focusableOnly */); if (next == null || !next.canTurnScreenOn()) { checkReadyForSleep(); } } finally { mInResumeTopActivity = false; } return result; } private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) { // Find the next top-most activity to resume in this stack that is not finishing and is // focusable. If it is not focusable, we will fall into the case below to resume the // top activity in the next focusable task. // 在当前Task栈中找到最上层正在运行的activity,如果这个activity没有获取焦点,那这个activity将会被重新启动ActivityRecord next = topRunningActivity(true /* focusableOnly */); final boolean hasRunningActivity = next != null; if (next.attachedToProcess()) { ... } else { ... // 调用StackSupervisor.startSpecificActivity mStackSupervisor.startSpecificActivity(next, true, true); } return true; } }

ActivityStack is used to manage a single activity stack and is ultimately called to ActivityStackSupervisor.startSpecificActivity().

 public class ActivityStackSupervisor implements RecentTasks.Callbacks { // 检查启动Activity所在进程是否有启动,没有则先启动进程void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) { // 根据processName和Uid查找启动Activity的所在进程final WindowProcessController wpc = mService.getProcessController(r.processName, r.info.applicationInfo.uid); boolean knownToBeDead = false; if (wpc != null && wpc.hasThread()) { // 进程已经存在,则直接启动Activity try { // 启动Activity ,并返回realStartActivityLocked(r, wpc, andResume, checkConfig); return; } catch (RemoteException e) { ... } knownToBeDead = true; } // 所在进程没创建则调用ATMS.startProcessAsync创建进程并启动Activity mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity"); } // 启动Activity的进程存在,则执行此方法boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc, boolean andResume, boolean checkConfig) throws RemoteException { ... // 创建活动启动事务// proc.getThread()是一个IApplicationThread对象,可以通过ClientTransaction.getClient()获取final ClientTransaction clientTransaction = ClientTransaction.obtain( proc.getThread(), r.appToken); // 为事务设置Callback,为LaunchActivityItem,在客户端时会被调用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, dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(), r.assistToken, r.createFixedRotationAdjustmentsIfNeeded())); // 设置所需的最终状态final ActivityLifecycleItem lifecycleItem; if (andResume) { lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward()); } else { lifecycleItem = PauseActivityItem.obtain(); } clientTransaction.setLifecycleStateRequest(lifecycleItem); // 执行事件,调用ClientLifecycleManager.scheduleTransaction mService.getLifecycleManager().scheduleTransaction(clientTransaction); ... return true; } }

In ActivityStackSupervisor, first check whether the process to start the activity exists. If it does, call the realStartActivityLocked method and call back the ApplicationThread.scheduleTransaction method through the ClientTransaction transaction. If the process does not exist, create the process.

Activity Display

 // 主要是处理AMS端的请求private class ApplicationThread extends IApplicationThread.Stub { @Override public void scheduleTransaction(ClientTransaction transaction) throws RemoteException { ActivityThread.this.scheduleTransaction(transaction); } } // ActivityThread的父类public abstract class ClientTransactionHandler { void scheduleTransaction(ClientTransaction transaction) { transaction.preExecute(this); // 发送EXECUTE_TRANSACTION消息sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction); } } // 它管理应用程序进程中主线程的执行,根据活动管理器的请求,在其上调度和执行活动、广播和其他操作。 public final class ActivityThread extends ClientTransactionHandler { class H extends Handler { public void handleMessage(Message msg) { switch (msg.what) { case EXECUTE_TRANSACTION: final ClientTransaction transaction = (ClientTransaction) msg.obj; // 调用TransactionExecutor.execute去处理ATMS阶段传过来的ClientTransaction 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(); } break; } } } } public class TransactionExecutor { public void execute(ClientTransaction transaction) { //... // 调用传过来的ClientTransaction事务的Callback executeCallbacks(transaction); executeLifecycleState(transaction); } public void executeCallbacks(ClientTransaction transaction) { final List<ClientTransactionItem> callbacks = transaction.getCallbacks(); ... final int size = callbacks.size(); for (int i = 0; i < size; ++i) { final ClientTransactionItem item = callbacks.get(i); ... // 调用LaunchActivityItem.execute item.execute(mTransactionHandler, token, mPendingActions); item.postExecute(mTransactionHandler, token, mPendingActions); ... } } } public class LaunchActivityItem extends ClientTransactionItem { public void execute(ClientTransactionHandler client, IBinder token, PendingTransactionActions pendingActions) { ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo, mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState, mPendingResults, mPendingNewIntents, mIsForward, mProfilerInfo, client, mAssistToken, mFixedRotationAdjustments); // 调用ActivityThread.handleLaunchActivity client.handleLaunchActivity(r, pendingActions, null /* customIntent */); } }

ApplicationThread finally calls the execute method of CallBack of ClientTransaction set in the ATMS stage, that is, LaunchActivityItem.execute method, at which time it creates an ActivityClientRecord object, and then starts the real Activity startup through ActivityThread.handleLaunchActivity.

 public final class ActivityThread extends ClientTransactionHandler { // ActivityThread启动Activity的过程@Override public Activity handleLaunchActivity(ActivityClientRecord r, PendingTransactionActions pendingActions, Intent customIntent) { // ... WindowManagerGlobal.initialize(); // 启动Activity final Activity a = performLaunchActivity(r, customIntent); if (a != null) { ... } else { // 启动失败,调用ATMS停止Activity启动try { ActivityTaskManager.getService() .finishActivity(r.token, Activity.RESULT_CANCELED, null, Activity.DONT_FINISH_TASK_WITH_ACTIVITY); } catch (RemoteException ex) { throw ex.rethrowFromSystemServer(); } } return a; } private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) { // 获取ActivityInfo类ActivityInfo aInfo = r.activityInfo; if (r.packageInfo == null) { // 获取APK文件的描述类LoadedApk r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo, Context.CONTEXT_INCLUDE_CODE); } // 启动的Activity的ComponentName类ComponentName component = r.intent.getComponent(); // 创建要启动Activity的上下文环境ContextImpl appContext = createBaseContextForActivity(r); Activity activity = null; try { java.lang.ClassLoader cl = appContext.getClassLoader(); // 用类加载器来创建该Activity的实例activity = mInstrumentation.newActivity( cl, component.getClassName(), r.intent); // ... } catch (Exception e) { // ... } try { // 创建Application Application app = r.packageInfo.makeApplication(false, mInstrumentation); if (activity != null) { // 初始化Activity activity.attach(appContext, this, getInstrumentation(), r.token, r.ident, app, r.intent, r.activityInfo, title, r.parent, r.embeddedID, r.lastNonConfigurationInstances, config, r.referrer, r.voiceInteractor, window, r.configCallback, r.assistToken); ... // 调用Instrumentation的callActivityOnCreate方法来启动Activity if (r.isPersistable()) { mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState); } else { mInstrumentation.callActivityOnCreate(activity, r.state); } ... } ... } catch (SuperNotCalledException e) { throw e; } catch (Exception e) { ... } return activity; } public class Instrumentation { public void callActivityOnCreate(Activity activity, Bundle icicle) { prePerformCreate(activity); // 调用Activity的performCreate activity.performCreate(icicle); postPerformCreate(activity); } } public class Activity extends ContextThemeWrapper implements LayoutInflater.Factory2, Window.Callback, KeyEvent.Callback, OnCreateContextMenuListener, ComponentCallbacks2, Window.OnWindowDismissedCallback, AutofillManager.AutofillClient, ContentCaptureManager.ContentCaptureClient { final void performCreate(Bundle icicle) { performCreate(icicle, null); } @UnsupportedAppUsage final void performCreate(Bundle icicle, PersistableBundle persistentState) { ... // 调用onCreate方法if (persistentState != null) { onCreate(icicle, persistentState); } else { onCreate(icicle); } ... } }

When initialization is complete, the Activity interface will be drawn and displayed on the screen. At this point, the user can interact with the Activity.

Summarize

  1. 「Start Request Initiation」:

Whether you start the Activity from within the application or through the desktop program (Launcher), you need to initiate a start request by calling the startActivity method.

This request contains information about the Activity to be started, usually passed through an Intent object.

  1. "Request arrives at ActivityTaskManagerService (ATMS)":
  • When a launch request is initiated, it first reaches ActivityTaskManagerService (ATMS).

  • ATMS is a system service responsible for managing the Activity lifecycle and task stack.

  1. 「Thread switching and message processing」:

  • When ATMS processes a startup request, thread switching and message processing may be involved.

  • For example, switching requests from application threads to system service threads, or processing requests through message queues.

  1. 「Activity initialization and life cycle management」:

  • Once ATMS decides which Activity to start, it notifies the corresponding application process to initialize the Activity.

  • This includes creating an instance of the Activity, loading the layout, initializing components, etc.

  • At the same time, the Activity's life cycle methods (such as onCreate, onStart, onResume, etc.) will also be called to ensure the correct initialization and state management of the Activity.

  1. Activity display:

  • When initialization is completed, the Activity interface will be drawn and displayed on the screen.

  • At this point, the user can interact with the Activity.

In different versions of Android, the startup process may be different and may involve more details and components. In addition, if a root Activity is started (for example, from the Launcher), the process may also include steps such as the creation of the application process. The Activity startup process is a complex process involving multiple components and services. It ensures that Android applications can correctly create, initialize, and display Activities, thereby providing users with a smooth and consistent experience.

<<:  How to load local video cover in Android

>>:  PMS APP installation process analysis

Recommend

10 Trend Predictions for Internet Celebrities/Live Streaming in 2020

2019 was the year when major internet celebrities...

"Super Moon" appears tonight!

Your browser does not support the video tag Xinhu...

My Primary Growth Map

The Internet has developed to this stage, and the...

There are many types of Internet operation jobs. How should I choose?

There are indeed many subdivisions of operations ...

Tesla may be suppressed if Trump is elected as US president

Republican candidate Trump was elected as the new...

Lost in Russia, the first marketing hit in 2020

When users across the country were staying at hom...

How to plan an efficient marketing operation plan?

Based on my own experience, I shared how the mobi...

Google engineers teach: Top 10 things new developers must invest in

[[120406]] As a software developer, what are the ...