当前位置:   article > 正文

Android 7.0 startActivity()源码解析以及对几个问题的思考:

startactivity assertmanager
一、本文需要解决的问题

本文并不是非常详细地解释startActivity()源码每行代码的具体作用(实际上也根本做不到),所以我省略了很多代码,只保留了最核心的代码。我研究这段源码的目的是为了解决以下几个我在开发应用的过程中所思考的问题:

  1. 是通过何种方式生成一个新的Activity类的,是通过java反射生成的吗?
  2. Activity的生命周期回调方法是通过哪个类调用的,在什么时候调用的?
  3. 界面的绘制是在执行Activity#onResume()之后还是之前?
  4. 在之前的学习中,我了解到应用程序的真正入口是ActivityThread类,那么ActivityThread#main()方法是在哪里调用的?
二、相关解析(基于Android 7.1源码)
  1. // 这里解析的是在已有进程中启动一个新Activity的情况
  2. Intent intent = new Intent(this, SubActivity.class);
  3. intent.startActivity();
  4. 复制代码

(1)Activity本地调用: Activity#startActivity()   --> Activity#startActivityForResult()

  1. @Override
  2. public void startActivityForResult(String who, Intent intent, int requestCode, @Nullable Bundle options) {
  3. // 省略代码
  4. Instrumentation.ActivityResult ar =
  5. mInstrumentation.execStartActivity(
  6. this, mMainThread.getApplicationThread(), mToken, who,
  7. intent, requestCode, options);
  8. // 省略代码
  9. }
  10. 复制代码

(2)Instrumentation#execStartActivity Instrumentation类相当于一个管家,它的职责是管理各个应用程序和系统的交互,Instrumentation将在任何应用程序运行前初始化,每个进程只会存在一个Instrumentation对象,且每个Activity都有此对象的实际引用,可以通过它监测系统与应用程序之间的所有交互。

  1. public ActivityResult execStartActivity(
  2. Context who, IBinder contextThread, IBinder token, Activity target,
  3. Intent intent, int requestCode, Bundle options) {
  4. // 省略代码
  5. int result = ActivityManagerNative.getDefault()
  6. .startActivity(whoThread, who.getBasePackageName(), intent,
  7. intent.resolveTypeIfNeeded(who.getContentResolver()),
  8. token, target != null ? target.mEmbeddedID : null,
  9. requestCode, 0, null, options);
  10. checkStartActivityResult(result, intent);
  11. // 省略代码
  12. }
  13. 复制代码

(3)ActivityManagerNative,ActivityManagerService,ActivityManagerProxy类之间的关系 ActivityManagerNative#getDefault()   --> ActivityManagerProxy#startActivity()

  1. public int startActivity(IApplicationThread caller, String callingPackage, Intent intent,
  2. String resolvedType, IBinder resultTo, String resultWho, int requestCode,
  3. 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. mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);
  28. reply.readException();
  29. int result = reply.readInt();
  30. reply.recycle();
  31. data.recycle();
  32. return result;
  33. }
  34. 复制代码

如果学过AIDL的话,对上面这段代码会比较熟悉,其实上面是发起了一次跨进程调用。这里涉及到一种设计模式叫作代理模式,这里不详细介绍这种设计模式,简单总结一下:

  • ActivityManagerProxy相当于Proxy
  • ActivityManagerNative就相当于Stub
  • ActivityManagerService是ActivityManagerNative的具体实现,换句话说,就是AMS才是服务端的具体实现!

(4)ActivityMangerService ActivityMangerService#startActivity()   --> ActivityMangerService#startActivityAsUser()

  1. @Override
  2. public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
  3. Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
  4. int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
  5. enforceNotIsolatedCaller("startActivity");
  6. userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
  7. userId, false, ALLOW_FULL_ONLY, "startActivity", null);
  8. // TODO: Switch to user app stacks here.
  9. return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
  10. resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
  11. profilerInfo, null, null, bOptions, false, userId, null, null);
  12. }
  13. 复制代码

(5)ActivityStarter ActivityStarter类的注释:

  1. /**
  2. * Controller for interpreting how and then launching activities.
  3. *
  4. * This class collects all the logic for determining how an intent and flags should be turned into
  5. * an activity and associated task and stack.
  6. */
  7. 复制代码

简单来说,ActivityStarter类主要负责处理Activity的Intent和Flags, 还有关联相关的Stack和TaskRecord ActivityStarter#startActivityMayWait()   --> ActivityStarter#startActivityLocked()     --> ActivityStarter#startActivityUnchecked()

其中: **startActivityMayWait():**获取Activity的启动信息,包括ResolveInfo和ActivityInfo,以及获取CallingPid和CallingUid; **startActivityLocked():**创建一个ActivityRecord; **startActivityUnchecked():**设置TaskRecord, 完成后执行ActivityStackSupervisor类的resumeFocusedStackTopActivityLocked方法

(6)ActivityStackSupervisor和ActivityStack ActivityStackSupervisor#resumeFocusedStackTopActivityLocked()   --> ActivityStackSupervisor#resumeTopActivityUncheckedLocked()     --> ActivityStack#resumeTopActivityInnerLocked()       --> ActivityStackSupervisor#startSpecificActivityLocked()

  1. void startSpecificActivityLocked(ActivityRecord r,
  2. boolean andResume, boolean checkConfig) {
  3. // Is this activity's application already running?
  4. ProcessRecord app = mService.getProcessRecordLocked(r.processName,
  5. r.info.applicationInfo.uid, true);
  6. r.task.stack.setLaunchTime(r);
  7. if (app != null && app.thread != null) {
  8. try {
  9. if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
  10. || !"android".equals(r.info.packageName)) {
  11. // Don't add this if it is a platform component that is marked
  12. // to run in multiple processes, because this is actually
  13. // part of the framework so doesn't make sense to track as a
  14. // separate apk in the process.
  15. app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
  16. mService.mProcessStats);
  17. }
  18. // !!!
  19. realStartActivityLocked(r, app, andResume, checkConfig);
  20. return;
  21. } catch (RemoteException e) {
  22. Slog.w(TAG, "Exception when starting activity "
  23. + r.intent.getComponent().flattenToShortString(), e);
  24. }
  25. // If a dead object exception was thrown -- fall through to
  26. // restart the application.
  27. }
  28. mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
  29. "activity", r.intent.getComponent(), false, false, true);
  30. }
  31. 复制代码

这里会判断进程是否存在,由于我们是在原有进程中启动一个新的activity,所以会调用 realStartActivityLocked()方法。 ActivityStackSupervisor#realStartActivityLocked()

  1. final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
  2. boolean andResume, boolean checkConfig) throws RemoteException {
  3. // 省略代码
  4. app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
  5. System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
  6. new Configuration(task.mOverrideConfig), r.compat, r.launchedFromPackage,
  7. task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results,
  8. newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo);
  9. }
  10. 复制代码

(7)关于IApplicationThread,ApplicationThreadProxy,ApplicationThreadNative,ApplicationThread 上述代码中,app.thread为IApplicationThread类型,继承了IInterface,我们查看IApplicationThread的直接实现ApplicationThreadNative ApplicationThreadNative#scheduleLaunchActivity()

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

同样的,这里也发起了一次跨进程调用。

  • ApplicationThreadProxy相当于Proxy
  • ApplicationThreadNative相当于Stub
  • ApplicationThread相当于服务器端,代码真正的实现者!

(8)ActivityThread.ApplicationThread类 ActivityThread.ApplicationThread#scheduleLaunchActivity

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

这里会调用sendMessage,最后调用到mH.sendMessage(msg); mH为H类的一个实例,H就是Handler的一个子类,发送消息之后,我们来查看H类的handleMessage()方法: 源码里面就是根据msg.what来执行对应的操作:

  1. case LAUNCH_ACTIVITY: {
  2. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
  3. final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
  4. r.packageInfo = getPackageInfoNoCheck(
  5. r.activityInfo.applicationInfo, r.compatInfo);
  6. handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
  7. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  8. }
  9. 复制代码

(9) ActivityThread#handleLaunchActivity()

  1. private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
  2. // If we are getting ready to gc after going to the background, well
  3. // we are back active so skip it.
  4. unscheduleGcIdler();
  5. mSomeActivitiesChanged = true;
  6. if (r.profilerInfo != null) {
  7. mProfiler.setProfiler(r.profilerInfo);
  8. mProfiler.startProfiling();
  9. }
  10. // Make sure we are running with the most recent config.
  11. handleConfigurationChanged(null, null);
  12. if (localLOGV) Slog.v(TAG, "Handling launch of " + r);
  13. // Initialize before creating the activity
  14. WindowManagerGlobal.initialize();
  15. // !!!
  16. Activity a = performLaunchActivity(r, customIntent);
  17. if (a != null) {
  18. r.createdConfig = new Configuration(mConfiguration);
  19. reportSizeConfigurations(r);
  20. Bundle oldState = r.state;
  21. handleResumeActivity(r.token, false, r.isForward,
  22. !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
  23. if (!r.activity.mFinished && r.startsNotResumed) {
  24. // The activity manager actually wants this one to start out paused, because it
  25. // needs to be visible but isn't in the foreground. We accomplish this by going
  26. // through the normal startup (because activities expect to go through onResume()
  27. // the first time they run, before their window is displayed), and then pausing it.
  28. // However, in this case we do -not- need to do the full pause cycle (of freezing
  29. // and such) because the activity manager assumes it can just retain the current
  30. // state it has.
  31. performPauseActivityIfNeeded(r, reason);
  32. // We need to keep around the original state, in case we need to be created again.
  33. // But we only do this for pre-Honeycomb apps, which always save their state when
  34. // pausing, so we can not have them save their state when restarting from a paused
  35. // state. For HC and later, we want to (and can) let the state be saved as the
  36. // normal part of stopping the activity.
  37. if (r.isPreHoneycomb()) {
  38. r.state = oldState;
  39. }
  40. }
  41. } else {
  42. // If there was an error, for any reason, tell the activity manager to stop us.
  43. try {
  44. ActivityManagerNative.getDefault()
  45. .finishActivity(r.token, Activity.RESULT_CANCELED, null,
  46. Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
  47. } catch (RemoteException ex) {
  48. throw ex.rethrowFromSystemServer();
  49. }
  50. }
  51. }
  52. 复制代码

这里会调用performLaunchActivity()方法。

(10)ActivityThread#performLaunchActivity()

  1. private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
  2. // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
  3. ActivityInfo aInfo = r.activityInfo;
  4. if (r.packageInfo == null) {
  5. r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
  6. Context.CONTEXT_INCLUDE_CODE);
  7. }
  8. ComponentName component = r.intent.getComponent();
  9. if (component == null) {
  10. component = r.intent.resolveActivity(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. if (!mInstrumentation.onException(activity, e)) {
  30. throw new RuntimeException(
  31. "Unable to instantiate activity " + component
  32. + ": " + e.toString(), e);
  33. }
  34. }
  35. try {
  36. Application app = r.packageInfo.makeApplication(false, mInstrumentation);
  37. if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
  38. if (localLOGV) Slog.v(
  39. TAG, r + ": app=" + app
  40. + ", appName=" + app.getPackageName()
  41. + ", pkg=" + r.packageInfo.getPackageName()
  42. + ", comp=" + r.intent.getComponent().toShortString()
  43. + ", dir=" + r.packageInfo.getAppDir());
  44. if (activity != null) {
  45. Context appContext = createBaseContextForActivity(r, activity);
  46. CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
  47. Configuration config = new Configuration(mCompatConfiguration);
  48. if (r.overrideConfig != null) {
  49. config.updateFrom(r.overrideConfig);
  50. }
  51. if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
  52. + r.activityInfo.name + " with config " + config);
  53. Window window = null;
  54. if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
  55. window = r.mPendingRemoveWindow;
  56. r.mPendingRemoveWindow = null;
  57. r.mPendingRemoveWindowManager = null;
  58. }
  59. activity.attach(appContext, this, getInstrumentation(), r.token,
  60. r.ident, app, r.intent, r.activityInfo, title, r.parent,
  61. r.embeddedID, r.lastNonConfigurationInstances, config,
  62. r.referrer, r.voiceInteractor, window);
  63. if (customIntent != null) {
  64. activity.mIntent = customIntent;
  65. }
  66. r.lastNonConfigurationInstances = null;
  67. activity.mStartedActivity = false;
  68. int theme = r.activityInfo.getThemeResource();
  69. if (theme != 0) {
  70. activity.setTheme(theme);
  71. }
  72. activity.mCalled = false;
  73. if (r.isPersistable()) {
  74. // 11.1
  75. mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
  76. } else {
  77. // 11.1
  78. mInstrumentation.callActivityOnCreate(activity, r.state);
  79. }
  80. if (!activity.mCalled) {
  81. throw new SuperNotCalledException(
  82. "Activity " + r.intent.getComponent().toShortString() +
  83. " did not call through to super.onCreate()");
  84. }
  85. r.activity = activity;
  86. r.stopped = true;
  87. if (!r.activity.mFinished) {
  88. // 11.2
  89. activity.performStart();
  90. r.stopped = false;
  91. }
  92. if (!r.activity.mFinished) {
  93. if (r.isPersistable()) {
  94. if (r.state != null || r.persistentState != null) {
  95. mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
  96. r.persistentState);
  97. }
  98. } else if (r.state != null) {
  99. mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
  100. }
  101. }
  102. if (!r.activity.mFinished) {
  103. activity.mCalled = false;
  104. if (r.isPersistable()) {
  105. mInstrumentation.callActivityOnPostCreate(activity, r.state,
  106. r.persistentState);
  107. } else {
  108. mInstrumentation.callActivityOnPostCreate(activity, r.state);
  109. }
  110. if (!activity.mCalled) {
  111. throw new SuperNotCalledException(
  112. "Activity " + r.intent.getComponent().toShortString() +
  113. " did not call through to super.onPostCreate()");
  114. }
  115. }
  116. }
  117. r.paused = true;
  118. mActivities.put(r.token, r);
  119. } catch (SuperNotCalledException e) {
  120. throw e;
  121. } catch (Exception e) {
  122. if (!mInstrumentation.onException(activity, e)) {
  123. throw new RuntimeException(
  124. "Unable to start activity " + component
  125. + ": " + e.toString(), e);
  126. }
  127. }
  128. return activity;
  129. }
  130. 复制代码

这里会收集要启动的Activity的相关信息,主要是package和component信息,然后通过ClassLoader将要启动的Activity类加载出来。

这里就解决了我的第一个问题:新的Activity类是通过类加载器方式即通过反射的方式生成的,我们可以看一下mInstrumentation.newActivity()方法:

  1. public Activity newActivity(ClassLoader cl, String className, Intent intent)
  2. throws InstantiationException, IllegalAccessException, ClassNotFoundException {
  3. return (Activity)cl.loadClass(className).newInstance();
  4. }
  5. 复制代码

最后调用mInstrumentation.callActivityOnCreate()

(11) 11.1 Instrumentation#callActivityOnCreate()

  1. public void callActivityOnCreate(Activity activity, Bundle icicle,
  2. PersistableBundle persistentState) {
  3. prePerformCreate(activity);
  4. activity.performCreate(icicle, persistentState);
  5. postPerformCreate(activity);
  6. }
  7. 复制代码

Activity#performCreate()

  1. final void performCreate(Bundle icicle, PersistableBundle persistentState) {
  2. restoreHasCurrentPermissionRequest(icicle);
  3. onCreate(icicle, persistentState);
  4. mActivityTransitionState.readState(icicle);
  5. performCreateCommon();
  6. }
  7. 复制代码

这里就会显式调用Activity的生命周期方法onCreate()!

11.2 Activity#performStart()

  1. final void performStart() {
  2. // 省略代码
  3. // !!!
  4. mInstrumentation.callActivityOnStart(this);
  5. // 省略代码
  6. }
  7. 复制代码

在mInstrumentation.callActivityOnStart(this)方法里面就会显式调用Activtiy的onStart()方法!

到这里我们也可以基本解决第二个问题:Activity的生命周期方法是通过Instrumentation类调用callActivityOnXXX方法最终调用Activity的onCreate等方法,调用时机为ActivityThread#performLaunchActivitiy()方法中。

那么还有一个问题,我们知道启动一个Activity,所经历的生命周期为onCreate() --> onStart() --> onResume() 那么onResume()方法在哪里调用的呢? 我们回到前面的ActivityThread#handleLaunchActivity():

  1. private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
  2. // 省略代码
  3. Activity a = performLaunchActivity(r, customIntent);
  4. if (a != null) {
  5. r.createdConfig = new Configuration(mConfiguration);
  6. reportSizeConfigurations(r);
  7. Bundle oldState = r.state;
  8. // !!!
  9. handleResumeActivity(r.token, false, r.isForward,
  10. !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
  11. // 省略代码
  12. }
  13. 复制代码

在我们调用performLaunchActivity之后返回新生成的Activity实例之后,接下来就会调用handleResumeActivity()方法 ActivityThread#handleResumeActivity()

  1. final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
  2. ActivityClientRecord r = mActivities.get(token);
  3. if (!checkAndUpdateLifecycleSeq(seq, r, "resumeActivity")) {
  4. return;
  5. }
  6. // If we are getting ready to gc after going to the background, well
  7. // we are back active so skip it.
  8. unscheduleGcIdler();
  9. mSomeActivitiesChanged = true;
  10. // TODO Push resumeArgs into the activity for consideration
  11. // !!!
  12. r = performResumeActivity(token, clearHide, reason);
  13. if (r != null) {
  14. final Activity a = r.activity;
  15. if (localLOGV) Slog.v(TAG, "Resume " + r + " started activity: " +
  16. a.mStartedActivity + ", hideForNow: " + r.hideForNow + ", finished: " + a.mFinished);
  17. final int forwardBit = isForward ? WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
  18. // If the window hasn't yet been added to the window manager,
  19. // and this guy didn't finish itself or start another activity,
  20. // then go ahead and add the window.
  21. boolean willBeVisible = !a.mStartedActivity;
  22. if (!willBeVisible) {
  23. try {
  24. willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible(a.getActivityToken());
  25. } catch (RemoteException e) {
  26. throw e.rethrowFromSystemServer();
  27. }
  28. }
  29. if (r.window == null && !a.mFinished && willBeVisible) {
  30. r.window = r.activity.getWindow();
  31. View decor = r.window.getDecorView();
  32. decor.setVisibility(View.INVISIBLE);
  33. ViewManager wm = a.getWindowManager();
  34. WindowManager.LayoutParams l = r.window.getAttributes();
  35. a.mDecor = decor;
  36. l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
  37. l.softInputMode |= forwardBit;
  38. if (r.mPreserveWindow) {
  39. a.mWindowAdded = true;
  40. r.mPreserveWindow = false;
  41. // Normally the ViewRoot sets up callbacks with the Activity
  42. // in addView->ViewRootImpl#setView. If we are instead reusing
  43. // the decor view we have to notify the view root that the
  44. // callbacks may have changed.
  45. ViewRootImpl impl = decor.getViewRootImpl();
  46. if (impl != null) {
  47. impl.notifyChildRebuilt();
  48. }
  49. }
  50. if (a.mVisibleFromClient && !a.mWindowAdded) {
  51. a.mWindowAdded = true;
  52. wm.addView(decor, l);
  53. }
  54. // If the window has already been added, but during resume
  55. // we started another activity, then don't yet make the
  56. // window visible.
  57. } else if (!willBeVisible) {
  58. if (localLOGV) Slog.v(TAG, "Launch " + r + " mStartedActivity set");
  59. r.hideForNow = true;
  60. }
  61. // Get rid of anything left hanging around.
  62. cleanUpPendingRemoveWindows(r, false /* force */ );
  63. // The window is now visible if it has been added, we are not
  64. // simply finishing, and we are not starting another activity.
  65. if (!r.activity.mFinished && willBeVisible && r.activity.mDecor != null && !r.hideForNow) {
  66. if (r.newConfig != null) {
  67. performConfigurationChangedForActivity(r, r.newConfig, REPORT_TO_ACTIVITY);
  68. if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity " + r.activityInfo.name +
  69. " with newConfig " + r.activity.mCurrentConfig);
  70. r.newConfig = null;
  71. }
  72. if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward=" + isForward);
  73. WindowManager.LayoutParams l = r.window.getAttributes();
  74. if ((l.softInputMode & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != forwardBit) {
  75. l.softInputMode = (l.softInputMode &
  76. (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
  77. | forwardBit;
  78. if (r.activity.mVisibleFromClient) {
  79. ViewManager wm = a.getWindowManager();
  80. View decor = r.window.getDecorView();
  81. wm.updateViewLayout(decor, l);
  82. }
  83. }
  84. r.activity.mVisibleFromServer = true;
  85. mNumVisibleActivities++;
  86. if (r.activity.mVisibleFromClient) {
  87. r.activity.makeVisible();
  88. }
  89. }
  90. if (!r.onlyLocalRequest) {
  91. r.nextIdle = mNewActivities;
  92. mNewActivities = r;
  93. if (localLOGV) Slog.v(TAG, "Scheduling idle handler for " + r);
  94. Looper.myQueue().addIdleHandler(new Idler());
  95. }
  96. r.onlyLocalRequest = false;
  97. // Tell the activity manager we have resumed.
  98. if (reallyResume) {
  99. try {
  100. ActivityManagerNative.getDefault().activityResumed(token);
  101. } catch (RemoteException ex) {
  102. throw ex.rethrowFromSystemServer();
  103. }
  104. }
  105. } else {
  106. // If an exception was thrown when trying to resume, then
  107. // just end this activity.
  108. try {
  109. ActivityManagerNative.getDefault().
  110. finishActivity(token, Activity.RESULT_CANCELED, null, Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
  111. } catch (RemoteException ex)
  112. throw ex.rethrowFromSystemServer();
  113. }
  114. }
  115. 复制代码

这里会调用: ActivityThread#performResumeActivity()   --> Activity#performResume()     --> Instrumentation#callActivityOnResume()       --> Activity#onResume() 另外,观察执行handleResumeActivity()之后的代码,会发现程序会开始获取DecorView,执行addView()方法,里面最终会调用到ViewRootImpl#performTraversals(),即开始绘制view界面! 这里我们就解决了第三个问题:界面的绘制是在执行Activity#onResume()之后!

三、关于第四个问题

那么我们还差第四个问题没有解决!为什么我们这个流程都没有涉及到调用main方法呢,是因为在一开始,我们分析的情况是在已有的App进程中启动一个新的Activity,而通过我们上文的分析,我们知道ActivityThread类才是应用的主线程类,一个app应用进程有且只有一个ActivityThread类,也就是我们一直说的应用程序主线程(UI线程)。所以,在分析源码时,我们已经假设ActivityThread类已经存在实例,所以不会再调用main方法。

那么什么情况下会调用到main方法呢,其实我们每次在手机的桌面点击一个应用图标打开应用时,其实是通由Launcher启动起来的。

(1)关于Launcher Launcher本身也是一个应用程序,其它的应用程序安装后,就会Launcher的界面上出现一个相应的图标,点击这个图标时,Launcher就会对应的应用程序启动起来。Launcher其实也是Activity的一个子类。

  1. public final class Launcher extends Activity
  2. implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks, AllAppsView.Watcher {
  3. ...
  4. }
  5. 复制代码

所以本质上也是调用了startActivity()方法启动一个新的Activity! 根据上述的流程,一直到ActivityStackSupervisor#startSpecificActivityLocked()这里,代码的调用流程就会开始发生变化! ActivityStackSupervisor#startSpecificActivityLocked()

  1. void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
  2. // Is this activity's application already running?
  3. ProcessRecord app = mService.getProcessRecordLocked(r.processName, 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 || !"android".equals(r.info.packageName)) {
  8. // Don't add this if it is a platform component that is marked
  9. // to run in multiple processes, because this is actually
  10. // part of the framework so doesn't make sense to track as a
  11. // separate apk in the process.
  12. app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode, mService.mProcessStats);
  13. }
  14. // !!!
  15. realStartActivityLocked(r, app, andResume, checkConfig);
  16. return;
  17. } catch (RemoteException e) {
  18. Slog.w(TAG, "Exception when starting activity " + r.intent.getComponent().flattenToShortString(), e);
  19. }
  20. // If a dead object exception was thrown -- fall through to
  21. // restart the application.
  22. }
  23. mService.startProcessLocked(r.processName, r.info.applicationInfo,
  24. true, 0, "activity", r.intent.getComponent(), false, false, true);
  25. }
  26. 复制代码

上文说过。这里会判断进程是否存在,而这次,app为空,所以会跳出if判断,直接到下面的mService.startProcessLocked()方法,这里的mService为ActivityManagerService类的一个实例! startProcessLocked()通过几次重载函数的调用,最终调用到这里:

  1. private final void startProcessLocked(ProcessRecord app, String hostingType, String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) {
  2. // 省略代码
  3. // Start the process. It will either succeed and return a result containing
  4. // the PID of the new process, or else throw a RuntimeException.
  5. boolean isActivityProcess = (entryPoint == null);
  6. if (entryPoint == null) entryPoint = "android.app.ActivityThread";
  7. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Start proc: " + app.processName);
  8. checkTime(startTime, "startProcess: asking zygote to start proc");
  9. // !!!
  10. Process.ProcessStartResult startResult = Process.start(entryPoint, app.processName, uid,
  11. uid, gids, debugFlags, mountExternal,
  12. app.info.targetSdkVersion, app.info.seinfo, requiredAbi, instructionSet,
  13. app.info.dataDir, entryPointArgs);
  14. // 省略代码
  15. }
  16. 复制代码

(2) Process#start()   --> Process#startViaZygote()

  1. private static ProcessStartResult startViaZygote(final String processClass,
  2. final String niceName,
  3. final int uid, final int gid,
  4. final int[] gids,
  5. int debugFlags, int mountExternal,
  6. int targetSdkVersion,
  7. String seInfo,
  8. String abi,
  9. String instructionSet,
  10. String appDataDir,
  11. String[] extraArgs)
  12. throws ZygoteStartFailedEx {
  13. ArrayList < String > argsForZygote = new ArrayList < String > ();
  14. // --runtime-args, --setuid=, --setgid=,
  15. // and --setgroups= must go first
  16. argsForZygote.add("--runtime-args");
  17. argsForZygote.add("--setuid=" + uid);
  18. argsForZygote.add("--setgid=" + gid);
  19. if ((debugFlags & Zygote.DEBUG_ENABLE_JNI_LOGGING) != 0) {
  20. argsForZygote.add("--enable-jni-logging");
  21. }
  22. if ((debugFlags & Zygote.DEBUG_ENABLE_SAFEMODE) != 0) {
  23. argsForZygote.add("--enable-safemode");
  24. }
  25. if ((debugFlags & Zygote.DEBUG_ENABLE_DEBUGGER) != 0) {
  26. argsForZygote.add("--enable-debugger");
  27. }
  28. if ((debugFlags & Zygote.DEBUG_ENABLE_CHECKJNI) != 0) {
  29. argsForZygote.add("--enable-checkjni");
  30. }
  31. if ((debugFlags & Zygote.DEBUG_GENERATE_DEBUG_INFO) != 0) {
  32. argsForZygote.add("--generate-debug-info");
  33. }
  34. if ((debugFlags & Zygote.DEBUG_ALWAYS_JIT) != 0) {
  35. argsForZygote.add("--always-jit");
  36. }
  37. if ((debugFlags & Zygote.DEBUG_NATIVE_DEBUGGABLE) != 0) {
  38. argsForZygote.add("--native-debuggable");
  39. }
  40. if ((debugFlags & Zygote.DEBUG_ENABLE_ASSERT) != 0) {
  41. argsForZygote.add("--enable-assert");
  42. }
  43. if (mountExternal == Zygote.MOUNT_EXTERNAL_DEFAULT) {
  44. argsForZygote.add("--mount-external-default");
  45. } else if (mountExternal == Zygote.MOUNT_EXTERNAL_READ) {
  46. argsForZygote.add("--mount-external-read");
  47. } else if (mountExternal == Zygote.MOUNT_EXTERNAL_WRITE) {
  48. argsForZygote.add("--mount-external-write");
  49. }
  50. argsForZygote.add("--target-sdk-version=" + targetSdkVersion);
  51. //TODO optionally enable debuger
  52. //argsForZygote.add("--enable-debugger");
  53. // --setgroups is a comma-separated list
  54. if (gids != null && gids.length > 0) {
  55. StringBuilder sb = new StringBuilder();
  56. sb.append("--setgroups=");
  57. int sz = gids.length;
  58. for (int i = 0; i < sz; i++) {
  59. if (i != 0) {
  60. sb.append(',');
  61. }
  62. sb.append(gids[i]);
  63. }
  64. argsForZygote.add(sb.toString());
  65. }
  66. if (niceName != null) {
  67. argsForZygote.add("--nice-name=" + niceName);
  68. }
  69. if (seInfo != null) {
  70. argsForZygote.add("--seinfo=" + seInfo);
  71. }
  72. if (instructionSet != null) {
  73. argsForZygote.add("--instruction-set=" + instructionSet);
  74. }
  75. if (appDataDir != null) {
  76. argsForZygote.add("--app-data-dir=" + appDataDir);
  77. }
  78. argsForZygote.add(processClass);
  79. if (extraArgs != null) {
  80. for (String arg: extraArgs) {
  81. argsForZygote.add(arg);
  82. }
  83. }
  84. return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);
  85. }
  86. 复制代码

上面方法中设置一些参数之后,调用最后的zygoteSendArgsAndGetResult(),方法的作用是向Zygote发送创建进程请求,内部与Zygote进行Socket通信。具体代码逻辑在ZygoteInit#runSelectLoop():

(3)ZygoteInit#runSelectLoop():

  1. private static void runSelectLoop(String abiList) throws MethodAndArgsCaller {
  2. ArrayList < FileDescriptor > fds = new ArrayList < FileDescriptor > ();
  3. ArrayList < ZygoteConnection > peers = new ArrayList < ZygoteConnection > ();
  4. fds.add(sServerSocket.getFileDescriptor());
  5. peers.add(null);
  6. while (true) {
  7. StructPollfd[] pollFds = new StructPollfd[fds.size()];
  8. for (int i = 0; i < pollFds.length; ++i) {
  9. pollFds[i] = new StructPollfd();
  10. pollFds[i].fd = fds.get(i);
  11. pollFds[i].events = (short) POLLIN;
  12. }
  13. try {
  14. Os.poll(pollFds, -1);
  15. } catch (ErrnoException ex) {
  16. throw new RuntimeException("poll failed", ex);
  17. }
  18. for (int i = pollFds.length - 1; i >= 0; --i) {
  19. if ((pollFds[i].revents & POLLIN) == 0) {
  20. continue;
  21. }
  22. if (i == 0) {
  23. ZygoteConnection newPeer = acceptCommandPeer(abiList);
  24. peers.add(newPeer);
  25. fds.add(newPeer.getFileDesciptor());
  26. } else {
  27. boolean done = peers.get(i).runOnce();
  28. if (done) {
  29. peers.remove(i);
  30. fds.remove(i);
  31. }
  32. }
  33. }
  34. }
  35. }
  36. 复制代码

上面方法当中,通过acceptCommandPeer()方法创建一个新的ZygoteConnection,调用runOnce()方法处理请求。 ZygoteConnection#runOnce():

  1. boolean runOnce() throws ZygoteInit.MethodAndArgsCaller {
  2. String args[];
  3. Arguments parsedArgs = null;
  4. FileDescriptor[] descriptors;
  5. try {
  6. // 读取参数
  7. args = readArgumentList();
  8. descriptors = mSocket.getAncillaryFileDescriptors();
  9. } catch (IOException ex) {
  10. Log.w(TAG, "IOException on command socket " + ex.getMessage());
  11. closeSocket();
  12. return true;
  13. }
  14. if (args == null) {
  15. // EOF reached.
  16. closeSocket();
  17. return true;
  18. }
  19. /** the stderr of the most recent request, if avail */
  20. PrintStream newStderr = null;
  21. if (descriptors != null && descriptors.length >= 3) {
  22. newStderr = new PrintStream(new FileOutputStream(descriptors[2]));
  23. }
  24. int pid = -1;
  25. FileDescriptor childPipeFd = null;
  26. FileDescriptor serverPipeFd = null;
  27. try {
  28. // 省略代码
  29. // !!!
  30. pid = Zygote.forkAndSpecialize(parsedArgs.uid,
  31. parsedArgs.gid,parsedArgs.gids,parsedArgs.debugFlags,
  32. rlimits, parsedArgs.mountExternal, parsedArgs.seInfo, parsedArgs.niceName,
  33. fdsToClose, parsedArgs.instructionSet, parsedArgs.appDataDir);
  34. } catch (ErrnoException ex) {
  35. logAndPrintError(newStderr, "Exception creating pipe", ex);
  36. } catch (IllegalArgumentException ex) {
  37. logAndPrintError(newStderr, "Invalid zygote arguments", ex);
  38. } catch (ZygoteSecurityException ex) {
  39. logAndPrintError(newStderr, "Zygote security policy prevents request: ", ex);
  40. }
  41. try {
  42. if (pid == 0) {
  43. // in child
  44. IoUtils.closeQuietly(serverPipeFd);
  45. serverPipeFd = null;
  46. // !!!
  47. handleChildProc(parsedArgs, descriptors, childPipeFd, newStderr);
  48. // should never get here, the child is expected to either
  49. // throw ZygoteInit.MethodAndArgsCaller or exec().
  50. return true;
  51. } else {
  52. // in parent...pid of < 0 means failure
  53. IoUtils.closeQuietly(childPipeFd);
  54. childPipeFd = null;
  55. return handleParentProc(pid, descriptors, serverPipeFd, parsedArgs);
  56. }
  57. } finally {
  58. IoUtils.closeQuietly(childPipeFd);
  59. IoUtils.closeQuietly(serverPipeFd);
  60. }
  61. }
  62. 复制代码

这里会调用Zygote.forkAndSpecialize()方法生成一个新的进程,如果生成成功,则pid的值为0,然后调用handleChildProc()方法:

  1. private void handleChildProc(Arguments parsedArgs,
  2. FileDescriptor[] descriptors, FileDescriptor pipeFd, PrintStream newStderr)
  3. throws ZygoteInit.MethodAndArgsCaller {
  4. /**
  5. * By the time we get here, the native code has closed the two actual Zygote
  6. * socket connections, and substituted /dev/null in their place. The LocalSocket
  7. * objects still need to be closed properly.
  8. */
  9. closeSocket();
  10. ZygoteInit.closeServerSocket();
  11. if (descriptors != null) {
  12. try {
  13. Os.dup2(descriptors[0], STDIN_FILENO);
  14. Os.dup2(descriptors[1], STDOUT_FILENO);
  15. Os.dup2(descriptors[2], STDERR_FILENO);
  16. for (FileDescriptor fd: descriptors) {
  17. IoUtils.closeQuietly(fd);
  18. }
  19. newStderr = System.err;
  20. } catch (ErrnoException ex) {
  21. Log.e(TAG, "Error reopening stdio", ex);
  22. }
  23. }
  24. if (parsedArgs.niceName != null) {
  25. Process.setArgV0(parsedArgs.niceName);
  26. }
  27. // End of the postFork event.
  28. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  29. if (parsedArgs.invokeWith != null) {
  30. WrapperInit.execApplication(parsedArgs.invokeWith,
  31. parsedArgs.niceName, parsedArgs.targetSdkVersion,
  32. VMRuntime.getCurrentInstructionSet(),
  33. pipeFd, parsedArgs.remainingArgs);
  34. } else {
  35. RuntimeInit.zygoteInit(parsedArgs.targetSdkVersion,
  36. parsedArgs.remainingArgs, null /* classLoader */);
  37. }
  38. }
  39. 复制代码

这里会根据invokeWith参数决定使用哪种执行方式,我们只要知道SystemServer和apk都是通过RuntimeInit类生成的即可。

(4)RuntimeInit#zygoteInit()

  1. public static final void zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)
  2. throws ZygoteInit.MethodAndArgsCaller {
  3. if (DEBUG) Slog.d(TAG, "RuntimeInit: Starting application from zygote");
  4. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "RuntimeInit");
  5. redirectLogStreams();
  6. commonInit();
  7. nativeZygoteInit();
  8. applicationInit(targetSdkVersion, argv, classLoader);
  9. }
  10. 复制代码

最后会调用applicationInit()方法:

  1. private static void applicationInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)
  2. throws ZygoteInit.MethodAndArgsCaller {
  3. // 省略代码
  4. // Remaining arguments are passed to the start class's static main
  5. invokeStaticMain(args.startClass, args.startArgs, classLoader);
  6. }
  7. 复制代码

最关键的就是invokeStaticMain()方法:

  1. private static void invokeStaticMain(String className, String[] argv, ClassLoader classLoader)
  2. throws ZygoteInit.MethodAndArgsCaller {
  3. Class<?> cl;
  4. try {
  5. cl = Class.forName(className, true, classLoader);
  6. } catch (ClassNotFoundException ex) {
  7. throw new RuntimeException(
  8. "Missing class when invoking static main " + className,
  9. ex);
  10. }
  11. Method m;
  12. try {
  13. m = cl.getMethod("main", new Class[] { String[].class });
  14. } catch (NoSuchMethodException ex) {
  15. throw new RuntimeException(
  16. "Missing static main on " + className, ex);
  17. } catch (SecurityException ex) {
  18. throw new RuntimeException(
  19. "Problem getting static main on " + className, ex);
  20. }
  21. int modifiers = m.getModifiers();
  22. if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
  23. throw new RuntimeException(
  24. "Main method is not public and static on " + className);
  25. }
  26. /*
  27. * This throw gets caught in ZygoteInit.main(), which responds
  28. * by invoking the exception's run() method. This arrangement
  29. * clears up all the stack frames that were required in setting
  30. * up the process.
  31. */
  32. throw new ZygoteInit.MethodAndArgsCaller(m, argv);
  33. }
  34. 复制代码

上述方法中,通过反射的方式获取main方法,最后抛出一个MethodAndArgsCaller,它继承于Exception,同时他也是实现了Runnable接口。看 throw new ZygoteInit.MethodAndArgsCaller()的代码注释我们可以知道,它会在ZygoteInit.main()方法中被捕获,执行run方法。

  1. public static class MethodAndArgsCaller extends Exception
  2. implements Runnable {
  3. /** method to call */
  4. private final Method mMethod;
  5. /** argument array */
  6. private final String[] mArgs;
  7. public MethodAndArgsCaller(Method method, String[] args) {
  8. mMethod = method;
  9. mArgs = args;
  10. }
  11. public void run() {
  12. try {
  13. mMethod.invoke(null, new Object[] { mArgs });
  14. } catch (IllegalAccessException ex) {
  15. throw new RuntimeException(ex);
  16. } catch (InvocationTargetException ex) {
  17. Throwable cause = ex.getCause();
  18. if (cause instanceof RuntimeException) {
  19. throw (RuntimeException) cause;
  20. } else if (cause instanceof Error) {
  21. throw (Error) cause;
  22. }
  23. throw new RuntimeException(ex);
  24. }
  25. }
  26. }
  27. 复制代码

我们可以知道,最终它将会调用ActivityThread类的main方法! 所以,我们解决了第四个问题,ActivityThread的main方法是在生成一个新的app进程过程中调用的,具体是通过与Zygote通信,之后通过RuntimeInit类采用反射的方式调用ActivityThread#main()方法,即生成app中的主线程(UI线程)!

这篇文章会同步到我的个人日志,如有问题,请大家踊跃提出,谢谢大家!

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

闽ICP备14008679号