文章目录

  • 一、Activity 启动源码分析 ( AMS | ActivityManagerService )
    • 1、Instrumentation 调用 AMS 方法
    • 2、ActivityStarter 调用 AMS 方法
    • 3、Process 启动新进程
  • 二、Activity 启动源码分析 ( ActivityStarter )
    • 1、ActivityStarter.startActivityMayWait() 方法
    • 2、ActivityStarter.startActivity ( 24 参数 ) 方法
    • 3、ActivityStarter.startActivity ( 23 参数 ) 方法
    • 4、ActivityStarter.startActivity ( 9 参数 ) 方法
    • 5、ActivityStarter.startActivityUnchecked 方法
    • 6、ActivityStarter.computeLaunchingTaskFlags() 方法
  • 三、Activity 启动源码分析 ( ActivityRecord )
  • 五、ActivityStack
  • 六、ActivityStackSupervisor
  • 四、ActivityStack、TaskRecord、ActivityRecord

一、Activity 启动源码分析 ( AMS | ActivityManagerService )


1、Instrumentation 调用 AMS 方法

在 Instrumentation 中 , 通过调用 ActivityManagerService ( AMS ) 的 startActivity 方法 ,

         // 在此处调用 AMS , Binder 机制获取 AMSint result = ActivityManager.getService().startActivity(whoThread, who.getBasePackageName(), intent,intent.resolveTypeIfNeeded(who.getContentResolver()),token, target != null ? target.mEmbeddedID : null,requestCode, 0, null, options);

调用的是 AMS 的 startActivity 101010 个参数的方法 , 在该方法中又掉了 111111 个参数的 startActivityAsUser 方法 ; 在 startActivityAsUser 方法中 , 主要是确保要打开的 Activity 在 AndroidManifest.xml 清单文件中注册过 ;

在插件化中 , 要在执行该 AMS 方法之前 , 使用在清单文件中注册过的占坑 Activity 替换插件 Activity , 借此骗过 AMS ;

AMS 相关源码如下 :

public class ActivityManagerService extends IActivityManager.Stubimplements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {@Overridepublic final int startActivity(IApplicationThread caller, String callingPackage,Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,resultWho, requestCode, startFlags, profilerInfo, bOptions,UserHandle.getCallingUserId());}@Overridepublic final int startActivityAsUser(IApplicationThread caller, String callingPackage,Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {enforceNotIsolatedCaller("startActivity");userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),userId, false, ALLOW_FULL_ONLY, "startActivity", null);// TODO: Switch to user app stacks here.return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,profilerInfo, null, null, bOptions, false, userId, null, "startActivityAsUser");}
}

ActivityManagerService 完整源码参考 : frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

2、ActivityStarter 调用 AMS 方法

ActivityStarter.startActivityUnchecked 中调用了 mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity, mOptions); 方法 , 显示栈顶元素 ,

mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity, mOptions); 中, 调用了 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0, "activity", r.intent.getComponent(), false, false, true); 方法启动新进程 ;

最终在 private final void startProcessLocked(ProcessRecord app, String hostingType, String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) 方法中 , 调用了Process.start(entryPoint, app.processName, uid, uid, gids, debugFlags, mountExternal, app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet, app.info.dataDir, invokeWith, entryPointArgs) 方法 , 开启新的进程 ;

public class ActivityManagerService extends IActivityManager.Stubimplements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {private final void startProcessLocked(ProcessRecord app, String hostingType,String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) {if (hostingType.equals("webview_service")) {startResult = startWebView(entryPoint,app.processName, uid, uid, gids, debugFlags, mountExternal,app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,app.info.dataDir, null, entryPointArgs);} else {startResult = Process.start(entryPoint,app.processName, uid, uid, gids, debugFlags, mountExternal,app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,app.info.dataDir, invokeWith, entryPointArgs);}}
}

ActivityManagerService 完整源码参考 : frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

3、Process 启动新进程

AMS 的 void startProcessLocked(ProcessRecord app, String hostingType, String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) 方法中 , 调用了 startResult = Process.start(entryPoint, app.processName, uid, uid, gids, debugFlags, mountExternal, app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet, app.info.dataDir, invokeWith, entryPointArgs); 启动新进程 , 该方法原型如下 :

    /*** 开始一个新的过程。** <p>如果启用了流程,则会创建一个新流程,并且* 在那里执行<var>processClass</var>的静态main()函数。* 此函数返回后,进程将继续运行。** <p>如果未启用进程,则在调用方的* 进程被创建,并在那里调用<var>processClass</var>的main()。** <p>niceName参数(如果不是空字符串)是要使用的自定义名称* 指定给进程,而不是使用processClass。这允许您* 即使使用相同的基础,也要创建易于识别的流程* <var>processClass</var>启动它们。** 当invokeWith不为null时,该进程将作为新应用程序启动* 而不是合子叉。请注意,这仅适用于uid 0或以下情况* runtimeFlags包含调试\启用\调试器。** @param processClass 要用作进程主项的类* 指向* @param niceName 用于进程的可读性更强的名称。* @param uid 进程将在其下运行的用户id。* @param gid 进程将在其下运行的组id。* @param gids 与进程关联的其他组ID。* @param runtimeFlags 为运行时添加附加标志。* @param targetSdkVersion 应用程序的目标SDK版本。* @param seInfo null确定新进程的SELinux信息。* @param abi non null此应用程序启动时应使用的abi。* @param instructionSet null确定要使用的指令集。* @param appDataDir null ok应用程序的数据目录。* @param invokeWith null ok用于调用的命令。* @param zygoteArgs 为合子进程提供附加参数。** @返回一个对象,该对象描述尝试启动进程的结果。* @在致命启动失败时引发RuntimeException** {@hide}*/public static final ProcessStartResult start(final String processClass,final String niceName,int uid, int gid, int[] gids,int runtimeFlags, int mountExternal,int targetSdkVersion,String seInfo,String abi,String instructionSet,String appDataDir,String invokeWith,String[] zygoteArgs) {return zygoteProcess.start(processClass, niceName, uid, gid, gids,runtimeFlags, mountExternal, targetSdkVersion, seInfo,abi, instructionSet, appDataDir, invokeWith, zygoteArgs);}

完整源码参考 /frameworks/base/core/java/android/os/Process.java ;

二、Activity 启动源码分析 ( ActivityStarter )


1、ActivityStarter.startActivityMayWait() 方法

在 AMS 中调用了 mActivityStarter.startActivityMayWait 方法 , 在 ActivityStarter 中的 startActivityMayWait 中 , 调用了 242424 个参数的 startActivity 方法 ,

class ActivityStarter {private int startActivityMayWait(IApplicationThread caller, int callingUid,String callingPackage, Intent intent, String resolvedType,IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,IBinder resultTo, String resultWho, int requestCode, int startFlags,ProfilerInfo profilerInfo, WaitResult outResult,Configuration globalConfig, SafeActivityOptions options, boolean ignoreTargetSecurity,int userId, TaskRecord inTask, String reason,boolean allowPendingRemoteAnimationRegistryLookup) {// 获取对应 Activity 信息 , 并处理该信息//   从多个 Activity 中选择最合适的 Activity//     类似于打开一个文本文件 , 弹出窗口 , 选择什么应用打开ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId,0 /* matchFlags */,computeResolveFilterUid(callingUid, realCallingUid, mRequest.filterCallingUid));// 在 ActivityRecord 对象中 , 记录了 Activity 的相关活动final ActivityRecord[] outRecord = new ActivityRecord[1];// 启动 Activity// 调用的是 24 个参数的 startActivity 方法int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,allowPendingRemoteAnimationRegistryLookup);}
}

完整代码参考 frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java ;

2、ActivityStarter.startActivity ( 24 参数 ) 方法

242424 个参数的 startActivity 的重载方法中 , 又调用了 232323 个参数的 startActivity 重载方法 ;

class ActivityStarter {// 24 个参数的 startActivity 的重载方法private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,String callingPackage, int realCallingPid, int realCallingUid, int startFlags,SafeActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,ActivityRecord[] outActivity, TaskRecord inTask, String reason,boolean allowPendingRemoteAnimationRegistryLookup) {// 调用了 23 个参数的 startActivity 的重载方法mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,inTask, allowPendingRemoteAnimationRegistryLookup);}
}

完整代码参考 frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java ;

3、ActivityStarter.startActivity ( 23 参数 ) 方法

232323 个参数的 startActivity 的重载方法中 , 又调用了 999 个参数的 startActivity 重载方法 ,

class ActivityStarter {// 23 个参数的 startActivity 重载方法private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,String callingPackage, int realCallingPid, int realCallingUid, int startFlags,SafeActivityOptions options,boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity,TaskRecord inTask, boolean allowPendingRemoteAnimationRegistryLookup) {// 调用 9 个参数的 startActivity 的重载方法return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,true /* doResume */, checkedOptions, inTask, outActivity);}
}

完整代码参考 frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java ;

4、ActivityStarter.startActivity ( 9 参数 ) 方法

999 个参数的 startActivity 的重载方法中 , 调用了 startActivityUnchecked 方法 ;

class ActivityStarter {// 9 个参数的 startActivity 的重载方法private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,ActivityRecord[] outActivity) {try {mService.mWindowManager.deferSurfaceLayout();// 此处是主要的逻辑result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,startFlags, doResume, options, inTask, outActivity);}}
}

完整代码参考 frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java ;

5、ActivityStarter.startActivityUnchecked 方法

startActivityUnchecked 方法中 , 调用了 computeLaunchingTaskFlags 方法 ,

mTargetStack.startActivityLocked 是将启动的 Activity 插入到栈顶部 , 调用 ActivityStack 的 startActivityLocked 方法 ;

class ActivityStarter {// 注意:此方法只能从{@link startActivity}调用。private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,ActivityRecord[] outActivity) {// 启动 Activity 的 Launcher Mode 4 种启动模式 , 就是在该方法中处理computeLaunchingTaskFlags();computeSourceStack();// 此处将启动的 Activity 插入到栈顶部//   调用 ActivityStack 的 startActivityLocked 方法mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition,mOptions);// 显示栈顶元素mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,mOptions);}

完整代码查看 frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java ;

6、ActivityStarter.computeLaunchingTaskFlags() 方法

该方法处理 Activity 启动模式 , 假如启动 Activity 场景是 Activity A 启动 Activity B , mSourceRecord 是 Activity A 相关资料 , 是 ActivityRecord 类型对象 , 该对象中保存了 Activity 的所有信息 ;

mSourceRecord == null , 判断启动 Activity 的源是否是 Activity , 如果通过 Context 或 Application 启动 Activity , 则 mSourceRecord 就是空的 ;

mInTask != null 判断要加入的 TaskRecord 是否为空 ;

调用 isLaunchModeOneOf(LAUNCH_SINGLE_INSTANCE, LAUNCH_SINGLE_TASK) 方法用于判定该 Activity 的启动模式是否是 LAUNCH_SINGLE_INSTANCE 或 LAUNCH_SINGLE_TASK 中二者之一 ;

class ActivityStarter {// 处理 Activity 启动模式private void computeLaunchingTaskFlags() {// 如果调用方不是来自另一个 Activity,而是给了我们一个明确的任务,//     他们希望我们在其中启动新Activity,那么让我们看看如何执行该任务。// 假如启动 Activity 场景是 Activity A 启动 Activity B//   mSourceRecord 是 Activity A 相关资料 , 是 ActivityRecord 类型对象//    该对象中保存了 Activity 的所有信息if (mSourceRecord == null && mInTask != null && mInTask.getStack() != null) {final Intent baseIntent = mInTask.getBaseIntent();final ActivityRecord root = mInTask.getRootActivity();if (baseIntent == null) {ActivityOptions.abort(mOptions);throw new IllegalArgumentException("Launching into task without base intent: "+ mInTask);}// 如果此任务为空,那么我们将添加第一个活动——它确定根,并且必须作为新的_任务启动。if (isLaunchModeOneOf(LAUNCH_SINGLE_INSTANCE, LAUNCH_SINGLE_TASK)) {if (root != null) {ActivityOptions.abort(mOptions);throw new IllegalArgumentException("Caller with mInTask " + mInTask+ " has root " + root + " but target is singleInstance/Task");}}}
}

完整代码参考 frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java ;

三、Activity 启动源码分析 ( ActivityRecord )


ActivityRecord 中记录了所有的 Activity 信息 , 其中的 private TaskRecord task; // the task this is in. 成员 , 记录该 ActivityRecord 是存储在哪个 TaskRecord 中 ;

由于 Activity 可以启动多次 , 111 个 Activity 可能有多个 ActivityRecord 与之对应 , 每个 ActivityRecord 都与当前某个存在的 Activity 对应 ; 如果启动模式是 Standard , 那么每次启动该 Activity 都会创建一个新的 Activity , 放在任务栈栈顶 ;

final class ActivityRecord extends ConfigurationContainer implements AppWindowContainerListener {private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityRecord" : TAG_AM;private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;private static final String TAG_SAVED_STATE = TAG + POSTFIX_SAVED_STATE;private static final String TAG_STATES = TAG + POSTFIX_STATES;private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;// TODO(b/67864419): Remove once recents component is overriddenprivate static final String LEGACY_RECENTS_PACKAGE_NAME = "com.android.systemui.recents";private static final boolean SHOW_ACTIVITY_START_TIME = true;private static final String ATTR_ID = "id";private static final String TAG_INTENT = "intent";private static final String ATTR_USERID = "user_id";private static final String TAG_PERSISTABLEBUNDLE = "persistable_bundle";private static final String ATTR_LAUNCHEDFROMUID = "launched_from_uid";private static final String ATTR_LAUNCHEDFROMPACKAGE = "launched_from_package";private static final String ATTR_RESOLVEDTYPE = "resolved_type";private static final String ATTR_COMPONENTSPECIFIED = "component_specified";static final String ACTIVITY_ICON_SUFFIX = "_activity_icon_";final ActivityManagerService service; // ownerfinal IApplicationToken.Stub appToken; // window manager tokenAppWindowContainerController mWindowContainerController;final ActivityInfo info; // all about me// TODO: This is duplicated state already contained in info.applicationInfo - removeApplicationInfo appInfo; // information about activity's appfinal int launchedFromPid; // always the pid who started the activity.final int launchedFromUid; // always the uid who started the activity.final String launchedFromPackage; // always the package who started the activity.final int userId;          // Which user is this running for?final Intent intent;    // the original intent that generated usfinal ComponentName realActivity;  // the intent component, or target of an alias.final String shortComponentName; // the short component name of the intentfinal String resolvedType; // as per original caller;final String packageName; // the package implementing intent's componentfinal String processName; // process where this component wants to runfinal String taskAffinity; // as per ActivityInfo.taskAffinityfinal boolean stateNotNeeded; // As per ActivityInfo.flagsboolean fullscreen; // The activity is opaque and fills the entire space of this task.// TODO: See if it possible to combine this with the fullscreen field.final boolean hasWallpaper; // Has a wallpaper window as a background.final boolean noDisplay;  // activity is not displayed?private final boolean componentSpecified;  // did caller specify an explicit component?final boolean rootVoiceInteraction;  // was this the root activity of a voice interaction?private CharSequence nonLocalizedLabel;  // the label information from the package mgr.private int labelRes;           // the label information from the package mgr.private int icon;               // resource identifier of activity's icon.private int logo;               // resource identifier of activity's logo.private int theme;              // resource identifier of activity's theme.private int realTheme;          // actual theme resource we will use, never 0.private int windowFlags;        // custom window flags for preview window.private TaskRecord task;        // the task this is in.private long createTime = System.currentTimeMillis();long displayStartTime;  // when we started launching this activitylong fullyDrawnStartTime; // when we started launching this activityprivate long startTime;         // last time this activity was startedlong lastVisibleTime;   // last time this activity became visiblelong cpuTimeAtResume;   // the cpu time of host process at the time of resuming activitylong pauseTime;         // last time we started pausing the activitylong launchTickTime;    // base time for launch tick messages// Last configuration reported to the activity in the client process.private MergedConfiguration mLastReportedConfiguration;private int mLastReportedDisplayId;private boolean mLastReportedMultiWindowMode;private boolean mLastReportedPictureInPictureMode;CompatibilityInfo compat;// last used compatibility modeActivityRecord resultTo; // who started this entry, so will get our replyfinal String resultWho; // additional identifier for use by resultTo.final int requestCode;  // code given by requester (resultTo)ArrayList<ResultInfo> results; // pending ActivityResult objs we have receivedHashSet<WeakReference<PendingIntentRecord>> pendingResults; // all pending intents for this actArrayList<ReferrerIntent> newIntents; // any pending new intents for single-top modeActivityOptions pendingOptions; // most recently given optionsActivityOptions returningOptions; // options that are coming back via convertToTranslucentAppTimeTracker appTimeTracker; // set if we are tracking the time in this app/task/activityHashSet<ConnectionRecord> connections; // All ConnectionRecord we holdUriPermissionOwner uriPermissions; // current special URI access perms.ProcessRecord app;      // if non-null, hosting applicationprivate ActivityState mState;    // current state we are inBundle  icicle;         // last saved activity statePersistableBundle persistentState; // last persistently saved activity state// TODO: See if this is still needed.boolean frontOfTask;    // is this the root activity of its task?boolean launchFailed;   // set if a launched failed, to abort on 2nd tryboolean haveState;      // have we gotten the last activity state?boolean stopped;        // is activity pause finished?boolean delayedResume;  // not yet resumed because of stopped app switches?boolean finishing;      // activity in pending finish list?boolean deferRelaunchUntilPaused;   // relaunch of activity is being deferred until pause is// completedboolean preserveWindowOnDeferredRelaunch; // activity windows are preserved on deferred relaunchint configChangeFlags;  // which config values have changedprivate boolean keysPaused;     // has key dispatching been paused for it?int launchMode;         // the launch mode activity attribute.int lockTaskLaunchMode; // the lockTaskMode manifest attribute, subject to overrideboolean visible;        // does this activity's window need to be shown?boolean visibleIgnoringKeyguard; // is this activity visible, ignoring the fact that Keyguard// might hide this activity?private boolean mDeferHidingClient; // If true we told WM to defer reporting to the client// process that it is hidden.boolean sleeping;       // have we told the activity to sleep?boolean nowVisible;     // is this activity's window visible?boolean mClientVisibilityDeferred;// was the visibility change message to client deferred?boolean idle;           // has the activity gone idle?boolean hasBeenLaunched;// has this activity ever been launched?boolean frozenBeforeDestroy;// has been frozen but not yet destroyed.boolean immersive;      // immersive mode (don't interrupt if possible)boolean forceNewConfig; // force re-create with new config next timeboolean supportsEnterPipOnTaskSwitch;  // This flag is set by the system to indicate that the// activity can enter picture in picture while pausing (only when switching to another task)PictureInPictureParams pictureInPictureArgs = new PictureInPictureParams.Builder().build();// The PiP params used when deferring the entering of picture-in-picture.int launchCount;        // count of launches since last statelong lastLaunchTime;    // time of last launch of this activityComponentName requestedVrComponent; // the requested component for handling VR mode.String stringName;      // for caching of toString().private boolean inHistory;  // are we in the history stack?final ActivityStackSupervisor mStackSupervisor;static final int STARTING_WINDOW_NOT_SHOWN = 0;static final int STARTING_WINDOW_SHOWN = 1;static final int STARTING_WINDOW_REMOVED = 2;int mStartingWindowState = STARTING_WINDOW_NOT_SHOWN;boolean mTaskOverlay = false; // Task is always on-top of other activities in the task.TaskDescription taskDescription; // the recents information for this activityboolean mLaunchTaskBehind; // this activity is actively being launched with// ActivityOptions.setLaunchTaskBehind, will be cleared once launch is completed.// These configurations are collected from application's resources based on size-sensitive// qualifiers. For example, layout-w800dp will be added to mHorizontalSizeConfigurations as 800// and drawable-sw400dp will be added to both as 400.private int[] mVerticalSizeConfigurations;private int[] mHorizontalSizeConfigurations;private int[] mSmallestSizeConfigurations;boolean pendingVoiceInteractionStart;   // Waiting for activity-invoked voice sessionIVoiceInteractionSession voiceSession;  // Voice interaction session for this activity// A hint to override the window specified rotation animation, or -1// to use the window specified value. We use this so that// we can select the right animation in the cases of starting// windows, where the app hasn't had time to set a value// on the window.int mRotationAnimationHint = -1;private boolean mShowWhenLocked;private boolean mTurnScreenOn;/*** Temp configs used in {@link #ensureActivityConfiguration(int, boolean)}*/private final Configuration mTmpConfig = new Configuration();private final Rect mTmpBounds = new Rect();
}

完整代码参考 frameworks/base/services/core/java/com/android/server/am/ActivityRecord.java

五、ActivityStack


ActivityStarter.startActivityUnchecked 方法中 , 调用了 ActivityStack.startActivityLocked 方法 , 将启动的 Activity 插入了任务栈的顶部 ;

class ActivityStack<T extends StackWindowController> extends ConfigurationContainerimplements StackWindowListener {void startActivityLocked(ActivityRecord r, ActivityRecord focusedTopActivity,boolean newTask, boolean keepCurTransition, ActivityOptions options) {TaskRecord rTask = r.getTask();final int taskId = rTask.taskId;// mLaunchTaskBehind tasks get placed at the back of the task stack.if (!r.mLaunchTaskBehind && (taskForIdLocked(taskId) == null || newTask)) {// Last activity in task had been removed or ActivityManagerService is reusing task.// Insert or replace.// Might not even be in.insertTaskAtTop(rTask, r);}}
}

六、ActivityStackSupervisor


ActivityStarter.startActivityUnchecked 方法中 , 调用了 ActivityStackSupervisor.resumeFocusedStackTopActivityLocked 方法 , 作用是重新显示栈顶 Activity ;

public class ActivityStackSupervisor extends ConfigurationContainer implements DisplayListener,RecentTasks.Callbacks {boolean resumeFocusedStackTopActivityLocked(ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {if (!readyToResume()) {return false;}if (targetStack != null && isFocusedStack(targetStack)) {return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);}final ActivityRecord r = mFocusedStack.topRunningActivityLocked();if (r == null || !r.isState(RESUMED)) {mFocusedStack.resumeTopActivityUncheckedLocked(null, null);} else if (r.isState(RESUMED)) {// Kick off any lingering app transitions form the MoveTaskToFront operation.mFocusedStack.executeAppTransition(targetOptions);}return false;}

完整代码参考 /frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java ;

startSpecificActivityLocked 方法中 , 根据 ProcessRecord app 是否为空 , 确定要启动的 Activity 对应的进程是否存在 , 如果不存在需要创建进程 ;

public class ActivityStackSupervisor extends ConfigurationContainer implements DisplayListener,RecentTasks.Callbacks {void startSpecificActivityLocked(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);}realStartActivityLocked(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);}
}

完整代码参考 /frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java ;

四、ActivityStack、TaskRecord、ActivityRecord


每个 ActivityStack 中对应多个 TaskRecord ; TaskRecord 对应 " 活动任务栈 "

每个 TaskRecord 对应多个 ActivityRecord ;

对应关系如下图所示 :

在 ActivityStack 中的 private final ArrayList<TaskRecord> mTaskHistory = new ArrayList<>(); 成员存储的就是若干 TaskRecord ;

/*** 单个堆栈活动的状态和管理。*/
class ActivityStack<T extends StackWindowController> extends ConfigurationContainerimplements StackWindowListener {/*** 所有以前(可能仍在运行)活动的历史记录。它包含#TaskRecord对象。*/private final ArrayList<TaskRecord> mTaskHistory = new ArrayList<>();}

完整代码参考 /frameworks/base/services/core/java/com/android/server/am/ActivityStack.java ;

在 TaskRecord.java 源码中 , TaskRecord 类中有 final ArrayList<ActivityRecord> mActivities 成员变量 , 该成员就是存储多个 ActivityRecord ;

class TaskRecord extends ConfigurationContainer implements TaskWindowContainerListener {/** 按历史顺序排列的任务中所有活动的列表 */final ArrayList<ActivityRecord> mActivities;
}

完整代码参考 /frameworks/base/services/core/java/com/android/server/am/TaskRecord.java ;

【Android 启动过程】Activity 启动源码分析 ( AMS -> ActivityThread、AMS 线程阶段 )相关推荐

  1. Activity启动过程——10.0源码分析

    对于一个activity,注意不是根activity,它的启动流程往往是通过创建intent,通过startActivity()的方式启动的,我们跟踪的就是安卓10.0这部分的启动流程. 在windo ...

  2. Android shortcut的使用及源码分析

    Android shortcut的使用及源码分析 最近遇到了一个切换国家码后部分应用的shortcut未更新的问题,就学习了shortcut的相关知识,在这里分享一下我了解的知识,希望能对大家有帮助. ...

  3. Android Q 10.1 KeyMaster源码分析(二) - 各家方案的实现

    写在之前 这两篇文章是我2021年3月初看KeyMaster的笔记,本来打算等分析完KeyMaster和KeyStore以后再一起做成一系列贴出来,后来KeyStore的分析中断了,这一系列的文章就变 ...

  4. 【Android 事件分发】ItemTouchHelper 源码分析 ( OnItemTouchListener 事件监听器源码分析 二 )

    Android 事件分发 系列文章目录 [Android 事件分发]事件分发源码分析 ( 驱动层通过中断传递事件 | WindowManagerService 向 View 层传递事件 ) [Andr ...

  5. 【Android 事件分发】ItemTouchHelper 源码分析 ( OnItemTouchListener 事件监听器源码分析 )

    Android 事件分发 系列文章目录 [Android 事件分发]事件分发源码分析 ( 驱动层通过中断传递事件 | WindowManagerService 向 View 层传递事件 ) [Andr ...

  6. 【Android 插件化】VirtualApp 源码分析 ( 启动应用源码分析 | HomePresenterImpl 启动应用方法 | VirtualCore 启动插件应用最终方法 )

    文章目录 一.启动应用源码分析 1.HomeActivity 启动应用点击方法 2.HomePresenterImpl 启动应用方法 3.VirtualCore 启动插件应用最终方法 一.启动应用源码 ...

  7. 详述 Spring MVC 启动流程及相关源码分析

    文章目录 Web 应用部署初始化过程(Web Application Deployement) Spring MVC 启动过程 Listener 的初始化过程 Filter 的初始化 Servlet ...

  8. apollo源码启动服务,apollo源码分析

    文章目录 1.下载APOLLO源码 2.执行Sql脚本 3.启动项目 3.1 启动ConfigServiceApplication 3.2 启动apollo-assembly 3.3 启动 apoll ...

  9. Android服务函数远程调用源码分析

    在Android服务查询完整过程源码分析中介绍了客户进程向ServiceManager进程查询服务的完整过程,ServiceManager进程根据服务名称在自身维护的服务链表中查找ServiceMan ...

  10. 【Android 插件化】VirtualApp 源码分析 ( 添加应用源码分析 | LaunchpadAdapter 适配器 | 适配器添加元素 | PackageAppData 元素 )

    文章目录 一.添加应用源码分析 1.LaunchpadAdapter 适配器 2.适配器添加元素 3.PackageAppData 元素 一.添加应用源码分析 1.LaunchpadAdapter 适 ...

最新文章

  1. LeetCode实战:二叉树中的最大路径和
  2. 零件库管理信息系统设计--part03:管理员登录部分设计
  3. 专家:教育等领域将成为人工智能“用武之地”
  4. Python 中的匿名函数,你滥用了吗?
  5. python信号分析_Python频谱分析
  6. SQL中Case和convert()
  7. 【CF1009F】 Dominant Indices (长链剖分+DP)
  8. 网站程序 Bin目录下 dll无法删除,删除并编译后自动重新引用的解决方法
  9. 深度学习教程(11) | 经典CNN网络实例详解(吴恩达·完整版)
  10. Hello,Bada!
  11. .prevent 与 .stop,以及解决其他地方长按,文本被选中的问题
  12. matlab-微分方程求解方法汇总
  13. tomcat介绍:安装与优化
  14. 【2023 · CANN训练营第一季】晟腾AI入门课(TensorFlow)第一章 晟腾AI基础知识介绍
  15. 《桃花庵歌》——唐伯虎
  16. 简七32堂极简理财课——模块三:日常理财,让你时时刻刻都有钱
  17. XMLHttpRequest简介
  18. 利用opencv带你玩转人脸识别-上篇(读取图片,灰度转换,尺寸修改,绘制矩形快速入门)
  19. 不用mac环境,如何使用Visual Studio在Windows中开发iOS应用
  20. 调试ASP程序时,遇到程序运行错误时怎么查看具体错误位置呢?

热门文章

  1. 西南民大oj(矩阵快速幂)
  2. .net Redis使用公共方法引用CSRedisCore
  3. Dinic最大流 || Luogu P3376 【模板】网络最大流
  4. 简述模块-random
  5. 下拉框处理(select)
  6. MySQL服务器修改主机名后问题解决
  7. 将string转换成UTF8在进行请求
  8. 用gameMaker做个小游戏
  9. XHTML基础问答-给初学者
  10. regression