Application启动流程

我用的是安卓10版本,其他版本可能有差异,但是具体实现原理是一致的

Activity.java

Android 的桌面本身也是一个 APP,为 Launcher。

当我们点击桌面的应用图标开始,就是 Launcher 中的一次点击事件:

1.Launcher

public class Launcher extends BaseDraggingActivity implements LauncherExterns,
         LauncherModel.Callbacks, LauncherProviderChangeListener, UserEventDelegate,
         InvariantDeviceProfile.OnIDPChangeListener {
             
             
 		   View createShortcut(WorkspaceItemInfo info) {
1120          return createShortcut((ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentPage()), info);
1121      }

1131      public View createShortcut(ViewGroup parent, WorkspaceItemInfo info) {
1132          BubbleTextView favorite = (BubbleTextView) LayoutInflater.from(parent.getContext())
1133                  .inflate(R.layout.app_icon, parent, false);
1134          favorite.applyFromWorkspaceItem(info);
1135          favorite.setOnClickListener(ItemClickHandler.INSTANCE);
1136          favorite.setOnFocusChangeListener(mFocusHandler);
1137          return favorite;
1138      }
         }            

1135ItemClickHandler点击事件

70      private static void onClick(View v, String sourceContainer) {
93  
94          Object tag = v.getTag();
95          if (tag instanceof WorkspaceItemInfo) {
96              onClickAppShortcut(v, (WorkspaceItemInfo) tag, launcher, sourceContainer);
97          } else if (tag instanceof FolderInfo) {
98              if (v instanceof FolderIcon) {
99                  onClickFolderIcon(v);
100              }
101          } else if (tag instanceof AppInfo) {
102              if (TestProtocol.sDebugTracing) {
103                  android.util.Log.d(TestProtocol.NO_START_TAG,
104                          "onClick 4");
105              }
106              startAppShortcutOrInfoActivity(v, (AppInfo) tag, launcher,
107                      sourceContainer == null ? CONTAINER_ALL_APPS: sourceContainer);
108          } else if (tag instanceof LauncherAppWidgetInfo) {
109              if (v instanceof PendingAppWidgetHostView) {
110                  onClickPendingWidget((PendingAppWidgetHostView) v, launcher);
111              }
112          }
113      }

调用startAppShortcutOrInfoActivity

235      private static void startAppShortcutOrInfoActivity(View v, ItemInfo item, Launcher launcher,
236              @Nullable String sourceContainer) {
237          if (TestProtocol.sDebugTracing) {
238              android.util.Log.d(TestProtocol.NO_START_TAG,
239                      "startAppShortcutOrInfoActivity");
240          }
241          Intent intent;
242          if (item instanceof PromiseAppInfo) {
243              PromiseAppInfo promiseAppInfo = (PromiseAppInfo) item;
244              intent = promiseAppInfo.getMarketIntent(launcher);
245          } else {
246              intent = item.getIntent();
247          }
248          if (intent == null) {
249              throw new IllegalArgumentException("Input must have a valid intent");
250          }
251          if (item instanceof WorkspaceItemInfo) {
252              WorkspaceItemInfo si = (WorkspaceItemInfo) item;
253              if (si.hasStatusFlag(WorkspaceItemInfo.FLAG_SUPPORTS_WEB_UI)
254                      && Intent.ACTION_VIEW.equals(intent.getAction())) {
255                  // make a copy of the intent that has the package set to null
256                  // we do this because the platform sometimes disables instant
257                  // apps temporarily (triggered by the user) and fallbacks to the
258                  // web ui. This only works though if the package isn't set
259                  intent = new Intent(intent);
260                  intent.setPackage(null);
261              }
262          }
263          if (v != null && launcher.getAppTransitionManager().supportsAdaptiveIconAnimation()) {
264              // Preload the icon to reduce latency b/w swapping the floating view with the original.
265              FloatingIconView.fetchIcon(launcher, v, item, true /* isOpening */);
266          }
267          launcher.startActivitySafely(v, intent, item, sourceContainer);
268      }

267最后调用startActivitySafely

1810      public boolean startActivitySafely(View v, Intent intent, ItemInfo item,
1811              @Nullable String sourceContainer) {
...  
1826          boolean success = super.startActivitySafely(v, intent, item, sourceContainer);
...
1836          return success;
1837      }

1826这里调用的是父类的 startActivitySafely 方法

Launcher extends BaseDraggingActivity

136      public boolean startActivitySafely(View v, Intent intent, @Nullable ItemInfo item,
137              @Nullable String sourceContainer) {
...
151          intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
152          if (v != null) {
153              intent.setSourceBounds(getViewBounds(v));
154          }
155          try {
156              boolean isShortcut = (item instanceof WorkspaceItemInfo)
157                      && (item.itemType == Favorites.ITEM_TYPE_SHORTCUT
158                      || item.itemType == Favorites.ITEM_TYPE_DEEP_SHORTCUT)
159                      && !((WorkspaceItemInfo) item).isPromise();
160              if (isShortcut) {
161                  // Shortcuts need some special checks due to legacy reasons.
162                  startShortcutIntentSafely(intent, optsBundle, item, sourceContainer);
163              } else if (user == null || user.equals(Process.myUserHandle())) {
164                  // Could be launching some bookkeeping activity
165                  if (TestProtocol.sDebugTracing) {
166                      android.util.Log.d(TestProtocol.NO_START_TAG,
167                              "startActivitySafely 2");
168                  }
169                  startActivity(intent, optsBundle);
...
185          return false;
186      }

2Activity中的startActivity

Activity.java

触发 startActivity(intent);

public void startActivity(Intent intent) {
    this.startActivity(intent, null);
}

调用重载

public void startActivity(Intent intent, @Nullable Bundle options) {
...
    if (options != null) {
        startActivityForResult(intent, -1, options);
    } else {
        // Note we want to go through this call for compatibility with
        // applications that may have overridden the method.
        startActivityForResult(intent, -1);
    }
}

无论option是否为空都触发startActivityForResult()

public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
        @Nullable Bundle options) {
    if (mParent == null) {
        options = transferSpringboardActivityOptions(options);
        Instrumentation.ActivityResult ar =
            mInstrumentation.execStartActivity(
                this, mMainThread.getApplicationThread(), mToken, this,
                intent, requestCode, options);
}

3.调用Instrumentation

调用execStartActivity方法

public ActivityResult execStartActivity(
        Context who, IBinder contextThread, IBinder token, Activity target,
        Intent intent, int requestCode, Bundle options) {
 ...
    try {
        intent.migrateExtraStreamToClipData(who);
        intent.prepareToLeaveProcess(who);
        int result = ActivityTaskManager.getService().startActivity(whoThread,
                who.getOpPackageName(), who.getAttributionTag(), intent,
                intent.resolveTypeIfNeeded(who.getContentResolver()), token,
                target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);
        checkStartActivityResult(result, intent);
    } catch (RemoteException e) {
        throw new RuntimeException("Failure from system", e);
    }
    return null;
}

4调用ActivityTaskManager

ActivityTaskManager.getService().startActivity方法

public static IActivityTaskManager getService() {
    return IActivityTaskManagerSingleton.get();
}

返回IActivityTaskManagerSingleton.get();

private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton =
        new Singleton<IActivityTaskManager>() {
            @Override
            protected IActivityTaskManager create() {
                final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
                return IActivityTaskManager.Stub.asInterface(b);
            }
        };

5.ActivityManagerService

这里ActivityTaskManager.getService()使用了aidl机制实现了ActivityManagerService

public class ActivityManagerService extends IActivityManager.Stub
public int startActivity(IApplicationThread caller, String callingPackage,
        Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
        int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
    return mActivityTaskManager.startActivity(caller, callingPackage, null, intent,
            resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions);
}

这个ActivityTaskManagerService也是ActivityTaskManager的aidl实现

 public class ActivityTaskManagerService extends IActivityTaskManager.Stub
public final int startActivity(IApplicationThread caller, String callingPackage,
	Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
	int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
	resultWho, requestCode, startFlags, profilerInfo, bOptions,
UserHandle.getCallingUserId());
}

这里返回了startActivityAsUser

6.ActivityStartController

1028      @Override
1029      public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1030              Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1031              int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1032          return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1033                  resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1034                  true /*validateIncomingUser*/);
1035      }
1036  
1037      int startActivityAsUser(IApplicationThread caller, String callingPackage,
1038              Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1039              int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1040              boolean validateIncomingUser) {
1041          enforceNotIsolatedCaller("startActivityAsUser");
1042  
1043          userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
1044                  Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1045  
1046          // TODO: Switch to user app stacks here.
1047          return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
1048                  .setCaller(caller)
1049                  .setCallingPackage(callingPackage)
1050                  .setResolvedType(resolvedType)
1051                  .setResultTo(resultTo)
1052                  .setResultWho(resultWho)
1053                  .setRequestCode(requestCode)
1054                  .setStartFlags(startFlags)
1055                  .setProfilerInfo(profilerInfo)
1056                  .setActivityOptions(bOptions)
1057                  .setMayWait(userId)
1058                  .execute();
1059  
1060      }
    ActivityStartController getActivityStartController() {
910          return mActivityStartController;
911      }
private ActivityStartController mActivityStartController;
ActivityStarter obtainStarter(Intent intent, String reason) {
    return mFactory.obtain().setIntent(intent).setReason(reason);
}
private final Factory mFactory;
interface Factory {
222          /**
223           * Sets the {@link ActivityStartController} to be passed to {@link ActivityStarter}.
224           */
225          void setController(ActivityStartController controller);
226  
227          /**
228           * Generates an {@link ActivityStarter} that is ready to handle a new start request.
229           * @param controller The {@link ActivityStartController} which the starter who will own
230           *                   this instance.
231           * @return an {@link ActivityStarter}
232           */
233          ActivityStarter obtain();
234  
235          /**
236           * Recycles a starter for reuse.
237           */
238          void recycle(ActivityStarter starter);
239      }

而Factory接口是ActivityStarter中的,所以return getActivityStartController().obtainStarter的execute()函数是ActivityStarter中的

查看execute()方法返回startActivityMayWait

     int execute() {
510          try {
511              // TODO(b/64750076): Look into passing request directly to these methods to allow
512              // for transactional diffs and preprocessing.
513              if (mRequest.mayWait) {
514                  return startActivityMayWait(mRequest.caller, mRequest.callingUid,
515                          mRequest.callingPackage, mRequest.realCallingPid, mRequest.realCallingUid,
516                          mRequest.intent, mRequest.resolvedType,
517                          mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
518                          mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,
519                          mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig,
520                          mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId,
521                          mRequest.inTask, mRequest.reason,
522                          mRequest.allowPendingRemoteAnimationRegistryLookup,
523                          mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart);
524              } else {
525                  return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,
526                          mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo,
527                          mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
528                          mRequest.resultWho, mRequest.requestCode, mRequest.callingPid,
529                          mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid,
530                          mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions,
531                          mRequest.ignoreTargetSecurity, mRequest.componentSpecified,
532                          mRequest.outActivity, mRequest.inTask, mRequest.reason,
533                          mRequest.allowPendingRemoteAnimationRegistryLookup,
534                          mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart);
535              }
536          } finally {
537              onExecutionComplete();
538          }
539      }

7.startActivityMayWait

514查看startActivityMayWait

private int startActivityMayWait(IApplicationThread caller, int callingUid,
1135              String callingPackage, int requestRealCallingPid, int requestRealCallingUid,
1136              Intent intent, String resolvedType, IVoiceInteractionSession voiceSession,
1137              IVoiceInteractor voiceInteractor, IBinder resultTo, String resultWho, int requestCode,
1138              int startFlags, ProfilerInfo profilerInfo, WaitResult outResult,
1139              Configuration globalConfig, SafeActivityOptions options, boolean ignoreTargetSecurity,
1140              int userId, TaskRecord inTask, String reason,
1141              boolean allowPendingRemoteAnimationRegistryLookup,
1142              PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {
...
1288              int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,
1289                      voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,
1290                      callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,
1291                      ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,
1292                      allowPendingRemoteAnimationRegistryLookup, originatingPendingIntent,
1293                      allowBackgroundActivityStart);

1288调用了startActivity

8.ActivityStarter

查看startActivity

private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
567              String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
568              IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
569              IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
570              String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
571              SafeActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
572              ActivityRecord[] outActivity, TaskRecord inTask, String reason,
573              boolean allowPendingRemoteAnimationRegistryLookup,
574              PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {
575  
576          if (TextUtils.isEmpty(reason)) {
577              throw new IllegalArgumentException("Need to specify a reason.");
578          }
579          mLastStartReason = reason;
580          mLastStartActivityTimeMs = System.currentTimeMillis();
581          mLastStartActivityRecord[0] = null;
582  
583          mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
584                  aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
585                  callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
586                  options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
587                  inTask, allowPendingRemoteAnimationRegistryLookup, originatingPendingIntent,
588                  allowBackgroundActivityStart);
589  
590          if (outActivity != null) {
591              // mLastStartActivityRecord[0] is set in the call to startActivity above.
592              outActivity[0] = mLastStartActivityRecord[0];
593          }
594  
595          return getExternalResult(mLastStartActivityResult);
596      }
597  

583调用startActivity的重载方法

  private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
612              String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
613              IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
614              IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
615              String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
616              SafeActivityOptions options,
617              boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity,
618              TaskRecord inTask, boolean allowPendingRemoteAnimationRegistryLookup,
619              PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {
...
933          final int res = startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
934                  true /* doResume */, checkedOptions, inTask, outActivity, restrictedBgActivity);
935          mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(res, outActivity[0]);
936          return res;
937      }

933继续调用startActivity

386      private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
1387                  IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
1388                  int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
1389                  ActivityRecord[] outActivity, boolean restrictedBgActivity) {
1390          int result = START_CANCELED;
1391          final ActivityStack startedActivityStack;
1392          try {
1393              mService.mWindowManager.deferSurfaceLayout();
1394              result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
1395                      startFlags, doResume, options, inTask, outActivity, restrictedBgActivity);
1396          } 
    
    ...
1433          postStartActivityProcessing(r, result, startedActivityStack);
1434  
1435          return result;
1436      }

9.startActivityUnchecked

1394调用了startActivityUnchecked

1464      private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
1465              IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
1466              int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
1467              ActivityRecord[] outActivity, boolean restrictedBgActivity) {
...
1641              if (mDoResume) {
1642                  mRootActivityContainer.resumeFocusedStacksTopActivities();
1643              }
1644              ActivityOptions.abort(mOptions);
1645              if ((mStartFlags & START_FLAG_ONLY_IF_NEEDED) != 0) {
1646                  // We don't need to start a new activity, and the client said not to do
1647                  // anything if that is the case, so this is it!
1648                  return START_RETURN_INTENT_TO_CALLER;
1649              }
1650  
...
1735  
1736          mSupervisor.handleNonResizableTaskIfNeeded(mStartActivity.getTaskRecord(),
1737                  preferredWindowingMode, mPreferredDisplayId, mTargetStack);
1738  
1739          return START_SUCCESS;
1740      }

走的1642的RootActivityContainer 的 resumeFocusedStacksTopActivities 方法。

10.RootActivityContainer

查看RootActivityContainer

 boolean resumeFocusedStacksTopActivities() {
1145          return resumeFocusedStacksTopActivities(null, null, null);
1146      }
1147  
1148      boolean resumeFocusedStacksTopActivities(
1149              ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
1150  
1151          if (!mStackSupervisor.readyToResume()) {
1152              return false;
1153          }
1154  
1155          boolean result = false;
1156          if (targetStack != null && (targetStack.isTopStackOnDisplay()
1157                  || getTopDisplayFocusedStack() == targetStack)) {
1158              result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
1159          }
...
1197          return result;
1198      }

1149创建ActivityStack对象,1158调用了resumeTopActivityUncheckedLocked方法

11.ActivityStack

查看ActivityStack

class ActivityStack extends ConfigurationContainer {
 
    boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
2566          if (mInResumeTopActivity) {
2568              return false;
2569          }
2570  
2571          boolean result = false;
2572          try {
2574              mInResumeTopActivity = true;
2575              result = resumeTopActivityInnerLocked(prev, options);
2584              final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
2585              if (next == null || !next.canTurnScreenOn()) {
2586                  checkReadyForSleep();
2587              }
2588          } finally {
2589              mInResumeTopActivity = false;
2590          }
2591  
2592          return result;
2593      }
2594    
    
}

2575调用resumeTopActivityInnerLocked方法

2614      private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
...
2744          boolean pausing = getDisplay().pauseBackStacks(userLeaving, next, false);
2745          if (mResumedActivity != null) {
2746              if (DEBUG_STATES) Slog.d(TAG_STATES,
2747                      "resumeTopActivityLocked: Pausing " + mResumedActivity);
2748              pausing |= startPausingLocked(userLeaving, false, next, false);
2749          }
...

2873          if (next.attachedToProcess()) {
...
3009                  mStackSupervisor.startSpecificActivityLocked(next, true, false);
3010                  return true;
3011              }
3012  
3013              // From this point on, if something goes wrong there is no way
3014              // to recover the activity.
3015              try {
3016                  next.completeResumeLocked();
3017              } catch (Exception e) {
3018                  // If any exception gets thrown, toss away this
3019                  // activity and try the next one.
3020                  Slog.w(TAG, "Exception thrown during resume of " + next, e);
3021                  requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
3022                          "resume-exception", true);
3023                  return true;
3024              }
3025          } else {
3026              // Whoops, need to restart this activity!
3027              if (!next.hasBeenLaunched) {
3028                  next.hasBeenLaunched = true;
3029              } else {
3030                  if (SHOW_APP_STARTING_PREVIEW) {
3031                      next.showStartingWindow(null /* prev */, false /* newTask */,
3032                              false /* taskSwich */);
3033                  }
3034                  if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Restarting: " + next);
3035              }
3036              if (DEBUG_STATES) Slog.d(TAG_STATES, "resumeTopActivityLocked: Restarting " + next);
3037              mStackSupervisor.startSpecificActivityLocked(next, true, true);
3038          }
3039  
3040          return true;
3041      }

2648先判断是否Activity处于Resume状态有的话调用2748startPausingLocked让Activity执行Pausing过程

接着调用3009和3037StackSupervisor.startSpecificActivityLocked方法

startPausingLocked

1653      final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,
1654              ActivityRecord resuming, boolean pauseImmediately) {
...
1692          if (prev.attachedToProcess()) {
1693              if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Enqueueing pending pause: " + prev);
1694              try {
1695                  EventLogTags.writeAmPauseActivity(prev.mUserId, System.identityHashCode(prev),
1696                          prev.shortComponentName, "userLeaving=" + userLeaving);
1697  
1698                  mService.getLifecycleManager().scheduleTransaction(prev.app.getThread(),
1699                          prev.appToken, PauseActivityItem.obtain(prev.finishing, userLeaving,
1700                                  prev.configChangeFlags, pauseImmediately));
1701              }
    ...
1751      }

核心调用mService.getLifecycleManager().scheduleTransaction方法

317      final ActivityTaskManagerService mService;

这个mService是ActivityTaskManagerService

12.ClientLifecycleManager

查看ActivityTaskManagerService

ClientLifecycleManager getLifecycleManager() {
    return mLifecycleManager;
}  
private final ClientLifecycleManager mLifecycleManager;

返回了ClientLifecycleManager

查看 ClientLifecycleManager

   void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
46          final IApplicationThread client = transaction.getClient();
47          transaction.schedule();
48          if (!(client instanceof Binder)) {
49              // If client is not an instance of Binder - it's a remote call and at this point it is
50              // safe to recycle the object. All objects used for local calls will be recycled after
51              // the transaction is executed on client in ActivityThread.
52              transaction.recycle();
53          }
54      }
55  
56      /**
57       * Schedule a single lifecycle request or callback to client activity.
58       * @param client Target client.
59       * @param activityToken Target activity token.
60       * @param stateRequest A request to move target activity to a desired lifecycle state.
61       * @throws RemoteException
62       *
63       * @see ClientTransactionItem
64       */
65      void scheduleTransaction(@NonNull IApplicationThread client, @NonNull IBinder activityToken,
66              @NonNull ActivityLifecycleItem stateRequest) throws RemoteException {
67          final ClientTransaction clientTransaction = transactionWithState(client, activityToken,
68                  stateRequest);
69          scheduleTransaction(clientTransaction);
70      }
71  
72      /**
73       * Schedule a single callback delivery to client activity.
74       * @param client Target client.
75       * @param activityToken Target activity token.
76       * @param callback A request to deliver a callback.
77       * @throws RemoteException
78       *
79       * @see ClientTransactionItem
80       */
81      void scheduleTransaction(@NonNull IApplicationThread client, @NonNull IBinder activityToken,
82              @NonNull ClientTransactionItem callback) throws RemoteException {
83          final ClientTransaction clientTransaction = transactionWithCallback(client, activityToken,
84                  callback);
85          scheduleTransaction(clientTransaction);
86      }
87  
88      /**
89       * Schedule a single callback delivery to client application.
90       * @param client Target client.
91       * @param callback A request to deliver a callback.
92       * @throws RemoteException
93       *
94       * @see ClientTransactionItem
95       */
96      void scheduleTransaction(@NonNull IApplicationThread client,
97              @NonNull ClientTransactionItem callback) throws RemoteException {
98          final ClientTransaction clientTransaction = transactionWithCallback(client,
99                  null /* activityToken */, callback);
100          scheduleTransaction(clientTransaction);
101      }
102  

重载了四次scheduleTransaction

第一个调用transaction.getClient();其余调用scheduleTransaction也就是全部掉用了transaction.getClient()通过ClientTransaction的getClient()返回client对象

13.ClientTransaction

查看ClientTransaction

private IApplicationThread mClient;
public IApplicationThread getClient() {
    return mClient;
}
144      public static ClientTransaction obtain(IApplicationThread client, IBinder activityToken) {
145          ClientTransaction instance = ObjectPool.obtain(ClientTransaction.class);
146          if (instance == null) {
147              instance = new ClientTransaction();
148          }
149          instance.mClient = client;
150          instance.mActivityToken = activityToken;
151  
152          return instance;
153      }
154  

其中obtion对mClient做了初始化

14.ActivityThread

ActivityThread

public final class ActivityThread extends ClientTransactionHandler
        implements ActivityThreadInternal {
    ...
  private class ApplicationThread extends IApplicationThread.Stub {
          public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
             ActivityThread.this.scheduleTransaction(transaction);
         }

    ...
}

这里可以看处理ApplicationThread继承了IApplicationThread.Stub 是aidl的server服务端

15.ClientTransactionHandler

查看ClientTransactionHandler

public abstract class ClientTransactionHandler {

   void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }

        abstract void sendMessage(int what, Object obj);

}

回到Activity中

void sendMessage(int what, Object obj) {
    sendMessage(what, obj, 0, 0, false);
}

private void sendMessage(int what, Object obj, int arg1) {
    sendMessage(what, obj, arg1, 0, false);
}

private void sendMessage(int what, Object obj, int arg1, int arg2) {
    sendMessage(what, obj, arg1, arg2, false);
}

private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
    if (DEBUG_MESSAGES) {
        Slog.v(TAG,
                "SCHEDULE " + what + " " + mH.codeToString(what) + ": " + arg1 + " / " + obj);
    }
    Message msg = Message.obtain();
    msg.what = what;
    msg.obj = obj;
    msg.arg1 = arg1;
    msg.arg2 = arg2;
    if (async) {
        msg.setAsynchronous(true);
    }
    mH.sendMessage(msg);
}

private void sendMessage(int what, Object obj, int arg1, int arg2, int seq) {
    if (DEBUG_MESSAGES) Slog.v(
            TAG, "SCHEDULE " + mH.codeToString(what) + " arg1=" + arg1 + " arg2=" + arg2 +
                    "seq= " + seq);
    Message msg = Message.obtain();
    msg.what = what;
    SomeArgs args = SomeArgs.obtain();
    args.arg1 = obj;
    args.argi1 = arg1;
    args.argi2 = arg2;
    args.argi3 = seq;
    msg.obj = args;
    mH.sendMessage(msg);
}

在ClientTransactionHandler中sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);时,ActivityThread中有一个H类

  class H extends Handler {
   4                  case EXECUTE_TRANSACTION:
2015                      final ClientTransaction transaction = (ClientTransaction) msg.obj;
2016                      mTransactionExecutor.execute(transaction);
2017                      if (isSystem()) {
2018                          // Client transactions inside system process are recycled on the client side
2019                          // instead of ClientLifecycleManager to avoid being cleared before this
2020                          // message is handled.
2021                          transaction.recycle();
2022                      }
2023                      // TODO(lifecycler): Recycle locally scheduled transactions.
2024                      break;   
      
  }
private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);

16.TransactionExecutor

调用了TransactionExecutor.execute(transaction)

69      public void execute(ClientTransaction transaction) {
...
97          executeLifecycleState(transaction);
...
100      }

执行核心方法executeLifecycleState(transaction)

152      private void executeLifecycleState(ClientTransaction transaction) {
153          final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
...
176          lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
177          lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
178      }
179  

返回了ActivityLifecycleItem

28  public abstract class ActivityLifecycleItem extends ClientTransactionItem {
29  
30      @IntDef(prefix = { "UNDEFINED", "PRE_", "ON_" }, value = {
31              UNDEFINED,
32              PRE_ON_CREATE,
33              ON_CREATE,
34              ON_START,
35              ON_RESUME,
36              ON_PAUSE,
37              ON_STOP,
38              ON_DESTROY,
39              ON_RESTART
40      })
41      @Retention(RetentionPolicy.SOURCE)
42      public @interface LifecycleState{}
43      public static final int UNDEFINED = -1;
44      public static final int PRE_ON_CREATE = 0;
45      public static final int ON_CREATE = 1;
46      public static final int ON_START = 2;
47      public static final int ON_RESUME = 3;
48      public static final int ON_PAUSE = 4;
49      public static final int ON_STOP = 5;
50      public static final int ON_DESTROY = 6;
51      public static final int ON_RESTART = 7;
52  
53      /** A final lifecycle state that an activity should reach. */
54      @LifecycleState
55      public abstract int getTargetState();
56  
57      /** Called by subclasses to make sure base implementation is cleaned up */
58      @Override
59      public void recycle() {
60      }
61  }
62  

而它是一抽象类,它有三个实现类PauseActivityItem,ResumeActivityItem,StopActivityItem,由于这里是要让 Activity 进入 Pause 状态,所以这里是 PauseActivityItem。

17.PauseActivityItem

public class PauseActivityItem extends ActivityLifecycleItem {
        public void execute(ClientTransactionHandler client, ActivityClientRecord r,
            PendingTransactionActions pendingActions) {
        Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
        client.handlePauseActivity(r, mFinished, mUserLeaving, mConfigChanges, pendingActions,
                "PAUSE_ACTIVITY_ITEM");
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }
}

这里调用了client.handlePauseActivity是ActivityThread中的

4397      public void handlePauseActivity(IBinder token, boolean finished, boolean userLeaving,
4398              int configChanges, PendingTransactionActions pendingActions, String reason) {
4399          ActivityClientRecord r = mActivities.get(token);
4400          if (r != null) {
4401              if (userLeaving) {
4402                  performUserLeavingActivity(r);
4403              }
4404  
4405              r.activity.mConfigChangeFlags |= configChanges;
4406              performPauseActivity(r, finished, reason, pendingActions);
4407  
4408              // Make sure any pending writes are now committed.
4409              if (r.isPreHoneycomb()) {
4410                  QueuedWork.waitToFinish();
4411              }
4412              mSomeActivitiesChanged = true;
4413          }
4414      }

4402调用performUserLeavingActivity

  private Bundle performPauseActivity(ActivityClientRecord r, boolean finished, String reason,
4431              PendingTransactionActions pendingActions) {
4432          if (r.paused) {
4433              if (r.activity.mFinished) {
4434                  // If we are finishing, we won't call onResume() in certain cases.
4435                  // So here we likewise don't want to call onPause() if the activity
4436                  // isn't resumed.
4437                  return null;
4438              }
4439              RuntimeException e = new RuntimeException(
4440                      "Performing pause of activity that is not resumed: "
4441                      + r.intent.getComponent().toShortString());
4442              Slog.e(TAG, e.getMessage(), e);
4443          }
4444          if (finished) {
4445              r.activity.mFinished = true;
4446          }
4447  
4448          // Pre-Honeycomb apps always save their state before pausing
4449          final boolean shouldSaveState = !r.activity.mFinished && r.isPreHoneycomb();
4450          if (shouldSaveState) {
4451              callActivityOnSaveInstanceState(r);
4452          }
4453  
4454          performPauseActivityIfNeeded(r, reason);
4455  
4456          // Notify any outstanding on paused listeners
4457          ArrayList<OnActivityPausedListener> listeners;
4458          synchronized (mOnPauseListeners) {
4459              listeners = mOnPauseListeners.remove(r.activity);
4460          }
4461          int size = (listeners != null ? listeners.size() : 0);
4462          for (int i = 0; i < size; i++) {
4463              listeners.get(i).onPaused(r.activity);
4464          }
4465  
4466          final Bundle oldState = pendingActions != null ? pendingActions.getOldState() : null;
4467          if (oldState != null) {
4468              // We need to keep around the original state, in case we need to be created again.
4469              // But we only do this for pre-Honeycomb apps, which always save their state when
4470              // pausing, so we can not have them save their state when restarting from a paused
4471              // state. For HC and later, we want to (and can) let the state be saved as the
4472              // normal part of stopping the activity.
4473              if (r.isPreHoneycomb()) {
4474                  r.state = oldState;
4475              }
4476          }
4477  
4478          return shouldSaveState ? r.state : null;
4479      }

调用了 performPauseActivityIfNeeded(r, reason)方法

4480  
4481      private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
4482          if (r.paused) {
4483              // You are already paused silly...
4484              return;
4485          }
4486  
4487          // Always reporting top resumed position loss when pausing an activity. If necessary, it
4488          // will be restored in performResumeActivity().
4489          reportTopResumedActivityChanged(r, false /* onTop */, "pausing");
4490  
4491          try {
4492              r.activity.mCalled = false;
4493              mInstrumentation.callActivityOnPause(r.activity);
4494              if (!r.activity.mCalled) {
4495                  throw new SuperNotCalledException("Activity " + safeToComponentShortString(r.intent)
4496                          + " did not call through to super.onPause()");
4497              }
4498          } catch (SuperNotCalledException e) {
4499              throw e;
4500          } catch (Exception e) {
4501              if (!mInstrumentation.onException(r.activity, e)) {
4502                  throw new RuntimeException("Unable to pause activity "
4503                          + safeToComponentShortString(r.intent) + ": " + e.toString(), e);
4504              }
4505          }
4506          r.setState(ON_PAUSE);
4507      }
53      Instrumentation mInstrumentation;
354      String mInstrumentationPackageName = null;

4493回到Instrumentation中的callActivityOnPause()方法

1499      public void callActivityOnPause(Activity activity) {
1500          activity.performPause();
1501      }
1502  

调用了activity.performPause()

7973      final void performPause() {
7974          dispatchActivityPrePaused();
7975          mDoReportFullyDrawn = false;
7976          mFragments.dispatchPause();
7977          mCalled = false;
7978          onPause();
7979          writeEventLog(LOG_AM_ON_PAUSE_CALLED, "performPause");
7980          mResumed = false;
7981          if (!mCalled && getApplicationInfo().targetSdkVersion
7982                  >= android.os.Build.VERSION_CODES.GINGERBREAD) {
7983              throw new SuperNotCalledException(
7984                      "Activity " + mComponent.toShortString() +
7985                      " did not call through to super.onPause()");
7986          }
7987          dispatchActivityPostPaused();
7988      }

7978这时候onPause()启动

18.ActivityStackSupervisor

11.resumeTopActivityInnerLocked中的

protected final ActivityStackSupervisor mStackSupervisor;

3009 3037调用了mStackSupervisor.startSpecificActivityLocked

956      void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
957          // Is this activity's application already running?
958          final WindowProcessController wpc =
959                  mService.getProcessController(r.processName, r.info.applicationInfo.uid);
960  
961          boolean knownToBeDead = false;
962          if (wpc != null && wpc.hasThread()) {
963              try {
964                  realStartActivityLocked(r, wpc, andResume, checkConfig);
965                  return;
966              } catch (RemoteException e) {
967                  Slog.w(TAG, "Exception when starting activity "
968                          + r.intent.getComponent().flattenToShortString(), e);
969              }
970  
971              // If a dead object exception was thrown -- fall through to
972              // restart the application.
973              knownToBeDead = true;
974          }
975  
976          // Suppress transition until the new activity becomes ready, otherwise the keyguard can
977          // appear for a short amount of time before the new process with the new activity had the
978          // ability to set its showWhenLocked flags.
979          if (getKeyguardController().isKeyguardLocked()) {
980              r.notifyUnknownVisibilityLaunched();
981          }
982  
983          try {
984              if (Trace.isTagEnabled(TRACE_TAG_ACTIVITY_MANAGER)) {
985                  Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "dispatchingStartProcess:"
986                          + r.processName);
987              }
988              // Post message to start process to avoid possible deadlock of calling into AMS with the
989              // ATMS lock held.
990              final Message msg = PooledLambda.obtainMessage(
991                      ActivityManagerInternal::startProcess, mService.mAmInternal, r.processName,
992                      r.info.applicationInfo, knownToBeDead, "activity", r.intent.getComponent());
993              mService.mH.sendMessage(msg);
994          } finally {
995              Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
996          }
997      }
998  

962判断app是否存在且启动,如果存在且启动则调用realStartActivityLocked

990如果 App 进程不存在,通过 sendMessage 启动新的进程。因为这里追的是从 Launcher 启动 App,所以进程必然不存在,这里追如果创建进程。

而创建启动是通过ActivityManagerInternal::startProcess

 public abstract class ActivityManagerInternal {

而ActivityManagerInternal是一个抽象类

public abstract void startProcess(String processName, ApplicationInfo info,
                                  boolean knownToBeDead, String hostingType, ComponentName hostingName);

19.ActivityManagerService

这时就要追溯到ActivityManagerService

18407          @Override
18408          public void startProcess(String processName, ApplicationInfo info,
18409                  boolean knownToBeDead, String hostingType, ComponentName hostingName) {
18410              try {
18411                  if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
18412                      Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "startProcess:"
18413                              + processName);
18414                  }
18415                  synchronized (ActivityManagerService.this) {
18416                      startProcessLocked(processName, info, knownToBeDead, 0 /* intentFlags */,
18417                              new HostingRecord(hostingType, hostingName),
18418                              false /* allowWhileBooting */, false /* isolated */,
18419                              true /* keepIfLarge */);
18420                  }
18421              } finally {
18422                  Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
18423              }
18424          }

调用了startProcessLocked

3021      @GuardedBy("this")
3022      final ProcessRecord startProcessLocked(String processName,
3023              ApplicationInfo info, boolean knownToBeDead, int intentFlags,
3024              HostingRecord hostingRecord, boolean allowWhileBooting,
3025              boolean isolated, boolean keepIfLarge) {
3026          return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags,
3027                  hostingRecord, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,
3028                  null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
3029                  null /* crashHandler */);
3030      }

返回mProcessList.startProcessLocked

final ProcessList mProcessList = new ProcessList();

20.ProcessList

1639      @GuardedBy("mService")
1640      boolean startProcessLocked(HostingRecord hostingRecord,
1641              String entryPoint,
1642              ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
1643              String seInfo, String requiredAbi, String instructionSet, String invokeWith,
1644              long startTime) {
1645          app.pendingStart = true;
1646          app.killedByAm = false;
1647          app.removed = false;
1648          app.killed = false;
1649          if (app.startSeq != 0) {
1650              Slog.wtf(TAG, "startProcessLocked processName:" + app.processName
1651                      + " with non-zero startSeq:" + app.startSeq);
1652          }
1653          if (app.pid != 0) {
1654              Slog.wtf(TAG, "startProcessLocked processName:" + app.processName
1655                      + " with non-zero pid:" + app.pid);
1656          }
1657          final long startSeq = app.startSeq = ++mProcStartSeqCounter;
1658          app.setStartParams(uid, hostingRecord, seInfo, startTime);
1659          app.setUsingWrapper(invokeWith != null
1660                  || SystemProperties.get("wrap." + app.processName) != null);
1661          mPendingStarts.put(startSeq, app);
1662  
1663          if (mService.mConstants.FLAG_PROCESS_START_ASYNC) {
1664              if (DEBUG_PROCESSES) Slog.i(TAG_PROCESSES,
1665                      "Posting procStart msg for " + app.toShortString());
1666              mService.mProcStartHandler.post(() -> {
1667                  try {
1668                      final Process.ProcessStartResult startResult = startProcess(app.hostingRecord,
1669                              entryPoint, app, app.startUid, gids, runtimeFlags, mountExternal,
1670                              app.seInfo, requiredAbi, instructionSet, invokeWith, app.startTime);
1671                      synchronized (mService) {
1672                          handleProcessStartedLocked(app, startResult, startSeq);
1673                      }
1674                  } catch (RuntimeException e) {
1675                      synchronized (mService) {
1676                          Slog.e(ActivityManagerService.TAG, "Failure starting process "
1677                                  + app.processName, e);
1678                          mPendingStarts.remove(startSeq);
1679                          app.pendingStart = false;
1680                          mService.forceStopPackageLocked(app.info.packageName,
1681                                  UserHandle.getAppId(app.uid),
1682                                  false, false, true, false, false, app.userId, "start failure");
1683                      }
1684                  }
1685              });
1686              return true;
1687          } else {
1688              try {
1689                  final Process.ProcessStartResult startResult = startProcess(hostingRecord,
1690                          entryPoint, app,
1691                          uid, gids, runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet,
1692                          invokeWith, startTime);
1693                  handleProcessStartedLocked(app, startResult.pid, startResult.usingWrapper,
1694                          startSeq, false);
1695              } catch (RuntimeException e) {
1696                  Slog.e(ActivityManagerService.TAG, "Failure starting process "
1697                          + app.processName, e);
1698                  app.pendingStart = false;
1699                  mService.forceStopPackageLocked(app.info.packageName, UserHandle.getAppId(app.uid),
1700                          false, false, true, false, false, app.userId, "start failure");
1701              }
1702              return app.pid > 0;
1703          }
1704      }

1689调用startProcess

1798      private Process.ProcessStartResult startProcess(HostingRecord hostingRecord, String entryPoint,
1799              ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
1800              String seInfo, String requiredAbi, String instructionSet, String invokeWith,
1801              long startTime) {
1802          try {
1803              Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Start proc: " +
1804                      app.processName);
1805              checkSlow(startTime, "startProcess: asking zygote to start proc");
1806              final Process.ProcessStartResult startResult;
1807              if (hostingRecord.usesWebviewZygote()) {
1808                  startResult = startWebView(entryPoint,
1809                          app.processName, uid, uid, gids, runtimeFlags, mountExternal,
1810                          app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
1811                          app.info.dataDir, null, app.info.packageName,
1812                          new String[] {PROC_START_SEQ_IDENT + app.startSeq});
1813              } else if (hostingRecord.usesAppZygote()) {
1814                  final AppZygote appZygote = createAppZygoteForProcessIfNeeded(app);
1815  
1816                  startResult = appZygote.getProcess().start(entryPoint,
1817                          app.processName, uid, uid, gids, runtimeFlags, mountExternal,
1818                          app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
1819                          app.info.dataDir, null, app.info.packageName,
1820                          /*useUsapPool=*/ false,
1821                          new String[] {PROC_START_SEQ_IDENT + app.startSeq});
1822              } else {
1823                  startResult = Process.start(entryPoint,
1824                          app.processName, uid, uid, gids, runtimeFlags, mountExternal,
1825                          app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
1826                          app.info.dataDir, invokeWith, app.info.packageName,
1827                          new String[] {PROC_START_SEQ_IDENT + app.startSeq});
1828              }
1829              checkSlow(startTime, "startProcess: returned from zygote!");
1830              return startResult;
1831          } finally {
1832              Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1833          }
1834      }

1823调用Process.start

21.Process

521      public static ProcessStartResult start(@NonNull final String processClass,
522                                             @Nullable final String niceName,
523                                             int uid, int gid, @Nullable int[] gids,
524                                             int runtimeFlags,
525                                             int mountExternal,
526                                             int targetSdkVersion,
527                                             @Nullable String seInfo,
528                                             @NonNull String abi,
529                                             @Nullable String instructionSet,
530                                             @Nullable String appDataDir,
531                                             @Nullable String invokeWith,
532                                             @Nullable String packageName,
533                                             @Nullable String[] zygoteArgs) {
534          return ZYGOTE_PROCESS.start(processClass, niceName, uid, gid, gids,
535                      runtimeFlags, mountExternal, targetSdkVersion, seInfo,
536                      abi, instructionSet, appDataDir, invokeWith, packageName,
537                      /*useUsapPool=*/ true, zygoteArgs);
538      }
539  

调用ZYGOTE_PROCESS.start

public static final ZygoteProcess ZYGOTE_PROCESS = new ZygoteProcess();

22.ZygoteProcess

314      public final Process.ProcessStartResult start(@NonNull final String processClass,
315                                                    final String niceName,
316                                                    int uid, int gid, @Nullable int[] gids,
317                                                    int runtimeFlags, int mountExternal,
318                                                    int targetSdkVersion,
319                                                    @Nullable String seInfo,
320                                                    @NonNull String abi,
321                                                    @Nullable String instructionSet,
322                                                    @Nullable String appDataDir,
323                                                    @Nullable String invokeWith,
324                                                    @Nullable String packageName,
325                                                    boolean useUsapPool,
326                                                    @Nullable String[] zygoteArgs) {
327          // TODO (chriswailes): Is there a better place to check this value?
328          if (fetchUsapPoolEnabledPropWithMinInterval()) {
329              informZygotesOfUsapPoolStatus();
330          }
331  
332          try {
333              return startViaZygote(processClass, niceName, uid, gid, gids,
334                      runtimeFlags, mountExternal, targetSdkVersion, seInfo,
335                      abi, instructionSet, appDataDir, invokeWith, /*startChildZygote=*/ false,
336                      packageName, useUsapPool, zygoteArgs);
337          } catch (ZygoteStartFailedEx ex) {
338              Log.e(LOG_TAG,
339                      "Starting VM process through Zygote failed");
340              throw new RuntimeException(
341                      "Starting VM process through Zygote failed", ex);
342          }
343      }

333调用startViaZygote

541      private Process.ProcessStartResult startViaZygote(@NonNull final String processClass,
542                                                        @Nullable final String niceName,
543                                                        final int uid, final int gid,
544                                                        @Nullable final int[] gids,
545                                                        int runtimeFlags, int mountExternal,
546                                                        int targetSdkVersion,
547                                                        @Nullable String seInfo,
548                                                        @NonNull String abi,
549                                                        @Nullable String instructionSet,
550                                                        @Nullable String appDataDir,
551                                                        @Nullable String invokeWith,
552                                                        boolean startChildZygote,
553                                                        @Nullable String packageName,
554                                                        boolean useUsapPool,
555                                                        @Nullable String[] extraArgs)
556                                                        throws ZygoteStartFailedEx {
...
635              return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi),
636                                                useUsapPool,
637                                                argsForZygote);
638          }
639      }

核心方法635zygoteSendArgsAndGetResult,和openZygoteSocketIfNeeded

905      @GuardedBy("mLock")
906      private ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx {
907          try {
908              attemptConnectionToPrimaryZygote();
909  
910              if (primaryZygoteState.matches(abi)) {
911                  return primaryZygoteState;
912              }
913  
914              if (mZygoteSecondarySocketAddress != null) {
915                  // The primary zygote didn't match. Try the secondary.
916                  attemptConnectionToSecondaryZygote();
917  
918                  if (secondaryZygoteState.matches(abi)) {
919                      return secondaryZygoteState;
920                  }
921              }
922          } catch (IOException ioe) {
923              throw new ZygoteStartFailedEx("Error connecting to zygote", ioe);
924          }
925  
926          throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);
927      }

调用attemptConnectionToPrimaryZygote方法向Zygote发起请求

380      @GuardedBy("mLock")
381      private Process.ProcessStartResult zygoteSendArgsAndGetResult(
382              ZygoteState zygoteState, boolean useUsapPool, @NonNull ArrayList<String> args){
...
419          return attemptZygoteSendArgsAndGetResult(zygoteState, msgStr);
420      }

调用attemptZygoteSendArgsAndGetResult

451      private Process.ProcessStartResult attemptUsapSendArgsAndGetResult(
452              ZygoteState zygoteState, String msgStr)
453              throws ZygoteStartFailedEx, IOException {
454          try (LocalSocket usapSessionSocket = zygoteState.getUsapSessionSocket()) {
455              final BufferedWriter usapWriter =
456                      new BufferedWriter(
457                              new OutputStreamWriter(usapSessionSocket.getOutputStream()),
458                              Zygote.SOCKET_BUFFER_SIZE);
459              final DataInputStream usapReader =
460                      new DataInputStream(usapSessionSocket.getInputStream());
461  
462              usapWriter.write(msgStr);
463              usapWriter.flush();
464  
465              Process.ProcessStartResult result = new Process.ProcessStartResult();
466              result.pid = usapReader.readInt();
467              // USAPs can't be used to spawn processes that need wrappers.
468              result.usingWrapper = false;
469  
470              if (result.pid >= 0) {
471                  return result;
472              } else {
473                  throw new ZygoteStartFailedEx("USAP specialization failed");
474              }
475          }
476      }

这个方法中通过 socket 向 Zygote 进程发送参数列表,然后进入“阻塞等待”状态,直到 socket 服务端发送回来新创建的进程 pid。Zygote 进程源码的最后调用到了 ActivityThread.main() 方法。

大致调用流程图

请添加图片描述

23.小结

ActivityThread

public final class ActivityThread extends ClientTransactionHandler {
 
    ...
 
    public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
 
        // Install selective syscall interception
        AndroidOs.install();
 
        // CloseGuard defaults to true and can be quite spammy.  We
        // disable it here, but selectively enable it later (via
        // StrictMode) on debug builds, but using DropBox, not logs.
        CloseGuard.setEnabled(false);
 
        Environment.initForCurrentUser();
 
        // Make sure TrustedCertificateStore looks in the right place for CA certificates
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);
 
        Process.setArgV0("<pre-initialized>");
 
        Looper.prepareMainLooper();   //开启looper
 
        // Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
        // It will be in the format "seq=114"
        long startSeq = 0;
        if (args != null) {
            for (int i = args.length - 1; i >= 0; --i) {
                if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
                    startSeq = Long.parseLong(
                            args[i].substring(PROC_START_SEQ_IDENT.length()));
                }
            }
        }
        ActivityThread thread = new ActivityThread();    
        thread.attach(false, startSeq); //初始化ActivityThread并且attach到系统进程
 
        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }
 
        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }
 
        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();
 
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }
 
    ...
 
}

查看attach方法

@UnsupportedAppUsage
private void attach(boolean system, long startSeq) {
    sCurrentActivityThread = this;
    mSystemThread = system;
    if (!system) {
        android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
                                                UserHandle.myUserId());
        RuntimeInit.setApplicationObject(mAppThread.asBinder());
        final IActivityManager mgr = ActivityManager.getService();    
        try {
            mgr.attachApplication(mAppThread, startSeq);    // 通过 ActivityManagerService 的 attachApplication 方法绑定一个 Application
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
        ...
 
    } else {
        ...
    }
 
    ...
 
    ViewRootImpl.addConfigCallback(configChangedCallback);
}
  final ApplicationThread mAppThread = new ApplicationThread();

ActivityManagerService

5180      public final void attachApplication(IApplicationThread thread, long startSeq) {
5181          if (thread == null) {
5182              throw new SecurityException("Invalid application interface");
5183          }
5184          synchronized (this) {
5185              int callingPid = Binder.getCallingPid();
5186              final int callingUid = Binder.getCallingUid();
5187              final long origId = Binder.clearCallingIdentity();
5188              attachApplicationLocked(thread, callingPid, callingUid, startSeq);
5189              Binder.restoreCallingIdentity(origId);
5190          }
5191      }

调用attachApplicationLocked

  @GuardedBy("this")
4767      private boolean attachApplicationLocked(@NonNull IApplicationThread thread,
4768              int pid, int callingUid, long startSeq) {
4769  
...
5102          boolean badApp = false;
5103          boolean didSomething = false;
5104  
5105          // See if the top visible activity is waiting to run in this process...
5106          if (normalMode) {
5107              try {
5108                  didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
5109              } catch (Exception e) {
5110                  Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
5111                  badApp = true;
5112              }
5113          }
5114  
5115          // Find any services that should be running in this process...
5116          if (!badApp) {
5117              try {
5118                  didSomething |= mServices.attachApplicationLocked(app, processName);
5119                  checkTime(startTime, "attachApplicationLocked: after mServices.attachApplicationLocked");
5120              } catch (Exception e) {
5121                  Slog.wtf(TAG, "Exception thrown starting services in " + app, e);
5122                  badApp = true;
5123              }
5124          }
5125  
5126          // Check if a next-broadcast receiver is in this process...
5127          if (!badApp && isPendingBroadcastProcessLocked(pid)) {
5128              try {
5129                  didSomething |= sendPendingBroadcastsLocked(app);
5130                  checkTime(startTime, "attachApplicationLocked: after sendPendingBroadcastsLocked");
5131              } catch (Exception e) {
5132                  // If the app died trying to launch the receiver we declare it 'bad'
5133                  Slog.wtf(TAG, "Exception thrown dispatching broadcasts in " + app, e);
5134                  badApp = true;
5135              }
5136          }
...
5176          return true;
5177      }

5106,5116,5127分别是对Activity,services,BroadcastReceiver的处理判断。5106调用了mAtmInternal.attachApplication

public ActivityTaskManagerInternal mAtmInternal;

查看ActivityTaskManagerInternal

public abstract class ActivityTaskManagerInternal {
    
  public abstract boolean attachApplication(WindowProcessController wpc) throws RemoteException;   
}

attachApplication是它的抽象方法

而 ActivityTaskManagerInternal 的实现类是 ActivityTaskManagerService 中的内部类 LocalService 继承了此抽象方法:

public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
    
      final class LocalService extends ActivityTaskManagerInternal {
6867          public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6868              synchronized (mGlobalLockWithoutBoost) {
6869                  return mRootActivityContainer.attachApplication(wpc);
6870              }
6871          }
      }
}

其返回了mRootActivityContainer.attachApplication

RootActivityContainer mRootActivityContainer;

RootActivityContainer

再次回到RootActivityContainer

768      boolean attachApplication(WindowProcessController app) throws RemoteException {
769          final String processName = app.mName;
770          boolean didSomething = false;
771          for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
772              final ActivityDisplay display = mActivityDisplays.get(displayNdx);
773              final ActivityStack stack = display.getFocusedStack();
774              if (stack != null) {
775                  stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList);
776                  final ActivityRecord top = stack.topRunningActivityLocked();
777                  final int size = mTmpActivityList.size();
778                  for (int i = 0; i < size; i++) {
779                      final ActivityRecord activity = mTmpActivityList.get(i);
780                      if (activity.app == null && app.mUid == activity.info.applicationInfo.uid
781                              && processName.equals(activity.processName)) {
782                          try {
783                              if (mStackSupervisor.realStartActivityLocked(activity, app,
784                                      top == activity /* andResume */, true /* checkConfig */)) {
785                                  didSomething = true;
786                              }
787                          } catch (RemoteException e) {
788                              Slog.w(TAG, "Exception in new application when starting activity "
789                                      + top.intent.getComponent().flattenToShortString(), e);
790                              throw e;
791                          }
792                      }
793                  }
794              }
795          }
796          if (!didSomething) {
797              ensureActivitiesVisible(null, 0, false /* preserve_windows */);
798          }
799          return didSomething;
800      }
801  

783核心调用mStackSupervisor.realStartActivityLocked

ActivityStackSupervisor mStackSupervisor;

ActivityStackSupervisor

705      boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
706              boolean andResume, boolean checkConfig) throws RemoteException {
...
853                  mService.getLifecycleManager().scheduleTransaction(clientTransaction);
...
921          }
922  

调用mService.getLifecycleManager().scheduleTransaction这里的 mService 是 ActivityTaskManagerService。而

getLifecycleManager 方法获取到的是 ClientLifecycleManager。又再次回到了 ClientLifecycleManager 的 scheduleTransaction 方法了。最终走到Activity的生命周期

24.总结

  1. 当在桌面点击 App 图标后,会调用 startActivity 转而调用 startActivityForResult,接着调用 Instrumentation 的 execStartActivity 方法。
  2. 通过 AIDL 调用到 ActivityTaskManagerService 的 startActivity以及 startActivityAsUser,最终会调用到 ActivityStarter 。
  3. ActivityStarter 中会调用到 execute 方法接着调用 startActivityUnchecked,此方法中调用 RootActivityContainer。这个类是暂时用来分担 ActivityStackSupervisor 的部分职责的。RootActivityContainer 会调用到 ActivityStack。
  4. ActivityStack 会先去判断是否有 Activity 处于 Resume 状态,有的话会先调用 startPausingLocked 方法让 Activity 执行 onPause 过程。
  5. ActivityStack 的 startPausingLocked执行之后。会调用ActivityStackSupervisor 中 的 startSpecificActivityLocked。
  6. ActivityStackSupervisor 先判断进程是否存在,当进程不存在时候,则调用 ActivityTaskManagerService 的 sendMessage,最终调用 ActivityManagerService 的 startProcessLocked。
  7. ActivityManagerService 中通过 socket 的方式去通知 Zygote 进程 fork 一个新的进程,当进程创建完毕后,会寻找子进程的 main 方法,也就是新进程 ActivityThread 中的 main 方法。
  8. 在 ActivityThread 的 main 方法中会去创建 Looper 并且执行 loop 方法以及调用了 attach 方法。attach 方法中调用 ActivityManagerService 的 attachApplication 方法。
  9. ActivityManagerService 的 attachApplication 中首先会调用 ApplicationThread 的 bindApplication 方法。ApplicationThread 是 ActivityThread 的一个内部类。在 bindApplication 中发送消息给 ActivityThread 的 H 类,调用 handleBindApplication 方法。
  10. handleBindApplication 方法创建 application,并且调用 callApplicationOnCreate,执行 Application 的 onCreate 方法。
  11. ActivityManagerService 中会调用 ActivityTaskManagerInternal 的 attachApplication,最终调用的是 ActivityTaskManagerService 的内部类 LocalService 的 attachApplication。
  12. 接着调用到 ActivityStackSupervisor 的 realStartActivityLocked,经过一系列的调用后执行到 ActivityThread 的 handleLaunchActivity,最终调用到 Activity 的 onCreate 方法。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值