当前位置:   article > 正文

安卓startActivity:彻底理解startActivity的启动过程这一篇就够了_android startactivity

android startactivity

基于Android 6.0的源码剖析, 分析android Activity启动流程,相关源码:

  1. frameworks/base/services/core/java/com/android/server/am/
  2. - ActivityManagerService.java
  3. - ActivityStackSupervisor.java
  4. - ActivityStack.java
  5. - ActivityRecord.java
  6. - ProcessRecord.java
  7. frameworks/base/core/java/android/app/
  8. - IActivityManager.java
  9. - ActivityManagerNative.java (内含AMP)
  10. - ActivityManager.java
  11. - IApplicationThread.java
  12. - ApplicationThreadNative.java (内含ATP)
  13. - ActivityThread.java (内含ApplicationThread)
  14. - ContextImpl.java

一. 概述

startActivity的整体流程与startService启动过程分析非常相近,但比Service启动更为复杂,多了stack/task以及UI的相关内容以及Activity的生命周期更为丰富。

Activity启动发起后,通过Binder最终交由system进程中的AMS来完成,则启动流程如下图:

 

接下来,从源码来说说每个过程。

二. 启动流程

2.1 Activity.startActivity

[-> Activity.java]

  1. public void startActivity(Intent intent) {
  2. this.startActivity(intent, null);
  3. }
  4. public void startActivity(Intent intent, @Nullable Bundle options) {
  5. if (options != null) {
  6. startActivityForResult(intent, -1, options);
  7. } else {
  8. //[见小节2.2]
  9. startActivityForResult(intent, -1);
  10. }
  11. }

2.2 startActivityForResult

[-> Activity.java]

  1. public void startActivityForResult(Intent intent, int requestCode) {
  2. startActivityForResult(intent, requestCode, null);
  3. }
  4. public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
  5. if (mParent == null) {
  6. //[见小节2.3]
  7. Instrumentation.ActivityResult ar =
  8. mInstrumentation.execStartActivity(
  9. this, mMainThread.getApplicationThread(), mToken, this,
  10. intent, requestCode, options);
  11. if (ar != null) {
  12. mMainThread.sendActivityResult(
  13. mToken, mEmbeddedID, requestCode, ar.getResultCode(),
  14. ar.getResultData());
  15. }
  16. //此时requestCode =-1
  17. if (requestCode >= 0) {
  18. mStartedActivity = true;
  19. }
  20. cancelInputsAndStartExitTransition(options);
  21. } else {
  22. ...
  23. }
  24. }

execStartActivity()方法的参数:

  • mAppThread: 数据类型为ApplicationThread,通过mMainThread.getApplicationThread()方法获取。
  • mToken: 数据类型为IBinder.

2.3 execStartActivity

[-> Instrumentation.java]

  1. public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options) {
  2. IApplicationThread whoThread = (IApplicationThread) contextThread;
  3. ...
  4. if (mActivityMonitors != null) {
  5. synchronized (mSync) {
  6. final int N = mActivityMonitors.size();
  7. for (int i=0; i<N; i++) {
  8. final ActivityMonitor am = mActivityMonitors.get(i);
  9. if (am.match(who, null, intent)) {
  10. am.mHits++;
  11. //当该monitor阻塞activity启动,则直接返回
  12. if (am.isBlocking()) {
  13. return requestCode >= 0 ? am.getResult() : null;
  14. }
  15. break;
  16. }
  17. }
  18. }
  19. }
  20. try {
  21. intent.migrateExtraStreamToClipData();
  22. intent.prepareToLeaveProcess();
  23. //[见小节2.4]
  24. int result = ActivityManagerNative.getDefault()
  25. .startActivity(whoThread, who.getBasePackageName(), intent,
  26. intent.resolveTypeIfNeeded(who.getContentResolver()),
  27. token, target != null ? target.mEmbeddedID : null,
  28. requestCode, 0, null, options);
  29. //检查activity是否启动成功
  30. checkStartActivityResult(result, intent);
  31. } catch (RemoteException e) {
  32. throw new RuntimeException("Failure from system", e);
  33. }
  34. return null;
  35. }

关于 ActivityManagerNative.getDefault()返回的是ActivityManagerProxy对象. 此处startActivity()的共有10个参数, 下面说说每个参数传递AMP.startActivity()每一项的对应值:

  • caller: 当前应用的ApplicationThread对象mAppThread;
  • callingPackage: 调用当前ContextImpl.getBasePackageName(),获取当前Activity所在包名;
  • intent: 这便是启动Activity时,传递过来的参数;
  • resolvedType: 调用intent.resolveTypeIfNeeded而获取;
  • resultTo: 来自于当前Activity.mToken
  • resultWho: 来自于当前Activity.mEmbeddedID
  • requestCode = -1;
  • startFlags = 0;
  • profilerInfo = null;
  • options = null;

2.4 AMP.startActivity

[-> ActivityManagerNative.java :: ActivityManagerProxy]

  1. class ActivityManagerProxy implements IActivityManager {
  2. ...
  3. public int startActivity(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle options) throws RemoteException {
  4. Parcel data = Parcel.obtain();
  5. Parcel reply = Parcel.obtain();
  6. data.writeInterfaceToken(IActivityManager.descriptor);
  7. data.writeStrongBinder(caller != null ? caller.asBinder() : null);
  8. data.writeString(callingPackage);
  9. intent.writeToParcel(data, 0);
  10. data.writeString(resolvedType);
  11. data.writeStrongBinder(resultTo);
  12. data.writeString(resultWho);
  13. data.writeInt(requestCode);
  14. data.writeInt(startFlags);
  15. if (profilerInfo != null) {
  16. data.writeInt(1);
  17. profilerInfo.writeToParcel(data, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
  18. } else {
  19. data.writeInt(0);
  20. }
  21. if (options != null) {
  22. data.writeInt(1);
  23. options.writeToParcel(data, 0);
  24. } else {
  25. data.writeInt(0);
  26. }
  27. //[见流程2.5]
  28. mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);
  29. reply.readException();
  30. int result = reply.readInt();
  31. reply.recycle();
  32. data.recycle();
  33. return result;
  34. }
  35. ...
  36. }

AMP经过binder IPC,进入ActivityManagerNative(简称AMN)。接下来程序进入了system_servr进程,开始继续执行。

2.5 AMN.onTransact

[-> ActivityManagerNative.java]

  1. public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
  2. switch (code) {
  3. case START_ACTIVITY_TRANSACTION:
  4. {
  5. data.enforceInterface(IActivityManager.descriptor);
  6. IBinder b = data.readStrongBinder();
  7. IApplicationThread app = ApplicationThreadNative.asInterface(b);
  8. String callingPackage = data.readString();
  9. Intent intent = Intent.CREATOR.createFromParcel(data);
  10. String resolvedType = data.readString();
  11. IBinder resultTo = data.readStrongBinder();
  12. String resultWho = data.readString();
  13. int requestCode = data.readInt();
  14. int startFlags = data.readInt();
  15. ProfilerInfo profilerInfo = data.readInt() != 0
  16. ? ProfilerInfo.CREATOR.createFromParcel(data) : null;
  17. Bundle options = data.readInt() != 0
  18. ? Bundle.CREATOR.createFromParcel(data) : null;
  19. //[见流程2.6]
  20. int result = startActivity(app, callingPackage, intent, resolvedType,
  21. resultTo, resultWho, requestCode, startFlags, profilerInfo, options);
  22. reply.writeNoException();
  23. reply.writeInt(result);
  24. return true;
  25. }
  26. ...
  27. } }

2.6 AMS.startActivity

[-> ActivityManagerService.java]

  1. public final int startActivity(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle options) {
  2. return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
  3. resultWho, requestCode, startFlags, profilerInfo, options,
  4. UserHandle.getCallingUserId());
  5. }
  6. public final int startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId) {
  7. enforceNotIsolatedCaller("startActivity");
  8. userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
  9. false, ALLOW_FULL_ONLY, "startActivity", null);
  10. //[见小节2.7]
  11. return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
  12. resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
  13. profilerInfo, null, null, options, false, userId, null, null);
  14. }

此处mStackSupervisor的数据类型为ActivityStackSupervisor

2.7 ASS.startActivityMayWait

当程序运行到这里时, ASS.startActivityMayWait的各个参数取值如下:

  • caller = ApplicationThreadProxy, 用于跟调用者进程ApplicationThread进行通信的binder代理类.
  • callingUid = -1;
  • callingPackage = ContextImpl.getBasePackageName(),获取调用者Activity所在包名
  • intent: 这是启动Activity时传递过来的参数;
  • resolvedType = intent.resolveTypeIfNeeded
  • voiceSession = null;
  • voiceInteractor = null;
  • resultTo = Activity.mToken, 其中Activity是指调用者所在Activity, mToken对象保存自己所处的ActivityRecord信息
  • resultWho = Activity.mEmbeddedID, 其中Activity是指调用者所在Activity
  • requestCode = -1;
  • startFlags = 0;
  • profilerInfo = null;
  • outResult = null;
  • config = null;
  • options = null;
  • ignoreTargetSecurity = false;
  • userId = AMS.handleIncomingUser, 当调用者userId跟当前处于同一个userId,则直接返回该userId;当不相等时则根据调用者userId来决定是否需要将callingUserId转换为mCurrentUserId.
  • iContainer = null;
  • inTask = null;

再来看看这个方法的源码:

[-> ActivityStackSupervisor.java]

  1. final int startActivityMayWait(IApplicationThread caller, int callingUid, String
  2. callingPackage, Intent intent, String resolvedType, IVoiceInteractionSession
  3. voiceSession, IVoiceInteractor voiceInteractor, IBinder resultTo, String
  4. resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, WaitResult
  5. outResult, Configuration config, Bundle optionsboolean ignoreTargetSecurity, 
  6. int userId, IActivityContainer iContainer, TaskRecord inTask) {
  7. ...
  8. boolean componentSpecified = intent.getComponent() != null;
  9. //创建新的Intent对象,即便intent被修改也不受影响
  10. intent = new Intent(intent);
  11. //收集Intent所指向的Activity信息, 当存在多个可供选择的Activity,则直接向用户弹出resolveActivity [见2.7.1]
  12. ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags, profilerInfo, userId);
  13. ActivityContainer container = (ActivityContainer)iContainer;
  14. synchronized (mService) {
  15. if (container != null && container.mParentActivity != null &&
  16. container.mParentActivity.state != RESUMED) {
  17. ... //不进入该分支, container == nul
  18. }
  19. final int realCallingPid = Binder.getCallingPid();
  20. final int realCallingUid = Binder.getCallingUid();
  21. int callingPid;
  22. if (callingUid >= 0) {
  23. callingPid = -1;
  24. } else if (caller == null) {
  25. callingPid = realCallingPid;
  26. callingUid = realCallingUid;
  27. } else {
  28. callingPid = callingUid = -1;
  29. }
  30. final ActivityStack stack;
  31. if (container == null || container.mStack.isOnHomeDisplay()) {
  32. stack = mFocusedStack; // 进入该分支
  33. } else {
  34. stack = container.mStack;
  35. }
  36. //此时mConfigWillChange = false
  37. stack.mConfigWillChange = config != null && mService.mConfiguration.diff(config) != 0;
  38. final long origId = Binder.clearCallingIdentity();
  39. if (aInfo != null &&
  40. (aInfo.applicationInfo.privateFlags
  41. &ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0) {
  42. // heavy-weight进程处理流程, 一般情况下不进入该分支
  43. if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
  44. ...
  45. }
  46. }
  47. //[见流程2.8]
  48. int res = startActivityLocked(caller, intent, resolvedType, aInfo,
  49. voiceSession, voiceInteractor, resultTo, resultWho,
  50. requestCode, callingPid, callingUid, callingPackage,
  51. realCallingPid, realCallingUid, startFlags, options, ignoreTargetSecurity,
  52. componentSpecified, null, container, inTask);
  53. Binder.restoreCallingIdentity(origId);
  54. if (stack.mConfigWillChange) {
  55. ... //不进入该分支
  56. }
  57. if (outResult != null) {
  58. ... //不进入该分支
  59. }
  60. return res;
  61. }
  62. }

该过程主要功能:通过resolveActivity来获取ActivityInfo信息, 然后再进入ASS.startActivityLocked().先来看看

2.7.1 ASS.resolveActivity

  1. // startFlags = 0; profilerInfo = null; userId代表caller UserId
  2. ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags, ProfilerInfo profilerInfo, int userId) {
  3. ActivityInfo aInfo;
  4. ResolveInfo rInfo =
  5. AppGlobals.getPackageManager().resolveIntent(
  6. intent, resolvedType,
  7. PackageManager.MATCH_DEFAULT_ONLY
  8. | ActivityManagerService.STOCK_PM_FLAGS, userId);
  9. aInfo = rInfo != null ? rInfo.activityInfo : null;
  10. if (aInfo != null) {
  11. intent.setComponent(new ComponentName(
  12. aInfo.applicationInfo.packageName, aInfo.name));
  13. if (!aInfo.processName.equals("system")) {
  14. ... //对于非system进程,根据flags来设置相应的debug信息
  15. }
  16. }
  17. return aInfo;
  18. }

ActivityManager类有如下4个flags用于调试:

  • START_FLAG_DEBUG:用于调试debug app
  • START_FLAG_OPENGL_TRACES:用于调试OpenGL tracing
  • START_FLAG_NATIVE_DEBUGGING:用于调试native
  • START_FLAG_TRACK_ALLOCATION: 用于调试allocation tracking

2.7.2 PKMS.resolveIntent

AppGlobals.getPackageManager()经过函数层层调用,获取的是ApplicationPackageManager对象。经过binder IPC调用,最终会调用PackageManagerService对象。故此时调用方法为PMS.resolveIntent().

[-> PackageManagerService.java]

  1. public ResolveInfo resolveIntent(Intent intent, String resolvedType, int flags, int userId) {
  2. if (!sUserManager.exists(userId)) return null;
  3. enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
  4. //[见流程2.7.3]
  5. List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
  6. //根据priority,preferred选择最佳的Activity
  7. return chooseBestActivity(intent, resolvedType, flags, query, userId);
  8. }

2.7.3 PMS.queryIntentActivities

  1. public List<ResolveInfo> queryIntentActivities(Intent intent,
  2. String resolvedType, int flags, int userId) {
  3. ...
  4. ComponentName comp = intent.getComponent();
  5. if (comp == null) {
  6. if (intent.getSelector() != null) {
  7. intent = intent.getSelector();
  8. comp = intent.getComponent();
  9. }
  10. }
  11. if (comp != null) {
  12. final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
  13. //获取Activity信息
  14. final ActivityInfo ai = getActivityInfo(comp, flags, userId);
  15. if (ai != null) {
  16. final ResolveInfo ri = new ResolveInfo();
  17. ri.activityInfo = ai;
  18. list.add(ri);
  19. }
  20. return list;
  21. }
  22. ...
  23. }

ASS.resolveActivity()方法的核心功能是找到相应的Activity组件,并保存到intent对象。

2.8 ASS.startActivityLocked

[-> ActivityStackSupervisor.java]

  1. final int startActivityLocked(IApplicationThread caller, Intent intent, String resolvedType, ActivityInfo aInfo, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid, String callingPackage, int realCallingPid, int realCallingUid, int startFlags, Bundle optionsboolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity, ActivityContainer container, TaskRecord inTask) {
  2. int err = ActivityManager.START_SUCCESS;
  3. //获取调用者的进程记录对象
  4. ProcessRecord callerApp = null;
  5. if (caller != null) {
  6. callerApp = mService.getRecordForAppLocked(caller);
  7. if (callerApp != null) {
  8. callingPid = callerApp.pid;
  9. callingUid = callerApp.info.uid;
  10. } else {
  11. err = ActivityManager.START_PERMISSION_DENIED;
  12. }
  13. }
  14. final int userId = aInfo != null ? UserHandle.getUserId(aInfo.applicationInfo.uid) : 0;
  15. ActivityRecord sourceRecord = null;
  16. ActivityRecord resultRecord = null;
  17. if (resultTo != null) {
  18. //获取调用者所在的Activity
  19. sourceRecord = isInAnyStackLocked(resultTo);
  20. if (sourceRecord != null) {
  21. if (requestCode >= 0 && !sourceRecord.finishing) {
  22. ... //requestCode = -1 则不进入
  23. }
  24. }
  25. }
  26. final int launchFlags = intent.getFlags();
  27. if ((launchFlags & Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0 && sourceRecord != null) {
  28. ... // activity执行结果的返回由源Activity转换到新Activity, 不需要返回结果则不会进入该分支
  29. }
  30. if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
  31. //从Intent中无法找到相应的Component
  32. err = ActivityManager.START_INTENT_NOT_RESOLVED;
  33. }
  34. if (err == ActivityManager.START_SUCCESS && aInfo == null) {
  35. //从Intent中无法找到相应的ActivityInfo
  36. err = ActivityManager.START_INTENT_NOT_RESOLVED;
  37. }
  38. if (err == ActivityManager.START_SUCCESS
  39. && !isCurrentProfileLocked(userId)
  40. && (aInfo.flags & FLAG_SHOW_FOR_ALL_USERS) == 0) {
  41. //尝试启动一个后台Activity, 但该Activity对当前用户不可见
  42. err = ActivityManager.START_NOT_CURRENT_USER_ACTIVITY;
  43. }
  44. ...
  45. //执行后resultStack = null
  46. final ActivityStack resultStack = resultRecord == null ? null : resultRecord.task.stack;
  47. ... //权限检查
  48. // ActivityController不为空的情况,比如monkey测试过程
  49. if (mService.mController != null) {
  50. Intent watchIntent = intent.cloneFilter();
  51. abort |= !mService.mController.activityStarting(watchIntent,
  52. aInfo.applicationInfo.packageName);
  53. }
  54. if (abort) {
  55. ... //权限检查不满足,才进入该分支则直接返回;
  56. return ActivityManager.START_SUCCESS;
  57. }
  58. // 创建Activity记录对象
  59. ActivityRecord r = new ActivityRecord(mService, callerApp, callingUid, callingPackage,
  60. intent, resolvedType, aInfo, mService.mConfiguration, resultRecord, resultWho,
  61. requestCode, componentSpecified, voiceSession != null, this, container, options);
  62. if (outActivity != null) {
  63. outActivity[0] = r;
  64. }
  65. if (r.appTimeTracker == null && sourceRecord != null) {
  66. r.appTimeTracker = sourceRecord.appTimeTracker;
  67. }
  68. // 将mFocusedStack赋予当前stack
  69. final ActivityStack stack = mFocusedStack;
  70. if (voiceSession == null && (stack.mResumedActivity == null
  71. || stack.mResumedActivity.info.applicationInfo.uid != callingUid)) {
  72. // 前台stack还没有resume状态的Activity时, 则检查app切换是否允许
  73. if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid,
  74. realCallingPid, realCallingUid, "Activity start")) {
  75. PendingActivityLaunch pal =
  76. new PendingActivityLaunch(r, sourceRecord, startFlags, stack);
  77. // 当不允许切换,则把要启动的Activity添加到mPendingActivityLaunches对象, 并且直接返回.
  78. mPendingActivityLaunches.add(pal);
  79. ActivityOptions.abort(options);
  80. return ActivityManager.START_SWITCHES_CANCELED;
  81. }
  82. }
  83. if (mService.mDidAppSwitch) {
  84. //从上次禁止app切换以来,这是第二次允许app切换,因此将允许切换时间设置为0,则表示可以任意切换app
  85. mService.mAppSwitchesAllowedTime = 0;
  86. } else {
  87. mService.mDidAppSwitch = true;
  88. }
  89. //处理 pendind Activity的启动, 这些Activity是由于app switch禁用从而被hold的等待启动activity
  90. doPendingActivityLaunchesLocked(false);
  91. //[见流程2.9]
  92. err = startActivityUncheckedLocked(r, sourceRecord, voiceSession, voiceInteractor,
  93. startFlags, true, options, inTask);
  94. if (err < 0) {
  95. notifyActivityDrawnForKeyguard();
  96. }
  97. return err;
  98. }

其中有两个返回值代表启动Activity失败:

  • START_INTENT_NOT_RESOLVED: 从Intent中无法找到相应的Component或者ActivityInfo
  • START_NOT_CURRENT_USER_ACTIVITY:该Activity对当前用户不可见

2.9 ASS.startActivityUncheckedLocked

[-> ActivityStackSupervisor.java]

  1. // sourceRecord是指调用者, r是指本次将要启动的Activity
  2. final int startActivityUncheckedLocked(final ActivityRecord r, ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags, boolean doResume, Bundle options, TaskRecord inTask) {
  3. final Intent intent = r.intent;
  4. final int callingUid = r.launchedFromUid;
  5. if (inTask != null && !inTask.inRecents) {
  6. inTask = null;
  7. }
  8. final boolean launchSingleTop = r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP;
  9. final boolean launchSingleInstance = r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE;
  10. final boolean launchSingleTask = r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK;
  11. int launchFlags = intent.getFlags();
  12. // 当intent和activity manifest存在冲突,则manifest优先
  13. if ((launchFlags & Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0 &&
  14. (launchSingleInstance || launchSingleTask)) {
  15. launchFlags &=
  16. ~(Intent.FLAG_ACTIVITY_NEW_DOCUMENT | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
  17. } else {
  18. ...
  19. }
  20. ...
  21. mUserLeaving = (launchFlags & Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
  22. //当本次不需要resume,则设置为延迟resume的状态
  23. if (!doResume) {
  24. r.delayedResume = true;
  25. }
  26. ActivityRecord notTop =
  27. (launchFlags & Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP) != 0 ? r : null;
  28. if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
  29. ActivityRecord checkedCaller = sourceRecord;
  30. if (checkedCaller == null) {
  31. checkedCaller = mFocusedStack.topRunningNonDelayedActivityLocked(notTop);
  32. }
  33. if (!checkedCaller.realActivity.equals(r.realActivity)) {
  34. //调用者 与将要启动的Activity不相同时,进入该分支。
  35. startFlags &= ~ActivityManager.START_FLAG_ONLY_IF_NEEDED;
  36. }
  37. }
  38. boolean addingToTask = false;
  39. TaskRecord reuseTask = null;
  40. //当调用者不是来自activity,而是明确指定task的情况。
  41. if (sourceRecord == null && inTask != null && inTask.stack != null) {
  42. ... //目前sourceRecord不为空,则不进入该分支
  43. } else {
  44. inTask = null;
  45. }
  46. if (inTask == null) {
  47. if (sourceRecord == null) {
  48. //调用者并不是Activity context,则强制创建新task
  49. if ((launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) == 0 && inTask == null) {
  50. launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
  51. }
  52. } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
  53. //调用者activity带有single instance,则创建新task
  54. launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
  55. } else if (launchSingleInstance || launchSingleTask) {
  56. //目标activity带有single instance或者single task,则创建新task
  57. launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
  58. }
  59. }
  60. ActivityInfo newTaskInfo = null;
  61. Intent newTaskIntent = null;
  62. ActivityStack sourceStack;
  63. if (sourceRecord != null) {
  64. if (sourceRecord.finishing) {
  65. //调用者处于即将finish状态,则创建新task
  66. if ((launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
  67. launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
  68. newTaskInfo = sourceRecord.info;
  69. newTaskIntent = sourceRecord.task.intent;
  70. }
  71. sourceRecord = null;
  72. sourceStack = null;
  73. } else {
  74. //当调用者Activity不为空,且不处于finishing状态,则其所在栈赋于sourceStack
  75. sourceStack = sourceRecord.task.stack;
  76. }
  77. } else {
  78. sourceStack = null;
  79. }
  80. ...
  81. targetStack.mLastPausedActivity = null;
  82. //创建activity [见流程2.10]
  83. targetStack.startActivityLocked(r, newTask, doResume, keepCurTransition, options);
  84. if (!launchTaskBehind) {
  85. mService.setFocusedActivityLocked(r, "startedActivity");
  86. }
  87. return ActivityManager.START_SUCCESS;
  88. }

找到或创建新的Activit所属于的Task对象,之后调用AS.startActivityLocked

2.9.1 Launch Mode

先来说说在ActivityInfo.java中定义了4类Launch Mode:

  • LAUNCH_MULTIPLE(standard):最常见的情形,每次启动Activity都是创建新的Activity;
  • LAUNCH_SINGLE_TOP: 当Task顶部存在同一个Activity则不再重新创建;其余情况同上;
  • LAUNCH_SINGLE_TASK:当Task栈存在同一个Activity(不在task顶部),则不重新创建,而移除该Activity上面其他的Activity;其余情况同上;
  • LAUNCH_SINGLE_INSTANCE:每个Task只有一个Activity.

再来说说几个常见的flag含义:

  • FLAG_ACTIVITY_NEW_TASK:将Activity放入一个新启动的Task;
  • FLAG_ACTIVITY_CLEAR_TASK:启动Activity时,将目标Activity关联的Task清除,再启动新Task,将该Activity放入该Task。该flags跟FLAG_ACTIVITY_NEW_TASK配合使用。
  • FLAG_ACTIVITY_CLEAR_TOP:启动非栈顶Activity时,先清除该Activity之上的Activity。例如Task已有A、B、C3个Activity,启动A,则清除B,C。类似于SingleTop。

最后再说说:设置FLAG_ACTIVITY_NEW_TASK的几个情况:

  • 调用者并不是Activity context;
  • 调用者activity带有single instance;
  • 目标activity带有single instance或者single task;
  • 调用者处于finishing状态;

2.10 AS.startActivityLocked

[-> ActivityStack.java]

  1. final void startActivityLocked(ActivityRecord r, boolean newTask, boolean doResume, boolean keepCurTransition, Bundle options) {
  2. TaskRecord rTask = r.task;
  3. final int taskId = rTask.taskId;
  4. if (!r.mLaunchTaskBehind && (taskForIdLocked(taskId) == null || newTask)) {
  5. //task中的上一个activity已被移除,或者ams重用该task,则将该task移到顶部
  6. insertTaskAtTop(rTask, r);
  7. mWindowManager.moveTaskToTop(taskId);
  8. }
  9. TaskRecord task = null;
  10. if (!newTask) {
  11. boolean startIt = true;
  12. for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
  13. task = mTaskHistory.get(taskNdx);
  14. if (task.getTopActivity() == null) {
  15. //该task所有activity都finishing
  16. continue;
  17. }
  18. if (task == r.task) {
  19. if (!startIt) {
  20. task.addActivityToTop(r);
  21. r.putInHistory();
  22. mWindowManager.addAppToken(task.mActivities.indexOf(r), r.appToken,
  23. r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen,
  24. (r.info.flags & ActivityInfo.FLAG_SHOW_FOR_ALL_USERS) != 0,
  25. r.userId, r.info.configChanges, task.voiceSession != null,
  26. r.mLaunchTaskBehind);
  27. ActivityOptions.abort(options);
  28. return;
  29. }
  30. break;
  31. } else if (task.numFullscreen > 0) {
  32. startIt = false;
  33. }
  34. }
  35. }
  36. if (task == r.task && mTaskHistory.indexOf(task) != (mTaskHistory.size() - 1)) {
  37. mStackSupervisor.mUserLeaving = false;
  38. }
  39. task = r.task;
  40. task.addActivityToTop(r);
  41. task.setFrontOfTask();
  42. r.putInHistory();
  43. mActivityTrigger.activityStartTrigger(r.intent, r.info, r.appInfo);
  44. if (!isHomeStack() || numActivities() > 0) {
  45. //当切换到新的task,或者下一个activity进程目前并没有运行,则
  46. boolean showStartingIcon = newTask;
  47. ProcessRecord proc = r.app;
  48. if (proc == null) {
  49. proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
  50. }
  51. if (proc == null || proc.thread == null) {
  52. showStartingIcon = true;
  53. }
  54. if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
  55. mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, keepCurTransition);
  56. mNoAnimActivities.add(r);
  57. } else {
  58. mWindowManager.prepareAppTransition(newTask
  59. ? r.mLaunchTaskBehind
  60. ? AppTransition.TRANSIT_TASK_OPEN_BEHIND
  61. : AppTransition.TRANSIT_TASK_OPEN
  62. : AppTransition.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
  63. mNoAnimActivities.remove(r);
  64. }
  65. mWindowManager.addAppToken(task.mActivities.indexOf(r),
  66. r.appToken, r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen,
  67. (r.info.flags & ActivityInfo.FLAG_SHOW_FOR_ALL_USERS) != 0, r.userId,
  68. r.info.configChanges, task.voiceSession != null, r.mLaunchTaskBehind);
  69. boolean doShow = true;
  70. if (newTask) {
  71. if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
  72. resetTaskIfNeededLocked(r, r);
  73. doShow = topRunningNonDelayedActivityLocked(null) == r;
  74. }
  75. } else if (options != null && new ActivityOptions(options).getAnimationType()
  76. == ActivityOptions.ANIM_SCENE_TRANSITION) {
  77. doShow = false;
  78. }
  79. if (r.mLaunchTaskBehind) {
  80. mWindowManager.setAppVisibility(r.appToken, true);
  81. ensureActivitiesVisibleLocked(null, 0);
  82. } else if (SHOW_APP_STARTING_PREVIEW && doShow) {
  83. ActivityRecord prev = mResumedActivity;
  84. if (prev != null) {
  85. //当前activity所属不同的task
  86. if (prev.task != r.task) {
  87. prev = null;
  88. }
  89. //当前activity已经displayed
  90. else if (prev.nowVisible) {
  91. prev = null;
  92. }
  93. }
  94. mWindowManager.setAppStartingWindow(
  95. r.appToken, r.packageName, r.theme,
  96. mService.compatibilityInfoForPackageLocked(
  97. r.info.applicationInfo), r.nonLocalizedLabel,
  98. r.labelRes, r.icon, r.logo, r.windowFlags,
  99. prev != null ? prev.appToken : null, showStartingIcon);
  100. r.mStartingWindowShown = true;
  101. }
  102. } else {
  103. mWindowManager.addAppToken(task.mActivities.indexOf(r), r.appToken,
  104. r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen,
  105. (r.info.flags & ActivityInfo.FLAG_SHOW_FOR_ALL_USERS) != 0, r.userId,
  106. r.info.configChanges, task.voiceSession != null, r.mLaunchTaskBehind);
  107. ActivityOptions.abort(options);
  108. options = null;
  109. }
  110. if (doResume) {
  111. // [见流程2.11]
  112. mStackSupervisor.resumeTopActivitiesLocked(this, r, options);
  113. }
  114. }

2.11 ASS.resumeTopActivitiesLocked

  1. boolean resumeTopActivitiesLocked(ActivityStack targetStack, ActivityRecord target, Bundle targetOptions) {
  2. if (targetStack == null) {
  3. targetStack = mFocusedStack;
  4. }
  5. boolean result = false;
  6. if (isFrontStack(targetStack)) {
  7. //[见流程2.12]
  8. result = targetStack.resumeTopActivityLocked(target, targetOptions);
  9. }
  10. for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
  11. final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
  12. for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
  13. final ActivityStack stack = stacks.get(stackNdx);
  14. if (stack == targetStack) {
  15. //上面刚已启动
  16. continue;
  17. }
  18. if (isFrontStack(stack)) {
  19. stack.resumeTopActivityLocked(null);
  20. }
  21. }
  22. }
  23. return result;
  24. }

2.12 AS.resumeTopActivityLocked

  1. final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
  2. if (mStackSupervisor.inResumeTopActivity) {
  3. return false; //防止递归启动
  4. }
  5. boolean result = false;
  6. try {
  7. mStackSupervisor.inResumeTopActivity = true;
  8. if (mService.mLockScreenShown == ActivityManagerService.LOCK_SCREEN_LEAVING) {
  9. mService.mLockScreenShown = ActivityManagerService.LOCK_SCREEN_HIDDEN;
  10. mService.updateSleepIfNeededLocked();
  11. }
  12. //[见流程2.13]
  13. result = resumeTopActivityInnerLocked(prev, options);
  14. } finally {
  15. mStackSupervisor.inResumeTopActivity = false;
  16. }
  17. return result;
  18. }

inResumeTopActivity用于保证每次只有一个Activity执行resumeTopActivityLocked()操作.

2.13 AS.resumeTopActivityInnerLocked

  1. private boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) {
  2. ... //系统没有进入booting或booted状态,则不允许启动Activity
  3. ActivityRecord parent = mActivityContainer.mParentActivity;
  4. if ((parent != null && parent.state != ActivityState.RESUMED) ||
  5. !mActivityContainer.isAttachedLocked()) {
  6. return false;
  7. }
  8. //top running之后的任意处于初始化状态且有显示StartingWindow, 则移除StartingWindow
  9. cancelInitializingActivities();
  10. //找到第一个没有finishing的栈顶activity
  11. final ActivityRecord next = topRunningActivityLocked(null);
  12. final boolean userLeaving = mStackSupervisor.mUserLeaving;
  13. mStackSupervisor.mUserLeaving = false;
  14. final TaskRecord prevTask = prev != null ? prev.task : null;
  15. if (next == null) {
  16. final String reason = "noMoreActivities";
  17. if (!mFullscreen) {
  18. //当该栈没有全屏,则尝试聚焦到下一个可见的stack
  19. final ActivityStack stack = getNextVisibleStackLocked();
  20. if (adjustFocusToNextVisibleStackLocked(stack, reason)) {
  21. return mStackSupervisor.resumeTopActivitiesLocked(stack, prev, null);
  22. }
  23. }
  24. ActivityOptions.abort(options);
  25. final int returnTaskType = prevTask == null || !prevTask.isOverHomeStack() ?
  26. HOME_ACTIVITY_TYPE : prevTask.getTaskToReturnTo();
  27. //启动home桌面activity
  28. return isOnHomeDisplay() &&
  29. mStackSupervisor.resumeHomeStackTask(returnTaskType, prev, reason);
  30. }
  31. ......
  32. //处于睡眠或者关机状态,top activity已暂停的情况下
  33. if (mService.isSleepingOrShuttingDown()
  34. && mLastPausedActivity == next
  35. && mStackSupervisor.allPausedActivitiesComplete()) {
  36. mWindowManager.executeAppTransition();
  37. mNoAnimActivities.clear();
  38. ActivityOptions.abort(options);
  39. return false;
  40. }
  41. if (mService.mStartedUsers.get(next.userId) == null) {
  42. return false; //拥有该activity的用户没有启动则直接返回
  43. }
  44. mStackSupervisor.mStoppingActivities.remove(next);
  45. mStackSupervisor.mGoingToSleepActivities.remove(next);
  46. next.sleeping = false;
  47. mStackSupervisor.mWaitingVisibleActivities.remove(next);
  48. mActivityTrigger.activityResumeTrigger(next.intent, next.info, next.appInfo);
  49. if (!mStackSupervisor.allPausedActivitiesComplete()) {
  50. return false; //当正处于暂停activity,则直接返回
  51. }
  52. mStackSupervisor.setLaunchSource(next.info.applicationInfo.uid);
  53. //需要等待暂停当前activity完成,再resume top activity
  54. boolean dontWaitForPause = (next.info.flags&ActivityInfo.FLAG_RESUME_WHILE_PAUSING) != 0;
  55. //暂停其他Activity[见小节2.13.1]
  56. boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, true, dontWaitForPause);
  57. if (mResumedActivity != null) {
  58. //当前resumd状态activity不为空,则需要先暂停该Activity
  59. pausing |= startPausingLocked(userLeaving, false, true, dontWaitForPause);
  60. }
  61. if (pausing) {
  62. if (next.app != null && next.app.thread != null) {
  63. mService.updateLruProcessLocked(next.app, true, null);
  64. }
  65. return true;
  66. }
  67. ......
  68. Bundle resumeAnimOptions = null;
  69. if (anim) {
  70. ActivityOptions opts = next.getOptionsForTargetActivityLocked();
  71. if (opts != null) {
  72. resumeAnimOptions = opts.toBundle();
  73. }
  74. next.applyOptionsLocked();
  75. } else {
  76. next.clearOptionsLocked();
  77. }
  78. ActivityStack lastStack = mStackSupervisor.getLastStack();
  79. //进程已存在的情况
  80. if (next.app != null && next.app.thread != null) {
  81. //activity正在成为可见
  82. mWindowManager.setAppVisibility(next.appToken, true);
  83. next.startLaunchTickingLocked();
  84. ActivityRecord lastResumedActivity = lastStack == null ? null :lastStack.mResumedActivity;
  85. ActivityState lastState = next.state;
  86. mService.updateCpuStats();
  87. //设置Activity状态为resumed
  88. next.state = ActivityState.RESUMED;
  89. mResumedActivity = next;
  90. next.task.touchActiveTime();
  91. mRecentTasks.addLocked(next.task);
  92. mService.updateLruProcessLocked(next.app, true, null);
  93. updateLRUListLocked(next);
  94. mService.updateOomAdjLocked();
  95. boolean notUpdated = true;
  96. if (mStackSupervisor.isFrontStack(this)) {
  97. Configuration config = mWindowManager.updateOrientationFromAppTokens(
  98. mService.mConfiguration,
  99. next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
  100. if (config != null) {
  101. next.frozenBeforeDestroy = true;
  102. }
  103. notUpdated = !mService.updateConfigurationLocked(config, next, false, false);
  104. }
  105. if (notUpdated) {
  106. ActivityRecord nextNext = topRunningActivityLocked(null);
  107. if (nextNext != next) {
  108. mStackSupervisor.scheduleResumeTopActivities();
  109. }
  110. if (mStackSupervisor.reportResumedActivityLocked(next)) {
  111. mNoAnimActivities.clear();
  112. return true;
  113. }
  114. return false;
  115. }
  116. try {
  117. //分发所有pending结果.
  118. ArrayList<ResultInfo> a = next.results;
  119. if (a != null) {
  120. final int N = a.size();
  121. if (!next.finishing && N > 0) {
  122. next.app.thread.scheduleSendResult(next.appToken, a);
  123. }
  124. }
  125. if (next.newIntents != null) {
  126. next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
  127. }
  128. next.sleeping = false;
  129. mService.showAskCompatModeDialogLocked(next);
  130. next.app.pendingUiClean = true;
  131. next.app.forceProcessStateUpTo(mService.mTopProcessState);
  132. next.clearOptionsLocked();
  133. //触发onResume()
  134. next.app.thread.scheduleResumeActivity(next.appToken, next.app.repProcState,
  135. mService.isNextTransitionForward(), resumeAnimOptions);
  136. mStackSupervisor.checkReadyForSleepLocked();
  137. } catch (Exception e) {
  138. ...
  139. return true;
  140. }
  141. next.visible = true;
  142. completeResumeLocked(next);
  143. next.stopped = false;
  144. } else {
  145. if (!next.hasBeenLaunched) {
  146. next.hasBeenLaunched = true;
  147. } else {
  148. if (SHOW_APP_STARTING_PREVIEW) {
  149. mWindowManager.setAppStartingWindow(
  150. next.appToken, next.packageName, next.theme,
  151. mService.compatibilityInfoForPackageLocked(
  152. next.info.applicationInfo),
  153. next.nonLocalizedLabel,
  154. next.labelRes, next.icon, next.logo, next.windowFlags,
  155. null, true);
  156. }
  157. }
  158. //见流程2.14
  159. mStackSupervisor.startSpecificActivityLocked(next, true, true);
  160. }
  161. return true;
  162. }

主要分支功能:

  • 当找不到需要resume的Activity,则直接回到桌面;
  • 否则,当mResumedActivity不为空,则执行startPausingLocked()暂停该activity;
  • 然后再进入startSpecificActivityLocked环节,接下来从这里继续往下说。

2.14 ASS.startSpecificActivityLocked

  1. void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
  2. ProcessRecord app = mService.getProcessRecordLocked(r.processName,
  3. r.info.applicationInfo.uid, true);
  4. r.task.stack.setLaunchTime(r);
  5. if (app != null && app.thread != null) {
  6. try {
  7. if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
  8. || !"android".equals(r.info.packageName)) {
  9. app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
  10. mService.mProcessStats);
  11. }
  12. //真正的启动Activity【见流程2.17
  13. realStartActivityLocked(r, app, andResume, checkConfig);
  14. return;
  15. } catch (RemoteException e) {
  16. Slog.w(TAG, "Exception when starting activity "
  17. + r.intent.getComponent().flattenToShortString(), e);
  18. }
  19. }
  20. //当进程不存在则创建进程 [见流程2.14.1]
  21. mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
  22. "activity", r.intent.getComponent(), false, false, true);
  23. }

2.15 AMS.startProcessLocked

    在文章理解Android进程启动之全过程中,详细介绍了AMS.startProcessLocked()整个过程,创建完新进程后会在新进程中调用AMP.attachApplication ,该方法经过binder ipc后调用到AMS.attachApplicationLocked

  1. private final boolean attachApplicationLocked(IApplicationThread thread, int pid) {
  2. ...
  3. 只有当系统启动完,或者app允许启动过程允许,则会true
  4. boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
  5. thread.bindApplication(...);
  6. if (normalMode) {
  7. //【见流程2.16
  8. if (mStackSupervisor.attachApplicationLocked(app)) {
  9. didSomething = true;
  10. }
  11. }
  12. ...
  13. }

在执行完bindApplication()之后进入ASS.attachApplicationLocked()

2.16 ASS.attachApplicationLocked

  1. boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
  2. final String processName = app.processName;
  3. boolean didSomething = false;
  4. for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
  5. ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
  6. for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
  7. final ActivityStack stack = stacks.get(stackNdx);
  8. if (!isFrontStack(stack)) {
  9. continue;
  10. }
  11. //获取前台stack中栈顶第一个非finishing的Activity
  12. ActivityRecord hr = stack.topRunningActivityLocked(null);
  13. if (hr != null) {
  14. if (hr.app == null && app.uid == hr.info.applicationInfo.uid
  15. && processName.equals(hr.processName)) {
  16. try {
  17. //真正的启动Activity【见流程2.17
  18. if (realStartActivityLocked(hr, app, true, true)) {
  19. didSomething = true;
  20. }
  21. } catch (RemoteException e) {
  22. throw e;
  23. }
  24. }
  25. }
  26. }
  27. }
  28. if (!didSomething) {
  29. //启动Activity不成功,则确保有可见的Activity
  30. ensureActivitiesVisibleLocked(null, 0);
  31. }
  32. return didSomething;
  33. }

2.17 ASS.realStartActivityLocked

  1. final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app, boolean andResume, boolean checkConfig) throws RemoteException {
  2. if (andResume) {
  3. r.startFreezingScreenLocked(app, 0);
  4. mWindowManager.setAppVisibility(r.appToken, true);
  5. //调度启动ticks用以收集应用启动慢的信息
  6. r.startLaunchTickingLocked();
  7. }
  8. if (checkConfig) {
  9. Configuration config = mWindowManager.updateOrientationFromAppTokens(
  10. mService.mConfiguration,
  11. r.mayFreezeScreenLocked(app) ? r.appToken : null);
  12. //更新Configuration
  13. mService.updateConfigurationLocked(config, r, false, false);
  14. }
  15. r.app = app;
  16. app.waitingToKill = null;
  17. r.launchCount++;
  18. r.lastLaunchTime = SystemClock.uptimeMillis();
  19. int idx = app.activities.indexOf(r);
  20. if (idx < 0) {
  21. app.activities.add(r);
  22. }
  23. mService.updateLruProcessLocked(app, true, null);
  24. mService.updateOomAdjLocked();
  25. final TaskRecord task = r.task;
  26. if (task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE ||
  27. task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE_PRIV) {
  28. setLockTaskModeLocked(task, LOCK_TASK_MODE_LOCKED, "mLockTaskAuth==LAUNCHABLE", false);
  29. }
  30. final ActivityStack stack = task.stack;
  31. try {
  32. if (app.thread == null) {
  33. throw new RemoteException();
  34. }
  35. List<ResultInfo> results = null;
  36. List<ReferrerIntent> newIntents = null;
  37. if (andResume) {
  38. results = r.results;
  39. newIntents = r.newIntents;
  40. }
  41. if (r.isHomeActivity() && r.isNotResolverActivity()) {
  42. //home进程是该栈的根进程
  43. mService.mHomeProcess = task.mActivities.get(0).app;
  44. }
  45. mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
  46. ...
  47. if (andResume) {
  48. app.hasShownUi = true;
  49. app.pendingUiClean = true;
  50. }
  51. //将该进程设置为前台进程PROCESS_STATE_TOP
  52. app.forceProcessStateUpTo(mService.mTopProcessState);
  53. //【见流程2.18
  54. app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
  55. System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
  56. new Configuration(stack.mOverrideConfig), r.compat, r.launchedFromPackage,
  57. task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results,
  58. newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo);
  59. if ((app.info.privateFlags&ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0) {
  60. ... //处理heavy-weight进程
  61. }
  62. } catch (RemoteException e) {
  63. if (r.launchFailed) {
  64. //第二次启动失败,则结束该activity
  65. mService.appDiedLocked(app);
  66. stack.requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
  67. "2nd-crash", false);
  68. return false;
  69. }
  70. //这是第一个启动失败,则重启进程
  71. app.activities.remove(r);
  72. throw e;
  73. }
  74. //将该进程加入到mLRUActivities队列顶部
  75. stack.updateLRUListLocked(r);
  76. if (andResume) {
  77. //启动过程的一部分
  78. stack.minimalResumeActivityLocked(r);
  79. } else {
  80. r.state = STOPPED;
  81. r.stopped = true;
  82. }
  83. if (isFrontStack(stack)) {
  84. //当系统发生更新时,只会执行一次的用户向导
  85. mService.startSetupActivityLocked();
  86. }
  87. //更新所有与该Activity具有绑定关系的Service连接
  88. mService.mServices.updateServiceConnectionActivitiesLocked(r.app);
  89. return true;
  90. }

2.18 ATP.scheduleLaunchActivity

[-> ApplicationThreadProxy.java]

  1. public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident, ActivityInfo info, Configuration curConfig, Configuration overrideConfig, CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor, int procState, Bundle state, PersistableBundle persistentState, List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents, boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) throws RemoteException {
  2. Parcel data = Parcel.obtain();
  3. data.writeInterfaceToken(IApplicationThread.descriptor);
  4. intent.writeToParcel(data, 0);
  5. data.writeStrongBinder(token);
  6. data.writeInt(ident);
  7. info.writeToParcel(data, 0);
  8. curConfig.writeToParcel(data, 0);
  9. if (overrideConfig != null) {
  10. data.writeInt(1);
  11. overrideConfig.writeToParcel(data, 0);
  12. } else {
  13. data.writeInt(0);
  14. }
  15. compatInfo.writeToParcel(data, 0);
  16. data.writeString(referrer);
  17. data.writeStrongBinder(voiceInteractor != null ? voiceInteractor.asBinder() : null);
  18. data.writeInt(procState);
  19. data.writeBundle(state);
  20. data.writePersistableBundle(persistentState);
  21. data.writeTypedList(pendingResults);
  22. data.writeTypedList(pendingNewIntents);
  23. data.writeInt(notResumed ? 1 : 0);
  24. data.writeInt(isForward ? 1 : 0);
  25. if (profilerInfo != null) {
  26. data.writeInt(1);
  27. profilerInfo.writeToParcel(data, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
  28. } else {
  29. data.writeInt(0);
  30. }
  31. //【见流程2.19
  32. mRemote.transact(SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION, data, null,
  33. IBinder.FLAG_ONEWAY);
  34. data.recycle();
  35. }

2.19 ATN.onTransact

[-> ApplicationThreadNative.java]

  1. public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
  2. switch (code) {
  3. case SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION:
  4. {
  5. data.enforceInterface(IApplicationThread.descriptor);
  6. Intent intent = Intent.CREATOR.createFromParcel(data);
  7. IBinder b = data.readStrongBinder();
  8. int ident = data.readInt();
  9. ActivityInfo info = ActivityInfo.CREATOR.createFromParcel(data);
  10. Configuration curConfig = Configuration.CREATOR.createFromParcel(data);
  11. Configuration overrideConfig = null;
  12. if (data.readInt() != 0) {
  13. overrideConfig = Configuration.CREATOR.createFromParcel(data);
  14. }
  15. CompatibilityInfo compatInfo = CompatibilityInfo.CREATOR.createFromParcel(data);
  16. String referrer = data.readString();
  17. IVoiceInteractor voiceInteractor = IVoiceInteractor.Stub.asInterface(
  18. data.readStrongBinder());
  19. int procState = data.readInt();
  20. Bundle state = data.readBundle();
  21. PersistableBundle persistentState = data.readPersistableBundle();
  22. List<ResultInfo> ri = data.createTypedArrayList(ResultInfo.CREATOR);
  23. List<ReferrerIntent> pi = data.createTypedArrayList(ReferrerIntent.CREATOR);
  24. boolean notResumed = data.readInt() != 0;
  25. boolean isForward = data.readInt() != 0;
  26. ProfilerInfo profilerInfo = data.readInt() != 0
  27. ? ProfilerInfo.CREATOR.createFromParcel(data) : null;
  28. //【见流程2.20
  29. scheduleLaunchActivity(intent, b, ident, info, curConfig, overrideConfig, compatInfo,
  30. referrer, voiceInteractor, procState, state, persistentState, ri, pi,
  31. notResumed, isForward, profilerInfo);
  32. return true;
  33. }
  34. ...
  35. }
  36. }

2.20 AT.scheduleLaunchActivity

[-> ApplicationThread.java]

  1. public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident, ActivityInfo info, Configuration curConfig, Configuration overrideConfig, CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor, int procState, Bundle state, PersistableBundle persistentState, List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents, boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {
  2. updateProcessState(procState, false);
  3. ActivityClientRecord r = new ActivityClientRecord();
  4. r.token = token;
  5. r.ident = ident;
  6. r.intent = intent;
  7. r.referrer = referrer;
  8. r.voiceInteractor = voiceInteractor;
  9. r.activityInfo = info;
  10. r.compatInfo = compatInfo;
  11. r.state = state;
  12. r.persistentState = persistentState;
  13. r.pendingResults = pendingResults;
  14. r.pendingIntents = pendingNewIntents;
  15. r.startsNotResumed = notResumed;
  16. r.isForward = isForward;
  17. r.profilerInfo = profilerInfo;
  18. r.overrideConfig = overrideConfig;
  19. updatePendingConfiguration(curConfig);
  20. //【见流程2.21
  21. sendMessage(H.LAUNCH_ACTIVITY, r);
  22. }

2.21 H.handleMessage

[-> ActivityThread.java ::H]

  1. public void handleMessage(Message msg) {
  2. switch (msg.what) {
  3. case LAUNCH_ACTIVITY: {
  4. final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
  5. r.packageInfo = getPackageInfoNoCheck(
  6. r.activityInfo.applicationInfo, r.compatInfo);
  7. //【见流程2.22】
  8. handleLaunchActivity(r, null);
  9. } break;
  10. ...
  11. }
  12. }

2.22 ActivityThread.handleLaunchActivity

[-> ActivityThread.java]

  1. private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
  2. unscheduleGcIdler();
  3. mSomeActivitiesChanged = true;
  4. //最终回调目标Activity的onConfigurationChanged()
  5. handleConfigurationChanged(null, null);
  6. //初始化wms
  7. WindowManagerGlobal.initialize();
  8. //最终回调目标Activity的onCreate[见流程2.23]
  9. Activity a = performLaunchActivity(r, customIntent);
  10. if (a != null) {
  11. r.createdConfig = new Configuration(mConfiguration);
  12. Bundle oldState = r.state;
  13. //最终回调目标Activity的onStart,onResume.
  14. handleResumeActivity(r.token, false, r.isForward,
  15. !r.activity.mFinished && !r.startsNotResumed);
  16. if (!r.activity.mFinished && r.startsNotResumed) {
  17. r.activity.mCalled = false;
  18. mInstrumentation.callActivityOnPause(r.activity);
  19. r.paused = true;
  20. }
  21. } else {
  22. //存在error则停止该Activity
  23. ActivityManagerNative.getDefault()
  24. .finishActivity(r.token, Activity.RESULT_CANCELED, null, false);
  25. }
  26. }

2.23 ActivityThread.performLaunchActivity

[-> ActivityThread.java]

  1. private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
  2. ActivityInfo aInfo = r.activityInfo;
  3. if (r.packageInfo == null) {
  4. r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
  5. Context.CONTEXT_INCLUDE_CODE);
  6. }
  7. ComponentName component = r.intent.getComponent();
  8. if (component == null) {
  9. component = r.intent.resolveActivity(
  10. mInitialApplication.getPackageManager());
  11. r.intent.setComponent(component);
  12. }
  13. if (r.activityInfo.targetActivity != null) {
  14. component = new ComponentName(r.activityInfo.packageName,
  15. r.activityInfo.targetActivity);
  16. }
  17. Activity activity = null;
  18. try {
  19. java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
  20. activity = mInstrumentation.newActivity(
  21. cl, component.getClassName(), r.intent);
  22. StrictMode.incrementExpectedActivityCount(activity.getClass());
  23. r.intent.setExtrasClassLoader(cl);
  24. r.intent.prepareToEnterProcess();
  25. if (r.state != null) {
  26. r.state.setClassLoader(cl);
  27. }
  28. } catch (Exception e) {
  29. ...
  30. }
  31. try {
  32. //创建Application对象
  33. Application app = r.packageInfo.makeApplication(false, mInstrumentation);
  34. if (activity != null) {
  35. Context appContext = createBaseContextForActivity(r, activity);
  36. CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
  37. Configuration config = new Configuration(mCompatConfiguration);
  38. activity.attach(appContext, this, getInstrumentation(), r.token,
  39. r.ident, app, r.intent, r.activityInfo, title, r.parent,
  40. r.embeddedID, r.lastNonConfigurationInstances, config,
  41. r.referrer, r.voiceInteractor);
  42. if (customIntent != null) {
  43. activity.mIntent = customIntent;
  44. }
  45. r.lastNonConfigurationInstances = null;
  46. activity.mStartedActivity = false;
  47. int theme = r.activityInfo.getThemeResource();
  48. if (theme != 0) {
  49. activity.setTheme(theme);
  50. }
  51. activity.mCalled = false;
  52. if (r.isPersistable()) {
  53. mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
  54. } else {
  55. mInstrumentation.callActivityOnCreate(activity, r.state);
  56. }
  57. ...
  58. r.activity = activity;
  59. r.stopped = true;
  60. if (!r.activity.mFinished) {
  61. activity.performStart();
  62. r.stopped = false;
  63. }
  64. if (!r.activity.mFinished) {
  65. if (r.isPersistable()) {
  66. if (r.state != null || r.persistentState != null) {
  67. mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
  68. r.persistentState);
  69. }
  70. } else if (r.state != null) {
  71. mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
  72. }
  73. }
  74. if (!r.activity.mFinished) {
  75. activity.mCalled = false;
  76. if (r.isPersistable()) {
  77. //调用Activity.onCreat方法
  78. mInstrumentation.callActivityOnPostCreate(activity, r.state,
  79. r.persistentState);
  80. } else {
  81. mInstrumentation.callActivityOnPostCreate(activity, r.state);
  82. }
  83. ...
  84. }
  85. }
  86. r.paused = true;
  87. mActivities.put(r.token, r);
  88. } catch (Exception e) {
  89. ...
  90. }
  91. return activity;
  92. }

到此,正式进入了Activity的onCreate, onStart, onResume这些生命周期的过程。

三. 总结

本文详细startActivity的整个启动流程,

  • 流程[2.1 ~2.4]:运行在调用者所在进程,比如从桌面启动Activity,则调用者所在进程为launcher进程,launcher进程利用ActivityManagerProxy作为Binder Client,进入system_server进程(AMS相应的Server端)。
  • 流程[2.5 ~2.18]:运行在system_server系统进程,整个过程最为复杂、核心的过程,下面其中部分步骤:
    • 流程[2.7]:会调用到resolveActivity(),借助PackageManager来查询系统中所有符合要求的Activity,当存在多个满足条件的Activity则会弹框让用户来选择;
    • 流程[2.8]:创建ActivityRecord对象,并检查是否运行App切换,然后再处理mPendingActivityLaunches中的activity;
    • 流程[2.9]:为Activity找到或创建新的Task对象,设置flags信息;
    • 流程[2.13]:当没有处于非finishing状态的Activity,则直接回到桌面; 否则,当mResumedActivity不为空则执行startPausingLocked()暂停该activity;然后再进入startSpecificActivityLocked()环节;
    • 流程[2.14]:当目标进程已存在则直接进入流程[2.17],当进程不存在则创建进程,经过层层调用还是会进入流程[2.17];
    • 流程[2.17]:system_server进程利用的ATP(Binder Client),经过Binder,程序接下来进入目标进程。
  • 流程[2.19 ~2.18]:运行在目标进程,通过Handler消息机制,该进程中的Binder线程向主线程发送H.LAUNCH_ACTIVITY,最终会通过反射创建目标Activity,然后进入onCreate()生命周期。

从另一个角度下图来概括:

                 

启动流程:

  1. 点击桌面App图标,Launcher进程采用Binder IPC向system_server进程发起startActivity请求;
  2. system_server进程接收到请求后,向zygote进程发送创建进程的请求;
  3. Zygote进程fork出新的子进程,即App进程;
  4. App进程,通过Binder IPC向sytem_server进程发起attachApplication请求;
  5. system_server进程在收到请求后,进行一系列准备工作后,再通过binder IPC向App进程发送scheduleLaunchActivity请求;
  6. App进程的binder线程(ApplicationThread)在收到请求后,通过handler向主线程发送LAUNCH_ACTIVITY消息;
  7. 主线程在收到Message后,通过发射机制创建目标Activity,并回调Activity.onCreate()等方法。

到此,App便正式启动,开始进入Activity生命周期,执行完onCreate/onStart/onResume方法,UI渲染结束后便可以看到App的主界面。 启动Activity较为复杂,后续计划再进一步讲解生命周期过程与系统是如何交互,以及UI渲染过程,敬请期待。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/680182
推荐阅读
相关标签
  

闽ICP备14008679号