接着上一篇继续去追踪Activity_B生命周期回调源代码。

 
      继续分析,在performPauseActivity方法中,回调了Activity的两个操作函数:

        一
个是用于保存状态的onSaveInstanceState(),还有一个就是onPause() 
,这里你应该了解onPause和onSaveInstanceState的调用顺序了,这里看来OnSaveInstanceState是先于onPause的调用的,可是打印的Log显示onSaveInstanceState在onPause之后,在onStop之前调用(不明确)。

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">


 
      最后r.state置为true。

 
      当 AmS通知当前Activity暂停后,AmS会马上返回,而在目标进程中则是发送一个暂停的消息,处理完该暂停消息后,目标进程会调用AmS的 activityPaused(),报 告 AMS自己已经暂停完成,然后运行ActivityManagerNative.getDefault().activityPaused(token)

从而AMS将開始启动真正的Activity。

 
      前面说过。ActivityManagerNative.getDefault().activityPaused的动作运行者是ActivityManagerService.activityPaused

        ActivityManagerService.class
  1. public final void activityPaused(IBinder token) {
  2. final long origId = Binder.clearCallingIdentity();
  3. synchronized(this) {
  4. ActivityStack stack = ActivityRecord.getStackLocked(token);
  5. if (stack != null) {
  6. stack.activityPausedLocked(token, false);
  7. }
  8. }
  9. Binder.restoreCallingIdentity(origId);
  10. }

ActivityStack.class

  1. final void activityPausedLocked(IBinder token, boolean timeout) {
  2. if (DEBUG_PAUSE) Slog.v(
  3. TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
  4.  
  5. final ActivityRecord r = isInStackLocked(token);
  6. if (r != null) {
  7. mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
  8. if (mPausingActivity == r) {
  9. if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r
  10. + (timeout ?
  11.  
  12. " (due to timeout)" : " (pause complete)"));
  13. completePauseLocked(true);
  14. } else {
  15. EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
  16. r.userId, System.identityHashCode(r), r.shortComponentName,
  17. mPausingActivity != null
  18. ? mPausingActivity.shortComponentName : "(none)");
  19. }
  20. }
  21. }

ActivityStack.class

  1. private void completePauseLocked(boolean resumeNext) {
  2. ActivityRecord prev = mPausingActivity;
  3. if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
  4.  
  5. if (prev != null) {
  6. //...
  7. }
  8.  
  9. if (resumeNext) {
  10. final ActivityStack topStack = mStackSupervisor.getFocusedStack();
  11. if (!mService.isSleepingOrShuttingDown()) {
  12. mStackSupervisor.resumeTopActivitiesLocked(topStack, prev, null);
  13. } else {
  14. mStackSupervisor.checkReadyForSleepLocked();
  15. ActivityRecord top = topStack.topRunningActivityLocked(null);
  16. if (top == null || (prev != null && top != prev)) {
  17. // If there are no more activities available to run,
  18. // do resume anyway to start something. Also if the top
  19. // activity on the stack is not the just paused activity,
  20. // we need to go ahead and resume it to ensure we complete
  21. // an in-flight app switch.
  22. mStackSupervisor.resumeTopActivitiesLocked(topStack, null, null);
  23. }
  24. }
  25. }
  26.  
  27. if (prev != null) {
  28. //...
  29. }
  30.  
  31. // Notfiy when the task stack has changed
  32. mService.notifyTaskStackChangedLocked();
  33. }

ActivityStackSupervisor.class

  1. boolean resumeTopActivitiesLocked(ActivityStack targetStack, ActivityRecord target,
  2. Bundle targetOptions) {
  3. if (targetStack == null) {
  4. targetStack = getFocusedStack();
  5. }
  6. // Do targetStack first.
  7. boolean result = false;
  8. if (isFrontStack(targetStack)) {
  9. result = targetStack.resumeTopActivityLocked(target, targetOptions);
  10. }
  11. for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
  12. final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
  13. for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
  14. final ActivityStack stack = stacks.get(stackNdx);
  15. if (stack == targetStack) {
  16. // Already started above.
  17. continue;
  18. }
  19. if (isFrontStack(stack)) {
  20. //调用 ActivityStack.resumeTopActivityLocked(null)方法正式启动目标Activity
  21. stack.resumeTopActivityLocked(null);
  22. }
  23. }
  24. }
  25. return result;
  26. }

ActivityStack.class

  1. final boolean resumeTopActivityLocked(ActivityRecord prev) {
  2. return resumeTopActivityLocked(prev, null);
  3. }
  4.  
  5. final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
  6. if (mStackSupervisor.inResumeTopActivity) {
  7. // Don't even start recursing.
  8. return false;
  9. }
  10.  
  11. boolean result = false;
  12. try {
  13. // Protect against recursion.
  14. mStackSupervisor.inResumeTopActivity = true;
  15. if (mService.mLockScreenShown == ActivityManagerService.LOCK_SCREEN_LEAVING) {
  16. mService.mLockScreenShown = ActivityManagerService.LOCK_SCREEN_HIDDEN;
  17. mService.updateSleepIfNeededLocked();
  18. }
  19. result = resumeTopActivityInnerLocked(prev, options);
  20. } finally {
  21. mStackSupervisor.inResumeTopActivity = false;
  22. }
  23. return result;
  24. }

ActivityStack.class

  1. final boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) {
  2. if (ActivityManagerService.DEBUG_LOCKSCREEN) mService.logLockScreen("");
  3. //...
  4. if (next == null) {
  5. //...
  6. }
  7.  
  8. // If the top activity is the resumed one, nothing to do.
  9. if (mResumedActivity == next && next.state == ActivityState.RESUMED &&
  10. mStackSupervisor.allResumedActivitiesComplete()) {
  11. //...
  12. }
  13.  
  14. final TaskRecord nextTask = next.task;
  15. if (prevTask != null && prevTask.stack == this &&
  16. prevTask.isOverHomeStack() && prev.finishing && prev.frontOfTask) {
  17. //...
  18. }
  19. //...
  20. ActivityStack lastStack = mStackSupervisor.getLastStack();
  21. if (next.app != null && next.app.thread != null) {
  22. //...
  23.  
  24. } else {
  25. // Whoops, need to restart this activity!
  26. if (!next.hasBeenLaunched) {
  27. next.hasBeenLaunched = true;
  28. } else {
  29. //...
  30. }
  31. if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Restarting " + next);
  32. mStackSupervisor.startSpecificActivityLocked(next, true, true);
  33. }
  34.  
  35. if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
  36. return true;
  37. }

假设上面不能直接resume已有的Activity对象。那么接下来就要推断目标Activity相应的进程是否存在。

        ActivityStackSupervisor.class

  1. void startSpecificActivityLocked(ActivityRecord r,
  2. boolean andResume, boolean checkConfig) {
  3. // Is this activity's application already running?
  4. ////获取目标Activity相应的进程对象ProcessRecord app
  5. ProcessRecord app = mService.getProcessRecordLocked(r.processName,
  6. r.info.applicationInfo.uid, true);
  7.  
  8. r.task.stack.setLaunchTime(r);
  9. //假设目标Activity所在的app进程已经开启,比方说直接从Activity_A打开Activity_B
  10. if (app != null && app.thread != null) {
  11. try {
  12. if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
  13. || !"android".equals(r.info.packageName)) {
  14. // Don't add this if it is a platform component that is marked
  15. // to run in multiple processes, because this is actually
  16. // part of the framework so doesn't make sense to track as a
  17. // separate apk in the process.
  18. app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
  19. mService.mProcessStats);
  20. }
  21. realStartActivityLocked(r, app, andResume, checkConfig);
  22. //注意:在这里return了
  23. return;
  24. } catch (RemoteException e) {
  25. Slog.w(TAG, "Exception when starting activity "
  26. + r.intent.getComponent().flattenToShortString(), e);
  27. }
  28.  
  29. // If a dead object exception was thrown -- fall through to
  30. // restart the application.
  31. }
  32. //假设目标Activity所在的app进程还未开启,假设是从Launcher启动一个新的APP,则会调用此句(不会运行上面的if)
  33. mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
  34. "activity", r.intent.getComponent(), false, false, true);
  35. }

Activity_A打开Activity_B会运行if (app != null && app.thread != null) 中的realStartActivityLocked(r,
app, andResume, checkConfig),由于已经目标Activity相应的进程已经开启了,事实上启动目标进程之后(mService.startProcessLocked)。还是会调用realStartActivityLocked,这里也顺便去看一看是怎么启动目标进程的。

 
      追踪ActivityManagerService.startProcessLocked,发现它会一步一步调用其重载函数(不贴代码了),最后调用关键的
Process.start(entryPoint,

                    app.processName, uid, uid, gids, debugFlags, mountExternal,

                    app.info.targetSdkVersion, app.info.seinfo, requiredAbi, instructionSet,

                    app.info.dataDir, entryPointArgs);
 
      通过Process.start启动一个新的应用进程,而且应用进程会从ActivityThread类 的 main()方法中開始运行。转了一圈,又回到了ActivityThread(上面说过:ActivityThread,该类为应用程序的主线程类,全部的APK程序都有且仅有一个ActivityThread类 ,程序的入口为该类中的static
main()函数)。
 
      ActivityThread.class
  1. public static void main(String[] args) {
  2. SamplingProfilerIntegration.start();
  3. Looper.prepareMainLooper();
  4. ActivityThread thread = new ActivityThread();
  5. thread.attach(false);
  6. //...
  7. Looper.loop();
  8. //...
  9. }

调用prepareMainLooper()在 U I线程创建一个消息队列(MessageQueue)。Looper.loop()让消息循环。

 
      H (Handler)和ApplicationThread则是在ActivityThread的初始化的时候创建的
  1. final ApplicationThread mAppThread = new ApplicationThread();
  2. final Looper mLooper = Looper.myLooper();
  3. final H mH = new H();

前面说过,ApplicationThread它是一个Binder对象,负责接收远程AmS的 IPC 调用,接收到调用后。则通
过Handler把消息发送到消息队列,U I主线程会异步地从消息队列中取出消息并运行对应操作。比方
start、 stop、pause 等 。

 
      跟踪main方法中的thread.attach(false)
  1. private void attach(boolean system) {
  2. sCurrentActivityThread = this;
  3. mSystemThread = system;
  4. if (!system) {
  5. //...
  6. try {
  7. mgr.attachApplication(mAppThread);
  8. } catch (RemoteException ex) {
  9. // Ignore
  10. }
  11. //...
  12. } else {
  13. //...
  14. }
  15.  
  16. //...
  17. ViewRootImpl.addConfigCallback(new ComponentCallbacks2() {
  18. //...
  19. });
  20. }

能够看到,这里 mgr.attachApplication(mAppThread)把ActivityThread初始化时创建的mAppThread作为參数传递过去

        再耐心地继续跟踪:

        ActivityManagerService.class

  1. @Override
  2. public final void attachApplication(IApplicationThread thread) {
  3. synchronized (this) {
  4. int callingPid = Binder.getCallingPid();
  5. final long origId = Binder.clearCallingIdentity();
  6. attachApplicationLocked(thread, callingPid);
  7. Binder.restoreCallingIdentity(origId);
  8. }
  9. }

ActivityManagerService.class

  1. private final boolean attachApplicationLocked(IApplicationThread thread,
  2. int pid) {
  3.  
  4. // Find the application record that is being attached... either via
  5. // the pid if we are running in multiple processes, or just pull the
  6. // next app record if we are emulating process with anonymous threads.
  7. ProcessRecord app;
  8. if (pid != MY_PID && pid >= 0) {
  9. synchronized (mPidsSelfLocked) {
  10. app = mPidsSelfLocked.get(pid);
  11. }
  12. } else {
  13. app = null;
  14. }
  15.  
  16. if (app == null) {
  17. //...
  18. return false;
  19. }
  20.  
  21. //...
  22.  
  23. if (localLOGV) Slog.v(
  24. TAG, "New app record " + app
  25. + " thread=" + thread.asBinder() + " pid=" + pid);
  26. try {
  27. //...
  28. //通过thread.bindApplication调用ActivityThread.handleBindApplication,Binder机制
  29. thread.bindApplication(processName, appInfo, providers, app.instrumentationClass,
  30. profilerInfo, app.instrumentationArguments, app.instrumentationWatcher,
  31. app.instrumentationUiAutomationConnection, testMode, enableOpenGlTrace,
  32. isRestrictedBackupMode || !normalMode, app.persistent,
  33. new Configuration(mConfiguration), app.compat,
  34. getCommonServicesLocked(app.isolated),
  35. mCoreSettingsObserver.getCoreSettingsLocked());
  36. updateLruProcessLocked(app, false, null);
  37. app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
  38. } catch (Exception e) {
  39. //...
  40. return false;
  41. }
  42. //...
  43. // See if the top visible activity is waiting to run in this process...
  44. if (normalMode) {
  45. try {
  46. if (mStackSupervisor.attachApplicationLocked(app)) {
  47. didSomething = true;
  48. }
  49. } catch (Exception e) {
  50. Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
  51. badApp = true;
  52. }
  53. }
  54. //...
  55. return true;
  56. }

通过thread.bindApplication调用ActivityThread.handleBindApplication,Binder机制

 
      ActivityThread.class
  1. private void handleBindApplication(AppBindData data) {
  2. mBoundApplication = data;
  3. mConfiguration = new Configuration(data.config);
  4. mCompatConfiguration = new Configuration(data.config);
  5.  
  6. //...
  7.  
  8. if (data.instrumentationName != null) {
  9. InstrumentationInfo ii = null;
  10. try {
  11. ii = appContext.getPackageManager().
  12. getInstrumentationInfo(data.instrumentationName, 0);
  13. } catch (PackageManager.NameNotFoundException e) {
  14. }
  15. if (ii == null) {
  16. throw new RuntimeException(
  17. "Unable to find instrumentation info for: "
  18. + data.instrumentationName);
  19. }
  20.  
  21. mInstrumentationPackageName = ii.packageName;
  22. mInstrumentationAppDir = ii.sourceDir;
  23. mInstrumentationSplitAppDirs = ii.splitSourceDirs;
  24. mInstrumentationLibDir = ii.nativeLibraryDir;
  25. mInstrumentedAppDir = data.info.getAppDir();
  26. mInstrumentedSplitAppDirs = data.info.getSplitAppDirs();
  27. mInstrumentedLibDir = data.info.getLibDir();
  28.  
  29. ApplicationInfo instrApp = new ApplicationInfo();
  30. instrApp.packageName = ii.packageName;
  31. instrApp.sourceDir = ii.sourceDir;
  32. instrApp.publicSourceDir = ii.publicSourceDir;
  33. instrApp.splitSourceDirs = ii.splitSourceDirs;
  34. instrApp.splitPublicSourceDirs = ii.splitPublicSourceDirs;
  35. instrApp.dataDir = ii.dataDir;
  36. instrApp.nativeLibraryDir = ii.nativeLibraryDir;
  37. LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
  38. appContext.getClassLoader(), false, true, false);
  39. ContextImpl instrContext = ContextImpl.createAppContext(this, pi);
  40.  
  41. try {
  42. java.lang.ClassLoader cl = instrContext.getClassLoader();
  43. //Instrumentation的初始化,一个应用程序中仅仅有一个Instrumentation对象,每一个Activity内部都有一个该对象的引用,初始化完毕之后。帮助管理Activity生命周期的回调。
  44. mInstrumentation = (Instrumentation)
  45. cl.loadClass(data.instrumentationName.getClassName()).newInstance();
  46. } catch (Exception e) {
  47. throw new RuntimeException(
  48. "Unable to instantiate instrumentation "
  49. + data.instrumentationName + ": " + e.toString(), e);
  50. }
  51.  
  52. mInstrumentation.init(this, instrContext, appContext,
  53. new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher,
  54. data.instrumentationUiAutomationConnection);
  55. //...
  56.  
  57. } else {
  58. mInstrumentation = new Instrumentation();
  59. }
  60.  
  61. if ((data.appInfo.flags&ApplicationInfo.FLAG_LARGE_HEAP) != 0) {
  62. dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
  63. }
  64.  
  65. // Allow disk access during application and provider setup. This could
  66. // block processing ordered broadcasts, but later processing would
  67. // probably end up doing the same disk access.
  68. final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskWrites();
  69. try {
  70. //...
  71.  
  72. // Do this after providers, since instrumentation tests generally start their
  73. // test thread at this point, and we don't want that racing.
  74. try {
  75. //App
  76. mInstrumentation.onCreate(data.instrumentationArgs);
  77. }
  78. catch (Exception e) {
  79. throw new RuntimeException(
  80. "Exception thrown in onCreate() of "
  81. + data.instrumentationName + ": " + e.toString(), e);
  82. }
  83.  
  84. try {
  85. //回调Application的onCreate方法
  86. mInstrumentation.callApplicationOnCreate(app);
  87. } catch (Exception e) {
  88. if (!mInstrumentation.onException(app, e)) {
  89. throw new RuntimeException(
  90. "Unable to create application " + app.getClass().getName()
  91. + ": " + e.toString(), e);
  92. }
  93. }
  94. } finally {
  95. StrictMode.setThreadPolicy(savedPolicy);
  96. }
  97. }
 
      前面提到的Instrumentation就是在里面初始化的。初始化完毕之后,帮助管理Activity生命周期的回调。

 
      再接着分析ActivityManagerService.attachApplicationLocked方法中的mStackSupervisor.attachApplicationLocked(app)
  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. ActivityRecord hr = stack.topRunningActivityLocked(null);
  12. if (hr != null) {
  13. if (hr.app == null && app.uid == hr.info.applicationInfo.uid
  14. && processName.equals(hr.processName)) {
  15. try {
  16. //调用了realStartActivityLocked
  17. if (realStartActivityLocked(hr, app, true, true)) {
  18. didSomething = true;
  19. }
  20. } catch (RemoteException e) {
  21. Slog.w(TAG, "Exception in new application when starting activity "
  22. + hr.intent.getComponent().flattenToShortString(), e);
  23. throw e;
  24. }
  25. }
  26. }
  27. }
  28. }
  29. if (!didSomething) {
  30. ensureActivitiesVisibleLocked(null, 0);
  31. }
  32. return didSomething;
  33. }

看到没有,这里仍然调用了realStartActivityLocked。再反复一下:

假设目标进程还处于活动状态,所以仅仅须要让目标进程再创建一个指定Activity的对象并运行之就可以,调用realStartActivityLocked,否则。假设目标进程还不存在,则须要首先启动目标进程。最后还是要调用realStartActivityLocked

 
      还是得继续追踪ActivityStackSupervisor中的realStartActivityLocked
 
      ActivityStackSupervisor.class
  1. final boolean realStartActivityLocked(ActivityRecord r,
  2. ProcessRecord app, boolean andResume, boolean checkConfig)
  3. throws RemoteException {
  4.  
  5. r.startFreezingScreenLocked(app, 0);
  6. if (false) Slog.d(TAG, "realStartActivity: setting app visibility true");
  7. //setAppVisibility(true/false), 其作 用 是 告 诉WMS指定的窗体能否够被显示,这里为true。表示能够被显示
  8. mWindowManager.setAppVisibility(r.appToken, true);
  9. //...
  10. try {
  11. //...
  12. app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_TOP);
  13. //调用ApplicationThread.scheduleLaunchActivity
  14. app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
  15. System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
  16. r.compat, r.launchedFromPackage, r.task.voiceInteractor, app.repProcState,
  17. r.icicle, r.persistentState, results, newIntents, !andResume,
  18. mService.isNextTransitionForward(), profilerInfo);
  19.  
  20. if ((app.info.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
  21. //...
  22. }
  23.  
  24. } catch (RemoteException e) {
  25. if (r.launchFailed) {
  26. // This is the second time we failed -- finish activity
  27. // and give up.
  28. Slog.e(TAG, "Second failure launching "
  29. + r.intent.getComponent().flattenToShortString()
  30. + ", giving up", e);
  31. mService.appDiedLocked(app);
  32. stack.requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
  33. "2nd-crash", false);
  34. return false;
  35. }
  36.  
  37. // This is the first time we failed -- restart process and
  38. // retry.
  39. app.activities.remove(r);
  40. throw e;
  41. }
  42.  
  43. //...
  44.  
  45. // Launch the new version setup screen if needed. We do this -after-
  46. // launching the initial activity (that is, home), so that it can have
  47. // a chance to initialize itself while in the background, making the
  48. // switch back to it faster and look better.
  49. if (isFrontStack(stack)) {
  50. mService.startSetupActivityLocked();
  51. }
  52.  
  53. // Update any services we are bound to that might care about whether
  54. // their client may have activities.
  55. mService.mServices.updateServiceConnectionActivitiesLocked(r.app);
  56.  
  57. return true;
  58. }

setAppVisibility(true/false), 其作 用是告诉WMS指定的窗体能否够被显示,这里为true,表示能够被显示。

 
      继续追踪ApplicationThread.scheduleLaunchActivity。还记得前面调用过ApplicationThread.schedulePauseActivity吧。
 
      ApplicationThread.class
  1. public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
  2. ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,
  3. String referrer, IVoiceInteractor voiceInteractor, int procState, Bundle state,
  4. PersistableBundle persistentState, List<ResultInfo> pendingResults,
  5. List<ReferrerIntent> pendingNewIntents, boolean notResumed, boolean isForward,
  6. ProfilerInfo profilerInfo) {
  7.  
  8. updateProcessState(procState, false);
  9.  
  10. ActivityClientRecord r = new ActivityClientRecord();
  11.  
  12. r.token = token;
  13. r.ident = ident;
  14. r.intent = intent;
  15. r.referrer = referrer;
  16. r.voiceInteractor = voiceInteractor;
  17. r.activityInfo = info;
  18. r.compatInfo = compatInfo;
  19. r.state = state;
  20. r.persistentState = persistentState;
  21.  
  22. r.pendingResults = pendingResults;
  23. r.pendingIntents = pendingNewIntents;
  24.  
  25. r.startsNotResumed = notResumed;
  26. r.isForward = isForward;
  27.  
  28. r.profilerInfo = profilerInfo;
  29.  
  30. updatePendingConfiguration(curConfig);
  31.  
  32. sendMessage(H.LAUNCH_ACTIVITY, r);
  33. }

说明:scheduleLaunchActivity()方 法依据參数构造出一个本地ActivityRecord数据类 ,ActivityThread内部会为每个Activity创
建 一 个 ActivityRecord对象,并使用这些数据对象来管理Activity。

        最后通过
sendMessage(H.LAUNCH_ACTIVITY, r)去掉用handleLaunchActivity()。在handleLaunchActivity里面再调用到
performLaunchActivity()和 handleResumeActivity()

        H类前面已经解释过了,再来看看 handleLaunchActivity

 
      ActivityThread.class
  1. private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
  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.  
  7. if (r.profilerInfo != null) {
  8. mProfiler.setProfiler(r.profilerInfo);
  9. mProfiler.startProfiling();
  10. }
  11.  
  12. // Make sure we are running with the most recent config.
  13. handleConfigurationChanged(null, null);
  14.  
  15. if (localLOGV) Slog.v(
  16. TAG, "Handling launch of " + r);
  17.  
  18. // Initialize before creating the activity
  19. WindowManagerGlobal.initialize();
  20. //得到一个Activity实例,在里面会运行onCreate方法
  21. Activity a = performLaunchActivity(r, customIntent);
  22.  
  23. if (a != null) {
  24. r.createdConfig = new Configuration(mConfiguration);
  25. Bundle oldState = r.state;
  26. // 调用目标activity的onResume,追踪源代码会发现 目标activity的onStart在里面会先于onResume调用
  27. handleResumeActivity(r.token, false, r.isForward,
  28. !r.activity.mFinished && !r.startsNotResumed);
  29.  
  30. if (!r.activity.mFinished && r.startsNotResumed) {
  31. // The activity manager actually wants this one to start out
  32. // paused, because it needs to be visible but isn't in the
  33. // foreground. We accomplish this by going through the
  34. // normal startup (because activities expect to go through
  35. // onResume() the first time they run, before their window
  36. // is displayed), and then pausing it. However, in this case
  37. // we do -not- need to do the full pause cycle (of freezing
  38. // and such) because the activity manager assumes it can just
  39. // retain the current state it has.
  40. try {
  41. r.activity.mCalled = false;
  42. //这里再次去居然再次调用了callActivityOnPause?事实上在前面的performPauseActivity方法中已经调用了此方法,Activity_A已经运行了OnPause
  43. mInstrumentation.callActivityOnPause(r.activity);
  44. // We need to keep around the original state, in case
  45. // we need to be created again. But we only do this
  46. // for pre-Honeycomb apps, which always save their state
  47. // when pausing, so we can not have them save their state
  48. // when restarting from a paused state. For HC and later,
  49. // we want to (and can) let the state be saved as the normal
  50. // part of stopping the activity.
  51. if (r.isPreHoneycomb()) {
  52. r.state = oldState;
  53. }
  54. if (!r.activity.mCalled) {
  55. throw new SuperNotCalledException(
  56. "Activity " + r.intent.getComponent().toShortString() +
  57. " did not call through to super.onPause()");
  58. }
  59.  
  60. } catch (SuperNotCalledException e) {
  61. throw e;
  62.  
  63. } catch (Exception e) {
  64. if (!mInstrumentation.onException(r.activity, e)) {
  65. throw new RuntimeException(
  66. "Unable to pause activity "
  67. + r.intent.getComponent().toShortString()
  68. + ": " + e.toString(), e);
  69. }
  70. }
  71. r.paused = true;
  72. }
  73. } else {
  74. // If there was an error, for any reason, tell the activity
  75. // manager to stop us.
  76. try {
  77. ActivityManagerNative.getDefault()
  78. .finishActivity(r.token, Activity.RESULT_CANCELED, null, false);
  79. } catch (RemoteException ex) {
  80. // Ignore
  81. }
  82. }
  83. }

继续追踪performLaunchActivity

 
      ActivityThread.class
  1. private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
  2. // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
  3. //...
  4. Activity activity = null;
  5. try {
  6. java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
  7. activity = mInstrumentation.newActivity(
  8. cl, component.getClassName(), r.intent);
  9. StrictMode.incrementExpectedActivityCount(activity.getClass());
  10. r.intent.setExtrasClassLoader(cl);
  11. r.intent.prepareToEnterProcess();
  12. if (r.state != null) {
  13. r.state.setClassLoader(cl);
  14. }
  15. } catch (Exception e) {
  16. if (!mInstrumentation.onException(activity, e)) {
  17. throw new RuntimeException(
  18. "Unable to instantiate activity " + component
  19. + ": " + e.toString(), e);
  20. }
  21. }
  22.  
  23. try {
  24. Application app = r.packageInfo.makeApplication(false, mInstrumentation);
  25. //...
  26. if (activity != null) {
  27. //...
  28. //在这里最终開始调用目标Activity的OnCreate方法了
  29. if (r.isPersistable()) {
  30. mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
  31. } else {
  32. mInstrumentation.callActivityOnCreate(activity, r.state);
  33. }
  34. //...
  35. if (!r.activity.mFinished) {
  36. //这里调用Activity_B的nRestoreInstanceState方法,获取保存在Bundle中的信息
  37. if (r.isPersistable()) {
  38. if (r.state != null || r.persistentState != null) {
  39. mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
  40. r.persistentState);
  41. }
  42. } else if (r.state != null) {
  43. mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
  44. }
  45. }
  46. //...
  47. }
  48. //...
  49.  
  50. } catch (SuperNotCalledException e) {
  51. throw e;
  52.  
  53. } catch (Exception e) {
  54. //...
  55. }
  56.  
  57. return activity;
  58. }

Instrumentation.callActivityOnCreate会调用activity.performCreate(icicle, persistentState),activity.performCreate又会其调用onCreate方法(不贴代码了)。

 
      到这里。Activity_B已经运行了onCreate方法,已经走完了Activity_A的onPause-->Activity_B的onCreate生命周期回调的流程。

 
      performLaunchActivity()方法返回后。运行ActivityThread.handleResumeActivity 
 
      ActivityThread.class
  1. final void handleResumeActivity(IBinder token,
  2. boolean clearHide, boolean isForward, boolean reallyResume) {
  3. // If we are getting ready to gc after going to the background, well
  4. // we are back active so skip it.
  5. unscheduleGcIdler();
  6. mSomeActivitiesChanged = true;
  7.  
  8. // TODO Push resumeArgs into the activity for consideration
  9. //在performResumeActivity里面调用了目标Activity_B的 onStart和onResume()方法。后面会追踪源代码
  10. ActivityClientRecord r = performResumeActivity(token, clearHide);
  11.  
  12. if (r != null) {
  13. final Activity a = r.activity;
  14. //...
  15.  
  16. if (!r.activity.mFinished && willBeVisible
  17. && r.activity.mDecor != null && !r.hideForNow) {
  18. //...
  19. if (r.activity.mVisibleFromClient) {
  20. //过r.activity.makeVisible()调用目标Activity_B的 makeVisible()函数,该函数其内部又会辗转和WmS进行各种调用,并终于导致Activity包括 的DecorView显示到屏幕上
  21. r.activity.makeVisible();
  22. }
  23. }
  24.  
  25. if (!r.onlyLocalRequest) {
  26. r.nextIdle = mNewActivities;
  27. mNewActivities = r;
  28. if (localLOGV) Slog.v(
  29. TAG, "Scheduling idle handler for " + r);
  30. //创建一个Idler对象,并加入到线程消息队列中,
  31. Looper.myQueue().addIdleHandler(new Idler());
  32. }
  33. //...
  34.  
  35. } else {
  36. //...
  37. }
  38. }
 
      追踪performResumeActivity
 
      ActivityThread.class
  1. public final ActivityClientRecord performResumeActivity(IBinder token,
  2. boolean clearHide) {
  3. ActivityClientRecord r = mActivities.get(token);
  4. if (localLOGV) Slog.v(TAG, "Performing resume of " + r
  5. + " finished=" + r.activity.mFinished);
  6. if (r != null && !r.activity.mFinished) {
  7. if (clearHide) {
  8. r.hideForNow = false;
  9. r.activity.mStartedActivity = false;
  10. }
  11. try {
  12. //...
  13. r.activity.performResume();
  14.  
  15. //...
  16. } catch (Exception e) {
  17. //...
  18. }
  19. }
  20. return r;
  21. }
        继续看performResume 
        Activity.class
  1. final void performResume() {
  2. //目标Activity的OnRestart和Onstart都在里面
  3. performRestart();
  4.  
  5. mFragments.execPendingActions();
  6.  
  7. mLastNonConfigurationInstances = null;
  8.  
  9. mCalled = false;
  10. // mResumed is set by the instrumentation
  11. // 调用了目标Activity的 onOnResume方法
  12. mInstrumentation.callActivityOnResume(this);
  13. if (!mCalled) {
  14. throw new SuperNotCalledException(
  15. "Activity " + mComponent.toShortString() +
  16. " did not call through to super.onResume()");
  17. }
  18.  
  19. // Now really resume, and install the current status bar and menu.
  20. mCalled = false;
  21.  
  22. mFragments.dispatchResume();
  23. mFragments.execPendingActions();
  24.  
  25. onPostResume();
  26. if (!mCalled) {
  27. throw new SuperNotCalledException(
  28. "Activity " + mComponent.toShortString() +
  29. " did not call through to super.onPostResume()");
  30. }
  31. }

还是得继续看performRestart

  1. final void performRestart() {
  2. mFragments.noteStateNotSaved();
  3.  
  4. if (mStopped) {
  5. mStopped = false;
  6. if (mToken != null && mParent == null) {
  7. WindowManagerGlobal.getInstance().setStoppedState(mToken, false);
  8. }
  9.  
  10. //...
  11.  
  12. mCalled = false;
  13. //这里调用OnRestart方法
  14. mInstrumentation.callActivityOnRestart(this);
  15. if (!mCalled) {
  16. throw new SuperNotCalledException(
  17. "Activity " + mComponent.toShortString() +
  18. " did not call through to super.onRestart()");
  19. }
  20. //目标Activity的onStart在这里面
  21. performStart();
  22. }
  23. }
  1. final void performStart() {
  2. //...
  3. // 目标Activity的onStart在这里运行
  4. mInstrumentation.callActivityOnStart(this);
  5. if (!mCalled) {
  6. throw new SuperNotCalledException(
  7. "Activity " + mComponent.toShortString() +
  8. " did not call through to super.onStart()");
  9. }
  10. //...
  11. }
        Instrumentation.class
  1. public void callActivityOnStart(Activity activity) {
  2. activity.onStart();
  3. }

看到了activity.onStart()

  1. public void callActivityOnResume(Activity activity) {
  2. activity.mResumed = true;
  3. activity.onResume();
  4.  
  5. if (mActivityMonitors != null) {
  6. synchronized (mSync) {
  7. final int N = mActivityMonitors.size();
  8. for (int i=0; i<N; i++) {
  9. final ActivityMonitor am = mActivityMonitors.get(i);
  10. am.match(activity, activity, activity.getIntent());
  11. }
  12. }
  13. }
  14. }
        看到了activity.onResume()

        至此。从已经走到了Activity_B生命周期的onResume方法。

源代码分析已经完毕了Activity_A.onPause()--Activity_B.onCreate()--Activity_B.onStart()--Activity_B.onResume(),期间还看到了Activity的onSaveInstanceState(),OnRestoreInstanceState()。OnRestart()方法。

        还有最后Activity_A的onStop方法没有看到,继续看源代码吧!
        回到ActivityThread的handleResumeActivity方法。里面的r.activity.makeVisible()去调用目标Activity_B的
makeVisible()函数,该函数其内部又会辗转和WmS进行各种调用。并最终导致Activity包括
的DecorView显示到屏幕上(有待研究)。
        handleResumeActivity方法中另一句Looper.myQueue().addIdleHandler(new
Idler()),创建一个Idler对象,并加入到线程消息队列中。而 Idler类的内部处理函数则是调用WmS的 activityldle()方法在该函数的内部则会辗转调用到stopActivityLocked()方法。

 
      ActivityStack.class
  1. final void stopActivityLocked(ActivityRecord r) {
  2. //...
  3. if (r.app != null && r.app.thread != null) {
  4. adjustFocusedActivityLocked(r, "stopActivity");
  5. r.resumeKeyDispatchingLocked();
  6. try {
  7. //...
  8. //这里调用setAppVisibility(r.appToken, false)隐藏Activity_A
  9. if (!r.visible) {
  10. mWindowManager.setAppVisibility(r.appToken, false);
  11. }
  12. //这里则是调用ActivityThread.scheduleStopActivity
  13. r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
  14. //...
  15. Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG, r);
  16. mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
  17. } catch (Exception e) {
  18. //...
  19. }
  20. }
  21. }

又回到了ActivityThread

 
      ActivityThread.class

  1. public final void scheduleStopActivity(IBinder token, boolean showWindow,
  2. int configChanges) {
  3. sendMessage(
  4. showWindow ?
  5.  
  6. H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
  7. token, 0, configChanges);
  8. }

告知H,运行
handleStopActivity,又会调用ActivityThread的performStopActivityInner,接着运行r.activity.performStop()调用Activity的performStop

 
      Activity.class
  1. final void performStop() {
  2. mDoReportFullyDrawn = false;
  3. //...
  4.  
  5. if (!mStopped) {
  6. //...
  7. //这里Activity_A的OnStop方法
  8. mInstrumentation.callActivityOnStop(this);
  9. if (!mCalled) {
  10. throw new SuperNotCalledException(
  11. "Activity " + mComponent.toShortString() +
  12. " did not call through to super.onStop()");
  13. }
  14.  
  15. //...
  16. mStopped = true;
  17. }
  18. mResumed = false;
  19. }

Instrumentation.class

  1. public void callActivityOnStop(Activity activity) {
  2. activity.onStop();
  3. }

最后调用了activity.onStop()



   
    至此,从Activity_A到Activity_B,分别经历的生命周期运行过程和顺序
走通了!!。!
Activity_A.onPause()--Activity_B.onCreate()--Activity_B.onStart()--Activity_B.onResume()--Activity_A.onStop()。

Activity生命周期的回调,你应该知道得很多其它!--Android源代码剖析(下)的更多相关文章

  1. android官方Api 理解Activity生命周期的回调机制(适合有基础的人看)

    原文地址:http://www.android-doc.com/training/basics/activity-lifecycle/starting.html#lifecycle-states 此处 ...

  2. Android全面解析之Activity生命周期

    前言 很高兴遇见你~ 欢迎阅读我的文章. 关于Activity生命周期的文章,网络上真的很多,有很多的博客也都讲得相当不错,可见Activity的重要性是非常高的.事实上,我猜测每个android开发 ...

  3. Activity生命周期以及启动模式对生命周期的影响(二)

    前面一篇文章概述了Android四大组件之一的Activity生命周期方法的调用先后顺序,但对于非标准启动模式下Activity被多次调用时的一些生命周期方法并未详细阐述,现在针对该情况着重记录. 现 ...

  4. Android Activity生命周期与启动模式

    Activity的完整生命周期如下图: Activity的加载模式有四种: standard: 标准模式,默认的加载模式,每次通过这种模式启动目标Acitivity,都创建一个新的实例,并将该Acti ...

  5. Activity生命周期(深入理解)

    今天看到一篇大神总结Activity的文章,内容甚为详细,特此转载http://www.cnblogs.com/lwbqqyumidi/p/3769113.html Android官方文档和其他不少资 ...

  6. Android Activity生命周期详讲

    管理 Activity 生命周期 通过实现回调方法管理 Activity 的生命周期对开发强大而又灵活的应用至关重要. Activity 的生命周期会直接受到 Activity 与其他 Activit ...

  7. Android总结篇系列:Activity生命周期

    Android官方文档和其他不少资料都对Activity生命周期进行了详细介绍,在结合资料和项目开发过程中遇到的问题,本文将对Activity生命周期进行一次总结. Activity是由Activit ...

  8. Android体系结构及activity生命周期

    Android的系统架构采用了分层架构的思想,如图1所示.从上层到底层共包括四层,分别是应用程序程序层.应用框架层.系统库和Android运行时和Linux内核 Android的系统架构图    每层 ...

  9. Android学习整理之Activity生命周期篇

    一.Activity生命周期说明   Activity的四种状态: ⒈活动状态(Active or Running):也称为运行状态,处于Activity栈顶,在用户界面中最上层,完全能被用户看到,能 ...

随机推荐

  1. 今日SGU 5.2

    SGU123 题意:求和 收获:无 #include<bits/stdc++.h> #define de(x) cout<<#x<<"="< ...

  2. 【例题 8-12 UVA-12627】Erratic Expansion

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 规律+递归题 f[k][i] k时刻前i行的红气球个数 i<=2^(k-1) f[k][i] = 2*f[k-1][i]; i ...

  3. 【CS Round #39 (Div. 2 only) B】Circle Elimination

    [Link]:https://csacademy.com/contest/round-39/task/circle-elimination/ [Description] [Solution] 把n个点 ...

  4. 漫话Unity(二)

    三.Unity编辑器介绍 Unity是一个商业级的3d游戏引擎.一个引擎的专业程度事实上并非体如今它多么牛b 的次世代效果,说实话那些效果即便你会用也不敢用.由于没有哪个手机是次世代的. 游戏引擎的专 ...

  5. 负载均衡器&amp;http正向代理

    透明的负载均衡器&http正向代理 * master-workers架构,http正向代理由独立的dns请求以及缓冲进程  * 使用epoll(ET)模式,採用全异步方式(双缓存,实现双向同一 ...

  6. 深入理解javascript之原型

    理解原型 原型是一个对象.其它对象能够通过它实现属性继承. 不论什么一个对象都能够成为继承,全部对象在默认的情况下都有一个原型.由于原型本身也是对象,所以每一个原型自身又有一个原型. 不论什么一个对象 ...

  7. eclipse-ubuntu14.04图标替换不掉的问题

    今天安装14.04的时候,遇到了一个问题.就是eclipse安装好以后,发现需要配置ADT,老是配置失败.后来实在没有办法了,所以就把这个eclipse跟删除了(当时它并没有安装,而是仅仅解压以后双击 ...

  8. WebService三大基本元素 SOAP WSDL UDDI

    转自:https://blog.csdn.net/hhooong/article/details/51763128 1.SOAP 即 Simple Object AccessProtocol 也就是简 ...

  9. echarts tooltip提示框 自定义小圆点(颜色、形状和大小等等)

    项目是拿 echarts + 百度地图 来做可视化界面,现在到收尾阶段慢慢优化. 先附代码: formatter: function(params) { var result = '' params. ...

  10. 【Todo】Zookeeper系列文章

    http://nileader.blog.51cto.com/1381108/1068033