Activity 的启动流程(Android 13)

avatar
作者
猴君
阅读量:0

Activity 的启动过程分为两种:一种是普通 Activity 的启动过程,另一种是根 Activity 的启动过程。普通 Activity 指的是除应用程序启动的第一个 Activity 之外的其他 Activity。根 Activity 指的是应用程序启动的第一个 Activity,因此,根 Activity 的启动过程一般情况下也可以理解为应用程序的启动过程。

1 普通 Activity 的启动流程

普通 Activity 的启动流程比较复杂,比如用 Activity A 打开 Activity B,这一过程开始于 A.startActivity(Intent) 经过 system_server 进程的处理,最终调用 B.finish() 结束生命周期。

普通 Activity 的启动流程可以分为以下 3 部分:

  • Activity 请求 ActivityTaskManagerService(ATMS) 的过程
  • ATMS 到 ApplicationThread 的调用过程
  • ActivityThread 启动 Activity;
1.1 Activity 请求 ActivityTaskManagerService(ATMS) 的过程

以下是 Activity 请求 ATMS 的时序图:

Activity 启动时序图_1

Instrumentation 负责调用 Activity 和 Application 的生命周期,具有跟踪 Application 和 Activity 生命周期的功能。 以下是 Instrumentation.execStartActivity 方法的相关源码:

public class Instrumentation {     public ActivityResult execStartActivity(           Context who, IBinder contextThread, IBinder token, Activity target,           Intent intent, int requestCode, Bundle options) {         ......         try {             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); // 1             ...         } catch (RemoteException e) {            .....         }         return null;     } } 

注释 1 处调用了 ActivityTaskManager.getService() 方法来获取 ATMS 的代理对象,接着调用了它的 startActivity 方法。以下是 ActivityTaskManager.getService() 的相关源码:

@SystemService(Context.ACTIVITY_TASK_SERVICE) public class ActivityTaskManager {      public static IActivityTaskManager getService() {         return IActivityTaskManagerSingleton.get();     }      private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton =             new Singleton<IActivityTaskManager>() {                 @Override                 protected IActivityTaskManager create() {                     final IBinder b =                        	ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE); // 1                     return IActivityTaskManager.Stub.asInterface(b); // 2                 }             };   }  // /frameworks/base/core/java/android/content/Context.java public abstract class Context {   	public static final String ACTIVITY_TASK_SERVICE = "activity_task"; } 

ActivityTaskManager:是实现 Activity 与 ATMS 跨进程交互的接口,ATMS 的辅助类。

从上述代码中可知,ActivityTaskManager.getService() 调用了 IActivityTaskManagerSingleton.get() 方法,IActivityTaskManagerSingleton 是一个 Singleton 类。注释 1 处得到一个名为 “activity_task” 的 Service 的引用,也就是 IBinder 类型的 ATMS 的引用。

在注释 2 处将它转换成 IActivityTaskManager 类型的对象,这段代码采用的 AIDL,IActivityManager.java 类是由 AIDL 工具在编译时自动生成的,IActivityTaskManager.aidl 的文件路径为 /frameworks/base/core/java/android/app/IActivityTaskManager.aidl。要实现进程间通信,服务器端也就是 ATMS 只需要继承 IActivityTaskManager.Stub 类并实现相应的方法就可以了。IActivityTaskManager 是 ATMS 在本地的代理。

以下是相关相关源码:

interface IActivityTaskManager {     int startActivity(in IApplicationThread caller, in String callingPackage,             in String callingFeatureId, in Intent intent, in String resolvedType,             in IBinder resultTo, in String resultWho, int requestCode,             int flags, in ProfilerInfo profilerInfo, in Bundle options);   	...... }  /**  * System service for managing activities and their containers(task, displays, ...)  *   */ public class ActivityTaskManagerService extends IActivityTaskManager.Stub {     @Override     public final int startActivity(IApplicationThread caller, String callingPackage,           String callingFeatureId, Intent intent, String resolvedType,            IBinder resultTo, String resultWho, int requestCode, int startFlags,                                     ProfilerInfo profilerInfo, Bundle bOptions) {       return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, 	                                  resolvedType, resultTo, resultWho, requestCode,                                   startFlags, profilerInfo, bOptions,                                  UserHandle.getCallingUserId());     } } 

ActivityTaskManagerService:是管理 Activity 以及其容器(task、stacks、displays)的系统服务,负责 Activity 管理和调度工作(Android 10 中新增)。ATMS 是 AMS 的一个辅助类,分担了 AMS 的一部分功能,继承自 IActivityTaskManager.Stub。

1.2 ATMS 到 ApplicationThread 的调用过程

Activity 请求 ATMS 后,代码逻辑就就进入到 ATMS 中,接着就是 ATMS 到 ApplicationThread 的调用流程,时序图如下所示:

Activity 启动时序图_2

ATMS.startActivity 方法会调用其 startActivityAsUser 方法,在 ATMS.startActivityAsUser 方法中会调用 ATMS.getActivityStartController() 方法获取 ActivityStartController 对象:

public class ActivityTaskManagerService extends IActivityTaskManager.Stub {   	private ActivityStartController mActivityStartController;      	ActivityStartController getActivityStartController() {         return mActivityStartController;     }      	private int startActivityAsUser(IApplicationThread caller, String callingPackage,             @Nullable String callingFeatureId, Intent intent, String resolvedType,             IBinder resultTo, String resultWho, int requestCode, int startFlags,             ProfilerInfo profilerInfo, Bundle bOptions, int userId,              boolean validateIncomingUser) {             	...                return getActivityStartController().obtainStarter(intent, "startActivityAsUser")                 .setCaller(caller)                 .setCallingPackage(callingPackage)                 .setCallingFeatureId(callingFeatureId)                 .setResolvedType(resolvedType)                 .setResultTo(resultTo)                 .setResultWho(resultWho)                 .setRequestCode(requestCode)                 .setStartFlags(startFlags)                 .setProfilerInfo(profilerInfo)                 .setActivityOptions(opts)                 .setUserId(userId)                 .execute();            } } 

ActivityStartController 是用于 Activity 启动的控制器。 通过调用其 obtainStarter 方法来获取 ActivityStarter 对象:

/**  * Controller for delegating activity launches.   * Activity 的启动的控制器  */ public class ActivityStartController {   	/**      * 返回一个启动器来配置和执行 Activity 的启动      */     ActivityStarter obtainStarter(Intent intent, String reason) {         return mFactory.obtain().setIntent(intent).setReason(reason);     }    } 

ActivityStarter 是 Android 7.0 中新加入的类,是 Activity 的控制器,讲如何启动一个 Activity,会收集所有的逻辑来决定如何将 Intent 和 Flags 转换为 Activity,并将 Activity 和 Task 以及 Stack 相关联。

/**  * Controller for interpreting how and then launching an activity.  *   * This class collects all the logic for determining how an intent and flags should be   * turned into an activity and associated task and root task.  */ class ActivityStarter {    } 

Task 就是用户在执行某项工作时与之相关联的 Activity 集合。系统通过任务栈来管理这些 Activity,它们按照打开的顺序进入任务栈中。这些 Activity 可以来自同一个 APP,也可以来自不同的 APP,Activity 之间不一定非要有关联。

当按 Home 键旁边的那个方形键(recent-apps)时,屏幕上展示的就是一个个的 Task。

/**  * {@link Task} is a TaskFragment that can contain a group of activities to perform a certain   * job.  Task 是 TaskFragment 的子类,可以包含执行某个任务的一组 activities。  *   * Activities of the same task affinities usually group in the same {@link Task}.   * 具有相同的 task affinities 的 activities 通常分在同一个 Task 中  *   * A {@link Task} can also be an entity that showing in the Recents Screen for a job that   * user interacted with.  * 按下 Home 键旁边的那个方形键(recent-apps)时,屏幕上展示的就是一个个的 Task  *   * A {@link Task} can also contain other {@link Task}s.  * 一个 Task 也可以包含其他的 Task  */ class Task extends TaskFragment {    }  /**  * A basic container that can be used to contain activities or other {@link TaskFragment},   * which also able to manage the activity lifecycle and updates the visibilities of the   * activities in it.  * 一个容器,可以用来放 activities 或者其它的 TaskFragment,也能够管理 activity 的生命周期或者更新  * activities 的可见性。  */ class TaskFragment extends WindowContainer<WindowContainer> {    } 

task affinity:在 manifest 文件中,注册 activity 时如果不申明 taskAffinity 属性,就是 APP 程序的默认包名,默认情况下,一个 APP 中所有的 Activity 都在一个 Task 中:

<activity 		android:taskAffinity="" 		... /> 

启动根 Activity 时会将 Intent 的 Flag 设置为 FLAG_ACTIVITY_NEW_TASK,表示要创建一个新的 Task:

class ActivityStarter {   	private Task mTargetRootTask;   	private final RootWindowContainer mRootWindowContainer;   	     private Task computeTargetTask() {       if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask               && (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) { // 1           // A new task should be created instead of using existing one.           return null;       } else if (mSourceRecord != null) {           return mSourceRecord.getTask();       } else if (mInTask != null) {           if (!mInTask.isAttached()) {               getOrCreateRootTask(mStartActivity, mLaunchFlags, mInTask, mOptions);           }           return mInTask;       } else {           final Task rootTask = getOrCreateRootTask(mStartActivity, mLaunchFlags,                                                      null /* task */, mOptions);           final ActivityRecord top = rootTask.getTopNonFinishingActivity();           if (top != null) {               return top.getTask();           } else {               rootTask.removeIfPossible("computeTargetTask");           }       }       return null;     }      private void setNewTask(Task taskToAffiliate) {         final boolean toTop = !mLaunchTaskBehind && !mAvoidMoveToFront;         final Task task = mTargetRootTask.reuseOrCreateTask(                 mStartActivity.info, mIntent, mVoiceSession,                 mVoiceInteractor, toTop, mStartActivity, mSourceRecord, mOptions);         task.mTransitionController.collectExistenceChange(task);         addOrReparentStartingActivity(task, "setTaskFromReuseOrCreateNewTask");          ProtoLog.v(WM_DEBUG_TASKS, "Starting new activity %s in new task %s",                 mStartActivity, mStartActivity.getTask());          if (taskToAffiliate != null) {             mStartActivity.setTaskToAffiliateWith(taskToAffiliate);         }     }       int startActivityInner(final ActivityRecord r, ActivityRecord sourceRecord,             IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,             int startFlags, boolean doResume, ActivityOptions options, Task inTask,             TaskFragment inTaskFragment, @BalCode int balCode,             NeededUriGrants intentGrants) {         ...          // Compute if there is an existing task that should be used for.         final Task targetTask = reusedTask != null ? reusedTask : computeTargetTask(); // 2         final boolean newTask = targetTask == null; // 3         mTargetTask = targetTask;          ...         if (newTask) { // 4             final Task taskToAffiliate = (mLaunchTaskBehind && mSourceRecord != null)                     ? mSourceRecord.getTask() : null;             setNewTask(taskToAffiliate); // 5         } else if (mAddingToTask) {             addOrReparentStartingActivity(targetTask, "adding to task");         }          ...          final boolean isTaskSwitch = startedTask != prevTopTask && !startedTask.isEmbedded();         mTargetRootTask.startActivityLocked(mStartActivity, topRootTask, newTask,                                              isTaskSwitch, mOptions, sourceRecord); // 6         if (mDoResume) {             ...             } else {                 ...                 mRootWindowContainer.resumeFocusedTasksTopActivities(                         mTargetRootTask, mStartActivity, mOptions, mTransientLaunch); // 7             }         }         ...          return START_SUCCESS;     }    } 

如果注释 4 处的条件满足,表示需要创建一个新的 Task。在注释 6 处调用的是 Task.startActivityLocked 方法,注释 7 处调用的是 RootWindowContainer.resumeFocusedTasksTopActivities 方法。

RootWindowContainer 表示窗口容器的根容器,是整个屏幕最顶层的容器。

/**   * Root {@link WindowContainer} for the device.   * 设备的根  */ class RootWindowContainer extends WindowContainer<DisplayContent>         implements DisplayManager.DisplayListener {    } 

ActivityRecord:记录 Activity 的信息;TaskRecord:记录 Task 的信息;ActivityStack:栈信息;

class Task extends TaskFragment {        private boolean resumeTopActivityInnerLocked(ActivityRecord prev,                                         ActivityOptions options, boolean deferPause) {         ...  				// 1         final ActivityRecord topActivity = topRunningActivity(true /* focusableOnly */);          if (topActivity == null) {             // There are no activities left in this task, let's look somewhere else.             return resumeNextFocusableActivityWhenRootTaskIsEmpty(prev, options);         }          final boolean[] resumed = new boolean[1];         final TaskFragment topFragment = topActivity.getTaskFragment();         resumed[0] = topFragment.resumeTopActivity(prev, options, deferPause);         ...         return resumed[0];     }    	     ActivityRecord topRunningActivity(IBinder token, int taskId) {         final PooledPredicate p = PooledLambda.obtainPredicate(Task::isTopRunning,                 PooledLambda.__(ActivityRecord.class), taskId, token);         final ActivityRecord r = getActivity(p);         p.recycle();         return r;     }    } 

注释 1 处调用 topRunningActivity 方法获取栈顶不是处于停止状态的 ActivityRecord,此处的栈指的是要启动的 Activity 所在的栈。

从注释上来看,ActivityTaskSupervisor,翻译过来是“活动任务主管”,从注释中可以看出,这个类已经变成了垃圾倾倒场,页面层级相关的代码移动到 RootWindowContainer 中,与 Activity 生命周期相关的移动到 ActivityLifeCycler 中,接口相关的代码移动到 ATMS 中,等等。

从功能上来看,可以理解成 ActivityTaskSupervisor 是用来辅助 ATMS 来对 Activity 和 Task 进行管理的。

// TODO: This class has become a dumping ground. Let's // 这个类已经变成了垃圾请倒场 // - Move things relating to the hierarchy to RootWindowContainer // - 把与层级相关的代码移动到 RootWindowContainer 中 // - Move things relating to activity life cycles to maybe a new class called ActivityLifeCycler // - 与 Activity 生命周期相关的代码移动到 ActivityLifeCycler 中 // - Move interface things to ActivityTaskManagerService. // - 接口相关的移动到 ActivityTaskManagerService 中 // - All other little things to other files. public class ActivityTaskSupervisor implements RecentTasks.Callbacks {     final ActivityTaskManagerService mService;      void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {         // 1 Is this activity's application already running?         final WindowProcessController wpc =                 mService.getProcessController(r.processName, r.info.applicationInfo.uid);          boolean knownToBeDead = false;         if (wpc != null && wpc.hasThread()) {             try {                 realStartActivityLocked(r, wpc, andResume, checkConfig); // 2                 return;             } catch (RemoteException e) {                 Slog.w(TAG, "Exception when starting activity "                         + r.intent.getComponent().flattenToShortString(), e);             }              ...         }          r.notifyUnknownVisibilityLaunchedForKeyguardTransition();          final boolean isTop = andResume && r.isTopRunningActivity();         mService.startProcessAsync(r, knownToBeDead, isTop,                 isTop ? HostingRecord.HOSTING_TYPE_TOP_ACTIVITY                         : HostingRecord.HOSTING_TYPE_ACTIVITY); // 3     } } 

注释 1 处的来判断当前的 Activity 所在的应用程序进程是否存在,如果存在则调用注释 2 处的 realStartActivityLocked 方法继续 Activity 的启动流程,如果不存在在调用注释 3 处 ATMS.startProcessAsync 方法创建进程。

/**  * The Activity Manager (AM) package manages the lifecycle of processes in the system through  * ProcessRecord. Activity Manager(AM)包通过 ProcessRecord 来管理系统中进程的生命周期  *   * However, it is important for the Window Manager (WM) package to be aware  * of the processes and their state since it affects how WM manages windows and activities.   * 但是,对于 Window Manager(WM)包来说,了解进程以及其状态是十分重要的,因为它会影响 Window Manager 管  * 理 windows 和 activities 的方式   *   * This class that allows the ProcessRecord object in the AM package to communicate important  * changes to its state to the WM package in a structured way.   * 这个类允许 ProcessRecord 对象以结构化的方式将其状态的重要改变传到给 WM 包  *   * WM package also uses {@link WindowProcessListener} to request changes to the process state   * on the AM side.  * WM 包也使用 WindowProcessListener 来请求更改 AM 端的进程状态  *   * Note that public calls into this class are assumed to be originating from outside the  * window manager so the window manager lock is held and appropriate permissions are checked   * before calls are allowed to proceed.  * 请注意,假定对该类的公共调用来自窗口管理器的外部,因此将该持有窗口管理器锁,并在允许调用继续进行之前检查适当  * 的权限。  */ public class WindowProcessController extends ConfigurationContainer<ConfigurationContainer>         implements ConfigurationContainerListener {      	private IApplicationThread mThread;   	   	IApplicationThread getThread() {         return mThread;     }      boolean hasThread() {         return mThread != null;     }    } 

Activity 启动时序图_3

在 ActivityTaskSupervisor.realStartActivityLocked 方法中会调用 mService.getLifecycleManager().scheduleTransaction(clientTransaction);,这里的 mService 是 ATMS。

在 ActivityTaskManagerService 中初始化了 ClientLifecycleManager(客户端事务管理类)的唯一实例,因此,所有的有关事务的操作都必须通过 ATMS 实例来发起。 以下是 ATMS 中的 ClientLifecycleManager 的相关初始化与获取操作:

public class ActivityTaskManagerService extends IActivityTaskManager.Stub {      	private final ClientLifecycleManager mLifecycleManager;      	public ActivityTaskManagerService(Context context) {       	...       	mLifecycleManager = new ClientLifecycleManager();       	...     }        ClientLifecycleManager getLifecycleManager() {         return mLifecycleManager;     } }  public class ActivityTaskSupervisor implements RecentTasks.Callbacks {     final ActivityTaskManagerService mService;      boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,                   boolean andResume, boolean checkConfig) throws RemoteException {        	...         // Create activity launch transaction.         final ClientTransaction clientTransaction = ClientTransaction.obtain(         proc.getThread(), r.token);          final boolean isTransitionForward = r.isTransitionForward();         final IBinder fragmentToken = r.getTaskFragment().getFragmentToken();         // 注意:LaunchActivityItem         clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),               System.identityHashCode(r), r.info,               // TODO: Have this take the merged configuration instead of separate global               // and override configs.               mergedConfiguration.getGlobalConfiguration(),               mergedConfiguration.getOverrideConfiguration(), r.compat,               r.getFilteredReferrer(r.launchedFromPackage), task.voiceInteractor,               proc.getReportedProcState(), r.getSavedState(), r.getPersistentSavedState(),               results, newIntents, r.takeOptions(), isTransitionForward,               proc.createProfilerInfoIfNeeded(), r.assistToken, activityClientController,               r.shareableActivityToken, r.getLaunchedFromBubble(), fragmentToken));          ...         mService.getLifecycleManager().scheduleTransaction(clientTransaction); // 2      } } 

ClientLifecycleManager:客户端事务管理类,能够组合多个客户端生命周期转换事务的请求和/或回调,并把它们作为单个事务执行。

/**   * Class that is able to combine multiple client lifecycle transition requests    * and/or callbacks, and execute them as a single transaction.   *    * 客户端事务管理类,能够组合多个客户端生命周期转换事务的请求和/或回调,并把它们作为单个事务执行   *    * @see ClientTransaction   */ class ClientLifecycleManager {         /**      * Schedule a transaction, which may consist of multiple callbacks and a lifecycle       * request.       * 调度一个事务,它可能由多个回调和一个生命周期请求组成      *      * @see ClientTransaction      */     void scheduleTransaction(ClientTransaction transaction) throws RemoteException { // 1         final IApplicationThread client = transaction.getClient();         transaction.schedule(); // 2         if (!(client instanceof Binder)) {             transaction.recycle();         }     }   	   	/**      * Schedule a single lifecycle request or callback to client activity.      *       * @param client Target client.      * @param activityToken Target activity token.      * @param stateRequest A request to move target activity to a desired lifecycle state.      * @throws RemoteException      *      * @see ClientTransactionItem      */     void scheduleTransaction(@NonNull IApplicationThread client,                               @NonNull IBinder activityToken,             @NonNull ActivityLifecycleItem stateRequest) throws RemoteException { // 3         final ClientTransaction clientTransaction = transactionWithState(           	                 client, activityToken, stateRequest);         scheduleTransaction(clientTransaction);     }      /**      * Schedule a single callback delivery to client activity.      * @param client Target client.      * @param activityToken Target activity token.      * @param callback A request to deliver a callback.      * @throws RemoteException      *      * @see ClientTransactionItem      */     void scheduleTransaction(@NonNull IApplicationThread client,                              @NonNull IBinder activityToken,             @NonNull ClientTransactionItem callback) throws RemoteException { // 4         final ClientTransaction clientTransaction = transactionWithCallback(           					client, activityToken, callback);         scheduleTransaction(clientTransaction);     }      /**      * Schedule a single callback delivery to client application.      * @param client Target client.      * @param callback A request to deliver a callback.      * @throws RemoteException      *      * @see ClientTransactionItem      */     void scheduleTransaction(@NonNull IApplicationThread client,             @NonNull ClientTransactionItem callback) throws RemoteException { // 5         final ClientTransaction clientTransaction = transactionWithCallback(client,                 null /* activityToken */, callback);         scheduleTransaction(clientTransaction);     }      /**      * @return A new instance of {@link ClientTransaction} with a single lifecycle state       * request.      *      * @see ClientTransaction      * @see ClientTransactionItem      */     private static ClientTransaction transactionWithState(@NonNull IApplicationThread client,           @NonNull IBinder activityToken, @NonNull ActivityLifecycleItem stateRequest) { // 6         final ClientTransaction clientTransaction = ClientTransaction.obtain(                                      client, activityToken);         clientTransaction.setLifecycleStateRequest(stateRequest);         return clientTransaction;     }      /**      * @return A new instance of {@link ClientTransaction} with a single callback invocation.      *      * @see ClientTransaction      * @see ClientTransactionItem      */     private static ClientTransaction transactionWithCallback(       			@NonNull IApplicationThread client,             IBinder activityToken, @NonNull ClientTransactionItem callback) { // 7         final ClientTransaction clientTransaction = ClientTransaction.obtain(                                        client, activityToken);         clientTransaction.addCallback(callback);         return clientTransaction;     } } 

从上面的代码中可以看出,ClientLifecycleManager 对外暴露了 3 种事务调度的方法,一是直接调度客户端事务集 ClientTransaction(注释 1),二是调度生命周期事务 ActivityLifecycleItem(注释 3),三是调度客户端事务 ClientTransactionItem(注释 4),实际上无论是生命周期事务 ActivityLifecycleItem 还是客户端事务 ClientTransactionItem 都被封装成 ClientTransaction 客户端事务集的形式,因此,这个类中的核心方法就是 scheduleTransaction(ClientTransaction) ,在这个方法中传入 ClientTransation 类型的参数并调用它的 schedule() 方法做进一步处理(注释 2)。

ClientTransaction 事务类集,一个事务集可以存放一系列的事务(ClientTransactionItem)以及一个生命周期事务(ActivityLifecycleItem)。

public class ClientTransaction implements Parcelable, ObjectPoolItem {      /** A list of individual callbacks to a client. */     @UnsupportedAppUsage     private List<ClientTransactionItem> mActivityCallbacks; // 1      /**      * Final lifecycle state in which the client activity should be after the transaction is      * executed.      */     private ActivityLifecycleItem mLifecycleStateRequest; // 2      /** Target client. */     private IApplicationThread mClient;      /** Get the target client of the transaction. */     public IApplicationThread getClient() {         return mClient;     }      /**      * Add a message to the end of the sequence of callbacks.      * @param activityCallback A single message that can contain a lifecycle       * request/callback.      */     public void addCallback(ClientTransactionItem activityCallback) {         if (mActivityCallbacks == null) {             mActivityCallbacks = new ArrayList<>();         }         mActivityCallbacks.add(activityCallback);     }      	public void schedule() throws RemoteException {         mClient.scheduleTransaction(this);     }   	   	... } 

ClientTransactionItem 客户端事务,是一个抽象类,ActivityLifecycleItem 是它的一个子类:

public abstract class ClientTransactionItem implements BaseClientRequest, Parcelable {    /** Get the state that must follow this callback. */   @LifecycleState   public int getPostExecutionState() {       return UNDEFINED;   }    // Parcelable   @Override   public int describeContents() {       return 0;   } }  /**  * Request to launch an activity.  * @hide  */ public class LaunchActivityItem extends ClientTransactionItem { }  public abstract class ActivityTransactionItem extends ClientTransactionItem { } public abstract class ActivityLifecycleItem extends ActivityTransactionItem { }  public class ResumeActivityItem extends ActivityLifecycleItem { } public class PauseActivityItem extends ActivityLifecycleItem { } public class StopActivityItem extends ActivityLifecycleItem { } public class DestroyActivityItem extends ActivityLifecycleItem { } public class ActivityRelaunchItem extends ActivityTransactionItem { } 

ActivityLifecycleItem 是 Activity 生命周期事务类,其子类有 ResumeActivityItem、PauseActivityItem、StopActivityItem、DestroyActivityItem,表示具体的 Activity 的生命周期转换事务。

LaunchActivityItem 请求启动一个 Activity,ActivityRelaunchItem 重启 Activity 的回调。

对于 ClientTransaction.schedule() 方法:

public class ClientTransaction implements Parcelable, ObjectPoolItem {     /** Target client. */     private IApplicationThread mClient; // 1      	public void schedule() throws RemoteException {         mClient.scheduleTransaction(this); // 2     }    } 

注释 1 处的 mClient 指的是 IApplicationThread,它的实现类是 ActivityThread 的内部类 ApplicationThread。ApplicationThread 继承了 IApplicationThread.Stub。当前代码运行在 ATMS 所在的进程(system_server)中,通过 IApplicationThread 与应用程序进程来进行 Binder 通信,换句话说 IApplicationThread 是 ATMS 所在的进程(system_server)和应用程序进程的通信桥梁。

1.3 ActivityThread 启动 Activity 的过程

Activity 启动时序图_4

目前的代码已经是运行在应用程序进程中了。

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

从注释 1 处可知,ApplicationThread 是 ActivityThread 的内部类,也是 IApplicationThread 的实现类。注释 2 处 调用了 ActivityThread.this.scheduleTransaction 方法。从注释 3 处可以知道 ActivityThread 是 ClientTransactionHandler 的实现类,ClientTransactionHandler.scheduleTransaction 方法如下所示:

/**   * Defines operations that a {@link android.app.servertransaction.ClientTransaction} or its    * items can perform on client.   * 定义了 ClientTransaction 或其 items 可以在客户端执行的操作   * @hide   */ public abstract class ClientTransactionHandler {        // Schedule phase related logic and handlers.      /** Prepare and schedule transaction for execution. */     void scheduleTransaction(ClientTransaction transaction) {         transaction.preExecute(this);         sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);     }      	abstract void sendMessage(int what, Object obj); } 

对于抽象方法 sendMessage,在 ActivityThread 中有实现:

public final class ActivityThread extends ClientTransactionHandler           implements ActivityThreadInternal {        final H mH = new H();        void sendMessage(int what, Object obj) {     		sendMessage(what, obj, 0, 0, false);      }      private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {         Message msg = Message.obtain();         msg.what = what;         msg.obj = obj;         msg.arg1 = arg1;         msg.arg2 = arg2;         if (async) {             msg.setAsynchronous(true);         }         mH.sendMessage(msg);     }    } 

最终调用的是 mH.sendMessage 方法,mH 是 H 类型的对象,H 是 ActivityThread 的内部类,也是 Handler 的子类:

public final class ActivityThread extends ClientTransactionHandler           implements ActivityThreadInternal {   	   	class H extends Handler { } } 

对于 ActivityThread.H.EXECUTE_TRANSACTION 消息的处理:

public final class ActivityThread extends ClientTransactionHandler           implements ActivityThreadInternal {   	   	class H extends Handler {          			public void handleMessage(Message msg) {             case EXECUTE_TRANSACTION:                 final ClientTransaction transaction = (ClientTransaction) msg.obj;                 mTransactionExecutor.execute(transaction); // 1                 if (isSystem()) {                     // Client transactions inside system process are recycled on the client side                     // instead of ClientLifecycleManager to avoid being cleared before this                     // message is handled.                     transaction.recycle();                 }                 // TODO(lifecycler): Recycle locally scheduled transactions.                 break;         } 	  } } 

注释 1 处调用了 TransactionExecutor.execute 方法。

ClientTransactionHandler:定义了客户端事务或其 Item 可以在客户端执行的操作,封装了 handleXXXActivity 方法,其实现类 ActivityThread 也会继承这些方法。

/**   * Defines operations that a {@link android.app.servertransaction.ClientTransaction} or its    * items can perform on client.   * 定义了 ClientTransaction 或其 items 可以在客户端执行的操作   * @hide   */ public abstract class ClientTransactionHandler {     public abstract Activity handleLaunchActivity(@NonNull ActivityClientRecord r,           PendingTransactionActions pendingActions, Intent customIntent);      /** Perform activity launch. */     public abstract Activity handleLaunchActivity(@NonNull ActivityClientRecord r,             PendingTransactionActions pendingActions, Intent customIntent);      /** Perform activity start. */     public abstract void handleStartActivity(@NonNull ActivityClientRecord r,             PendingTransactionActions pendingActions, ActivityOptions activityOptions);     /** Resume the activity. */     public abstract void handleResumeActivity(@NonNull ActivityClientRecord r,             boolean finalStateRequest, boolean isForward, String reason);      /** Pause the activity. */     public abstract void handlePauseActivity(@NonNull ActivityClientRecord r,              boolean finished, boolean userLeaving, int configChanges,              PendingTransactionActions pendingActions, String reason);      /** Stop the activity. */     public abstract void handleStopActivity(@NonNull ActivityClientRecord r,              int configChanges, PendingTransactionActions pendingActions,              boolean finalStateRequest, String reason);      public abstract void handleDestroyActivity(@NonNull ActivityClientRecord r,                   boolean finishing, int configChanges, boolean getNonConfigInstance,                   String reason);      public abstract void handleRelaunchActivity(@NonNull ActivityClientRecord r,                   PendingTransactionActions pendingActions); } 

TransactionExecutor:事务执行器,让事务按正确顺序执行的类。TransactionExecutor 持有 ClientTransactionHandler 对象,在其构造函数中作为参数传入,ClientTransactionHandler 才是任务的真正执行者。

/**   * Class that manages transaction execution in the correct order.   * @hide   */ public class TransactionExecutor {   	private ClientTransactionHandler mTransactionHandler;   	     /** Initialize an instance with transaction handler, that will execute all requested actions. */     public TransactionExecutor(ClientTransactionHandler clientTransactionHandler) {         mTransactionHandler = clientTransactionHandler;     }  } 

回到 TransactionExecutor.execute 方法中:

public class TransactionExecutor {        public void execute(ClientTransaction transaction) {        ...         executeCallbacks(transaction); // 1         executeLifecycleState(transaction);        ...     }        @VisibleForTesting     public void executeCallbacks(ClientTransaction transaction) {         final List<ClientTransactionItem> callbacks = transaction.getCallbacks();         if (callbacks == null || callbacks.isEmpty()) {             // No callbacks to execute, return early.             return;         }         ...          final int size = callbacks.size();         for (int i = 0; i < size; ++i) {             final ClientTransactionItem item = callbacks.get(i); // 2             ...             final int postExecutionState = item.getPostExecutionState();             final int closestPreExecutionState = mHelper.getClosestPreExecutionState(r,                     item.getPostExecutionState());             if (closestPreExecutionState != UNDEFINED) {                 cycleToPath(r, closestPreExecutionState, transaction);             }              item.execute(mTransactionHandler, token, mPendingActions); // 3             item.postExecute(mTransactionHandler, token, mPendingActions);             ...         }     } }  

注释 3 处调用了 ClientTransactionItem.execute 方法,对于启动一个 Activity,此处的 ClientTransactionItem 是其子类 LaunchActivityItem,请求启动一个 Activity。

/**  * Request to launch an activity.  * @hide  */ public class LaunchActivityItem extends ClientTransactionItem {    }  public abstract class ClientTransactionItem implements BaseClientRequest, Parcelable {    } 

BaseClientRequest:事务的抽象类,定义了 preExecute、execute、postExecute 三个接口,分别代表事务执行前、执行中、执行后三个阶段的回调方法。

public interface BaseClientRequest extends ObjectPoolItem {      /**      * Prepare the client request before scheduling.      * An example of this might be informing about pending updates for some values.      *      * @param client Target client handler.      * @param token  Target activity token.      */     default void preExecute(ClientTransactionHandler client, IBinder token) {     }      /**      * Execute the request.      * @param client Target client handler.      * @param token Target activity token.      * @param pendingActions Container that may have data pending to be used.      */     void execute(ClientTransactionHandler client, IBinder token,             PendingTransactionActions pendingActions);      /**      * Perform all actions that need to happen after execution, e.g. report the result to server.      * @param client Target client handler.      * @param token Target activity token.      * @param pendingActions Container that may have data pending to be used.      */     default void postExecute(ClientTransactionHandler client, IBinder token,             PendingTransactionActions pendingActions) {     } } 

LaunchActivityItem 重写了 execute 方法:

public class LaunchActivityItem extends ClientTransactionItem {     @Override     public void execute(ClientTransactionHandler client, IBinder token,             PendingTransactionActions pendingActions) {         Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");         ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,                 mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState,                  mPersistentState, mPendingResults, mPendingNewIntents, mActivityOptions,                  mIsForward, mProfilerInfo, client, mAssistToken, mShareableActivityToken,                  mLaunchedFromBubble, mTaskFragmentToken);         client.handleLaunchActivity(r, pendingActions, null /* customIntent */); // 1         Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);     }    } 

注释 1 处的 client 的类型是 ClientTransactionHandler,ActivityThread 继承了 ClientTransactionHandler,是事务的真正执行者。

public final class ActivityThread extends ClientTransactionHandler         implements ActivityThreadInternal {        @Override     public Activity handleLaunchActivity(ActivityClientRecord r,             PendingTransactionActions pendingActions, Intent customIntent) {         ...          final Activity a = performLaunchActivity(r, customIntent);          ...         return a;     }  } 

2 根 Activity 的启动过程

根 Activity 的启动流程可以分为以下 3 部分:

  • Launcher 请求 ActivityTaskManagerService(ATMS) 的过程
  • ATMS 到 ApplicationThread 的调用过程
  • ActivityThread 启动 Activity;
2.1 Launcher 请求 ATMS 过程

Launcher 启动后会将已安装的应用程序的快捷图标显示到桌面上,这些应用程序的快捷图标就是启动根 Activity 的入口。当我们点击某个应用题程序的快捷图标时,就会通过 Launcher 请求 ATMS 来启动应用程序。

以下是 Launcher 请求 ATMS 的时序图:

根Activity 启动时序图_1

点击应用程序的快捷图标时,就会调用 Launcher.startActivitySafely 方法:

// /packages/apps/Launcher3/src/com/android/launcher3/Launcher.java public class Launcher extends StatefulActivity<LauncherState>         implements LauncherExterns, Callbacks, InvariantDeviceProfile.OnIDPChangeListener,         PluginListener<LauncherOverlayPlugin> {                public boolean startActivitySafely(View v, Intent intent, ItemInfo item,                              @Nullable String sourceContainer) {         ...         boolean success = super.startActivitySafely(v, intent, item, sourceContainer); // 1         ...     }        }  public abstract class StatefulActivity<STATE_TYPE extends BaseState<STATE_TYPE>>         extends BaseDraggingActivity {    }  public abstract class BaseDraggingActivity extends BaseActivity         implements OnColorsChangedListener, DisplayInfoChangeListener {    }  public abstract class BaseActivity extends Activity implements ActivityContext {    } 

注释 1 处调用的是 super.startActivitySafely 方法,这里的 super,由继承关系可以知道调用的是 ActivityContext.startActivitySafely 方法:

// packages/apps/Launcher3/src/com/android/launcher3/views/ActivityContext.java public interface ActivityContext {        default boolean startActivitySafely(View v, Intent intent, @Nullable ItemInfo item) {         ...          // Prepare intent         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // 1         if (v != null) {             intent.setSourceBounds(Utilities.getViewBounds(v));         }         try {             boolean isShortcut = (item instanceof WorkspaceItemInfo)                     && (item.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT                     || item.itemType == LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT)                     && !((WorkspaceItemInfo) item).isPromise();             if (isShortcut) {                 // Shortcuts need some special checks due to legacy reasons.                 startShortcutIntentSafely(intent, optsBundle, item);             } else if (user == null || user.equals(Process.myUserHandle())) {                 // Could be launching some bookkeeping activity                 context.startActivity(intent, optsBundle); // 2             } else {                 context.getSystemService(LauncherApps.class).startMainActivity(                         intent.getComponent(), user, intent.getSourceBounds(), optsBundle);             }             ...             return true;         } catch (NullPointerException | ActivityNotFoundException | SecurityException e) {             ...         }         return false;     } } 

注释 1 处将 Flag 设置为 Intent.FLAG_ACTIVITY_NEW_TASK,这样根 Activity 会在新的任务栈中启动,在注释 2 处调用了 Context.startActivity 方法,Context 是抽象类,其中定义了抽象方法 startActivity,在其子类 Activity 中实现:

// frameworks/base/core/java/android/content/Context.java public abstract class Context {   	public abstract void startActivity(@RequiresPermission Intent intent,             @Nullable Bundle options);  }  // frameworks/base/core/java/android/content/ContextWrapper.java public class ContextWrapper extends Context {   	 }  // frameworks/base/core/java/android/content/ContextWrapper.java public class ContextThemeWrapper extends ContextWrapper {    }  // frameworks/base/core/java/android/app/Activity.java public class Activity extends ContextThemeWrapper         implements LayoutInflater.Factory2,         Window.Callback, KeyEvent.Callback,         OnCreateContextMenuListener, ComponentCallbacks2,         Window.OnWindowDismissedCallback,         ContentCaptureManager.ContentCaptureClient {                @Override     public void startActivity(Intent intent, @Nullable Bundle options) {         getAutofillClientController().onStartActivity(intent, mIntent);         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);         }     }            } 
2.2 ATMS 到 ApplicationThread 的调用过程

Launcher 请求 ATMS 后,代码逻辑已经进入到 ATMS 中,接着是 ATMS 到 ApplicationThread 的调用流程:

Activity 启动时序图_2

ActivityStackSupervisor.startSpecificActivityLocked 方法,代码如下所示:

// /frameworks/base/services/core/java/com/android/server/wm/ActivityStackSupervisor.java // TODO: This class has become a dumping ground. Let's // 这个类已经变成了垃圾请倒场 // - Move things relating to the hierarchy to RootWindowContainer // - 把与层级相关的代码移动到 RootWindowContainer 中 // - Move things relating to activity life cycles to maybe a new class called ActivityLifeCycler // - 与 Activity 生命周期相关的代码移动到 ActivityLifeCycler 中 // - Move interface things to ActivityTaskManagerService. // - 接口相关的移动到 ActivityTaskManagerService 中 // - All other little things to other files. public class ActivityTaskSupervisor implements RecentTasks.Callbacks {     final ActivityTaskManagerService mService;      void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {         // Is this activity's application already running?         final WindowProcessController wpc =                 mService.getProcessController(r.processName, r.info.applicationInfo.uid);          boolean knownToBeDead = false;         if (wpc != null && wpc.hasThread()) {             try {                 realStartActivityLocked(r, wpc, andResume, checkConfig);                  return;             } catch (RemoteException e) {                 Slog.w(TAG, "Exception when starting activity "                         + r.intent.getComponent().flattenToShortString(), e);             }              ...         }          r.notifyUnknownVisibilityLaunchedForKeyguardTransition();          final boolean isTop = andResume && r.isTopRunningActivity();         mService.startProcessAsync(r, knownToBeDead, isTop,                 isTop ? HostingRecord.HOSTING_TYPE_TOP_ACTIVITY                         : HostingRecord.HOSTING_TYPE_ACTIVITY); // 1     } } 

注释 1 处调用 ATMS.startProcessAsync 方法用来创建新的进程。Zygote 进程收到请求后,fork 出新的进程并调用 ActivityThread.main 方法。

根Activity 启动时序图

以下是 ActivityTaskManagerService.startProcessAsync 方法的相关源码:

// frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java public class ActivityTaskManagerService extends IActivityTaskManager.Stub {        void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,                            String hostingType) {         try {           if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {               Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"                       + activity.processName);           }           // Post message to start process to avoid possible deadlock of calling into AMS             // with the ATMS lock held.           final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,                   mAmInternal, activity.processName, activity.info.applicationInfo,                    knownToBeDead, isTop, hostingType, activity.intent.getComponent()); // 1           mH.sendMessage(m);         } finally {           Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);         }     }    } 

ActivityManagerInternal.startProcess 方法是请求启动应用进程的起点。 注释 1 处的 PooledLambda.obtainMessage 获取一个 Message,并为其指定 Callback。

// frameworks/base/core/java/com/android/internal/util/function/pooled/PooledLambda.java public interface PooledLambda {     static <A, B, C, D, E, F, G> Message obtainMessage(         HeptConsumer<? super A, ? super B, ? super C, ? super D, ? super E, ? super F,                 ? super G> function, A arg1, B arg2, C arg3, D arg4, E arg5, F arg6, G arg7) {         synchronized (Message.sPoolSync) {         PooledRunnable callback = acquire(PooledLambdaImpl.sMessageCallbacksPool,                 function, 7, 0, ReturnType.VOID, arg1, arg2, arg3, arg4, arg5, arg6, arg7,                  null, null, null, null, null);         return Message.obtain().setCallback(callback.recycleOnUse());     }    }   

ActivityManagerInternal 是抽象类,其实现类是 ActivityManagerService 的内部类 LocalService:

// frameworks/base/core/java/android/app/ActivityManagerInternal.java public abstract class ActivityManagerInternal {     public abstract void startProcess(String processName, ApplicationInfo info,             boolean knownToBeDead, boolean isTop, String hostingType,              ComponentName hostingName); }  // frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java public class ActivityManagerService extends IActivityManager.Stub         implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback,  										ActivityManagerGlobalLock {          public final class LocalService extends ActivityManagerInternal                 implements ActivityManagerLocal {          @Override         public void startProcess(String processName, ApplicationInfo info,                  boolean knownToBeDead, boolean isTop, String hostingType,                  ComponentName hostingName) {             try {                 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "startProcess:"                             + processName);                 }                 synchronized (ActivityManagerService.this) {                     // If the process is known as top app, set a hint so when the process is                     // started, the top priority can be applied immediately to avoid cpu                      // being                     // preempted by other processes before attaching the process of top app.                     startProcessLocked(processName, info, knownToBeDead, 0 /* intentFlags */,                             new HostingRecord(hostingType, hostingName, isTop),                             ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE,                              false /* allowWhileBooting */, false /* isolated */);                 }             } finally {                 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);             }         }      }                            final ProcessRecord startProcessLocked(String processName,         ApplicationInfo info, boolean knownToBeDead, int intentFlags,         HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting,         boolean isolated) {                return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags,                 hostingRecord, zygotePolicyFlags, allowWhileBooting, isolated,                  0 /* isolatedUid */, false /* isSdkSandbox */,                  0 /* sdkSandboxClientAppUid */, null /* sdkSandboxClientAppPackage */,                 null /* ABI override */, null /* entryPoint */,                 null /* entryPointArgs */, null /* crashHandler */);     }    } 

以下是 ZygoteProcess.startViaZygote 方法的相关源码:

// frameworks/base/core/java/android/os/ZygoteProcess.java public class ZygoteProcess {     private Process.ProcessStartResult startViaZygote(@NonNull final String processClass,                                                   @Nullable final String niceName,                                                   final int uid, final int gid,                                                   @Nullable final int[] gids,                                                   int runtimeFlags, int mountExternal,                                                   int targetSdkVersion,                                                   @Nullable String seInfo,                                                   @NonNull String abi,                                                   @Nullable String instructionSet,                                                   @Nullable String appDataDir,                                                   @Nullable String invokeWith,                                                   boolean startChildZygote,                                                   @Nullable String packageName,                                                   int zygotePolicyFlags,                                                   boolean isTopApp,                                                   @Nullable long[] disabledCompatChanges,                                                   @Nullable Map<String, Pair<String, Long>>                                                           pkgDataInfoMap,                                                   @Nullable Map<String, Pair<String, Long>>                                                           allowlistedDataInfoList,                                                   boolean bindMountAppsData,                                                   boolean bindMountAppStorageDirs,                                                   @Nullable String[] extraArgs)                                                   throws ZygoteStartFailedEx {         ...          synchronized(mLock) {             // The USAP pool can not be used if the application will not use the systems              // graphics driver.               // If that driver is requested use the Zygote application start path.             return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi),                                               zygotePolicyFlags,                                               argsForZygote); // 1     	} 		}   } 

注释 1 处调用 openZygoteSocketIfNeeded 方法建立与 Zygote 进程的 Socket 连接,并返回一个 ZygoteState 对象:

// frameworks/base/core/java/android/os/ZygoteProcess.java public class ZygoteProcess {        private ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx {       try {           attemptConnectionToPrimaryZygote();            if (primaryZygoteState.matches(abi)) {               return primaryZygoteState;           }            if (mZygoteSecondarySocketAddress != null) {               // The primary zygote didn't match. Try the secondary.               attemptConnectionToSecondaryZygote();                if (secondaryZygoteState.matches(abi)) {                   return secondaryZygoteState;               }           }       } catch (IOException ioe) {           throw new ZygoteStartFailedEx("Error connecting to zygote", ioe);       }        throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);     }      private void attemptConnectionToPrimaryZygote() throws IOException {       if (primaryZygoteState == null || primaryZygoteState.isClosed()) {           primaryZygoteState =                   ZygoteState.connect(mZygoteSocketAddress, mUsapPoolSocketAddress);            maybeSetApiDenylistExemptions(primaryZygoteState, false);           maybeSetHiddenApiAccessLogSampleRate(primaryZygoteState);       }     }    } 

ZygoteState 是 ZygoteProcess 的内部类:

// frameworks/base/core/java/android/os/ZygoteProcess.java public class ZygoteProcess {      private static class ZygoteState implements AutoCloseable {       static ZygoteState connect(@NonNull LocalSocketAddress zygoteSocketAddress,               @Nullable LocalSocketAddress usapSocketAddress)               throws IOException {            DataInputStream zygoteInputStream;           BufferedWriter zygoteOutputWriter;           final LocalSocket zygoteSessionSocket = new LocalSocket();            if (zygoteSocketAddress == null) {               throw new IllegalArgumentException("zygoteSocketAddress can't be null");           }            try {               zygoteSessionSocket.connect(zygoteSocketAddress); // 1               zygoteInputStream = new DataInputStream(zygoteSessionSocket.getInputStream());               zygoteOutputWriter =                       new BufferedWriter(                               new OutputStreamWriter(zygoteSessionSocket.getOutputStream()),                               Zygote.SOCKET_BUFFER_SIZE);           } catch (IOException ex) {               try {                   zygoteSessionSocket.close();               } catch (IOException ignore) { }                throw ex;           }            return new ZygoteState(zygoteSocketAddress, usapSocketAddress,                                  zygoteSessionSocket, zygoteInputStream, zygoteOutputWriter,                                  getAbiList(zygoteOutputWriter, zygoteInputStream));       } 	}    } 

注释 1 处调用的是 LocalSocket.connect 方法。LocalSocket 是客户端(system_server 进程),与服务端(Zygote 进程)建立 Socket 连接,实现跨进程通讯。zygoteSocketAddress 指向服务端 Socket 地址。

// frameworks/base/core/java/android/os/ZygoteProcess.java public class ZygoteProcess {        private Process.ProcessStartResult zygoteSendArgsAndGetResult(         ZygoteState zygoteState, int zygotePolicyFlags, @NonNull ArrayList<String> args)         throws ZygoteStartFailedEx {         for (String arg : args) {             if (arg.indexOf('\n') >= 0) {                 throw new ZygoteStartFailedEx("Embedded newlines not allowed");             } else if (arg.indexOf('\r') >= 0) {                 throw new ZygoteStartFailedEx("Embedded carriage returns not allowed");             }         }          String msgStr = args.size() + "\n" + String.join("\n", args) + "\n";          if (shouldAttemptUsapLaunch(zygotePolicyFlags, args)) {             try {                 return attemptUsapSendArgsAndGetResult(zygoteState, msgStr);             } catch (IOException ex) {                 Log.e(LOG_TAG, "IO Exception while communicating with USAP pool - "                         + ex.getMessage());             }         } 				// 1 准备向服务端(Zygote 进程)发送启动应用程序进程的参数         return attemptZygoteSendArgsAndGetResult(zygoteState, msgStr);     }      private Process.ProcessStartResult attemptZygoteSendArgsAndGetResult(         ZygoteState zygoteState, String msgStr) throws ZygoteStartFailedEx {         try {             final BufferedWriter zygoteWriter = zygoteState.mZygoteOutputWriter;             final DataInputStream zygoteInputStream = zygoteState.mZygoteInputStream;              zygoteWriter.write(msgStr);             zygoteWriter.flush();              Process.ProcessStartResult result = new Process.ProcessStartResult();             result.pid = zygoteInputStream.readInt();             result.usingWrapper = zygoteInputStream.readBoolean();              if (result.pid < 0) {                 throw new ZygoteStartFailedEx("fork() failed");             }              return result;         } catch (IOException ex) {             zygoteState.close();             Log.e(LOG_TAG, "IO Exception while communicating with Zygote - "                     + ex.toString());             throw new ZygoteStartFailedEx(ex);         }     } } 

注释 1 处准备向服务端(Zygote 进程)发送启动应用程序进程的参数。

根Activity 启动时序图

以下是 ZygoteInit 的构造方法和 main 方法的相关源码:

// frameworks/base/core/java/com/android/internal/os/ZygoteInit.java public static void main(String[] argv) {     ZygoteServer zygoteServer = null;      ...      Runnable caller;     try {         ...          zygoteServer = new ZygoteServer(isPrimaryZygote);          if (startSystemServer) {             Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);              // {@code r == null} in the parent (zygote) process, and {@code r != null} in the             // child (system_server) process.             if (r != null) {                 r.run();                 return;             }         }          Log.i(TAG, "Accepting command socket connections");          // The select loop returns early in the child process after a fork and         // loops forever in the zygote.         caller = zygoteServer.runSelectLoop(abiList); // 1     } catch (Throwable ex) {         Log.e(TAG, "System zygote died with fatal exception", ex);         throw ex;     } finally {         if (zygoteServer != null) {             zygoteServer.closeServerSocket();         }     }      // We're in the child process and have exited the select loop. Proceed to execute the     // command.     if (caller != null) {         caller.run(); // 2     } } 

LocalServerSocket 是 socket 通讯分服务端。注释 1 处调用了 ZygoteServer.runSelectLoop 方法:

// frameworks/base/core/java/com/android/internal/os/ZygoteServer.java private LocalServerSocket mZygoteSocket; private final LocalServerSocket mUsapPoolSocket;  ZygoteServer(boolean isPrimaryZygote) {     mUsapPoolEventFD = Zygote.getUsapPoolEventFD();      if (isPrimaryZygote) {         mZygoteSocket = Zygote.createManagedSocketFromInitSocket(Zygote.PRIMARY_SOCKET_NAME);         mUsapPoolSocket =                 Zygote.createManagedSocketFromInitSocket(                         Zygote.USAP_POOL_PRIMARY_SOCKET_NAME);     } else {         mZygoteSocket =            Zygote.createManagedSocketFromInitSocket(Zygote.SECONDARY_SOCKET_NAME);         mUsapPoolSocket =                 Zygote.createManagedSocketFromInitSocket(                         Zygote.USAP_POOL_SECONDARY_SOCKET_NAME);     }      mUsapPoolSupported = true;     fetchUsapPoolPolicyProps(); }  Runnable runSelectLoop(String abiList) {     ...     ArrayList<ZygoteConnection> peers = new ArrayList<>();      ...      while (true) {         ...          if (pollReturnValue == 0) {             ...          } else {             boolean usapPoolFDRead = false;              while (--pollIndex >= 0) {                 if ((pollFDs[pollIndex].revents & POLLIN) == 0) {                     continue;                 }                  if (pollIndex == 0) {                     // Zygote server socket                     ZygoteConnection newPeer = acceptCommandPeer(abiList); // 1                     peers.add(newPeer);                     socketFDs.add(newPeer.getFileDescriptor());                 } else if (pollIndex < usapPoolEventFDIndex) {                     // Session socket accepted from the Zygote server socket                      try {                         ZygoteConnection connection = peers.get(pollIndex);                         boolean multipleForksOK = !isUsapPoolEnabled()                                 && ZygoteHooks.isIndefiniteThreadSuspensionSafe();                         final Runnable command =                                 connection.processCommand(this, multipleForksOK); // 2                          ...                     } catch (Exception e) {                         ...                     } finally {                         ...                     }                  } else {                     ...                 }             }              ...         }          ...     } }  private LocalServerSocket mZygoteSocket;  private ZygoteConnection acceptCommandPeer(String abiList) {     try {         return createNewConnection(mZygoteSocket.accept(), abiList); // 3     } catch (IOException ex) {         throw new RuntimeException(                 "IOException during accept()", ex);     } }  protected ZygoteConnection createNewConnection(LocalSocket socket, String abiList)         throws IOException {     return new ZygoteConnection(socket, abiList); // 4 } 

注释 1 处的 acceptCommandPeer 方法中会 new ZygoteConnection(LocalServerSocket.accept, abiList),其中 LocalServerSocket.accept() 方法用来监听来自客户端(system_server 进程)的 connect 请求,并返回一个 LocalSocket 对象,通过该对象可以实现与客户端跨进程通讯。

// frameworks/base/core/java/com/android/internal/os/ZygoteConnection.java Runnable processCommand(ZygoteServer zygoteServer, boolean multipleOK) {     ZygoteArguments parsedArgs;      try (ZygoteCommandBuffer argBuffer = new ZygoteCommandBuffer(mSocket)) {         while (true) {             try {                 parsedArgs = ZygoteArguments.getInstance(argBuffer);                 // Keep argBuffer around, since we need it to fork.             } catch (IOException ex) {                 throw new IllegalStateException("IOException on command socket", ex);             }             ...                           if (parsedArgs.mInvokeWith != null || parsedArgs.mStartChildZygote                     || !multipleOK || peer.getUid() != Process.SYSTEM_UID) {                 // Continue using old code for now. TODO: Handle these cases in the other path.                 pid = Zygote.forkAndSpecialize(parsedArgs.mUid, parsedArgs.mGid,                         parsedArgs.mGids, parsedArgs.mRuntimeFlags, rlimits,                         parsedArgs.mMountExternal, parsedArgs.mSeInfo, parsedArgs.mNiceName,                         fdsToClose, fdsToIgnore, parsedArgs.mStartChildZygote,                         parsedArgs.mInstructionSet, parsedArgs.mAppDataDir,                         parsedArgs.mIsTopApp, parsedArgs.mPkgDataInfoList,                         parsedArgs.mAllowlistedDataInfoList,                          parsedArgs.mBindMountAppDataDirs,                         parsedArgs.mBindMountAppStorageDirs); // 1                  try {                     if (pid == 0) {                         // in child                         zygoteServer.setForkChild();                          zygoteServer.closeServerSocket();                         IoUtils.closeQuietly(serverPipeFd);                         serverPipeFd = null;                          return handleChildProc(parsedArgs, childPipeFd,                                 parsedArgs.mStartChildZygote); // 2                     } else {                         ...                     }                 } finally {                     ...                 }             } else {                 ...             }         }     }     ...     throw new AssertionError("Shouldn't get here"); }   private Runnable handleChildProc(ZygoteArguments parsedArgs,         FileDescriptor pipeFd, boolean isZygote) {     ...     if (parsedArgs.mInvokeWith != null) {         ...     } else {         if (!isZygote) { // 3 isZygote 一般是 false             return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,                     parsedArgs.mDisabledCompatChanges,                     parsedArgs.mRemainingArgs, null /* classLoader */); // 4         } else {             return ZygoteInit.childZygoteInit(                     parsedArgs.mRemainingArgs  /* classLoader */); //          }     } } 

注释 3 处的 isZygote 一般是 false,注释 4 处调用的是 ZygoteInit.zygoteInit 方法:

// frameworks/base/core/java/com/android/internal/os/ZygoteInit.java public static Runnable zygoteInit(int targetSdkVersion, long[] disabledCompatChanges,         String[] argv, ClassLoader classLoader) {     if (RuntimeInit.DEBUG) {         Slog.d(RuntimeInit.TAG, "RuntimeInit: Starting application from zygote");     }      Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");     RuntimeInit.redirectLogStreams();      RuntimeInit.commonInit();     ZygoteInit.nativeZygoteInit();     return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv,             classLoader); // 1 } 

注释 1 处调用 RuntimeInit.applicationInit 方法:

// frameworks/base/core/java/com/android/internal/os/RuntimeInit.java protected static Runnable applicationInit(int targetSdkVersion, long[] disabledCompatChanges,         String[] argv, ClassLoader classLoader) {     nativeSetExitWithoutCleanup(true);      VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);     VMRuntime.getRuntime().setDisabledCompatChanges(disabledCompatChanges);      final Arguments args = new Arguments(argv);      // The end of of the RuntimeInit event (see #zygoteInit).     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);      // Remaining arguments are passed to the start class's static main     return findStaticMain(args.startClass, args.startArgs, classLoader); }  protected static Runnable findStaticMain(String className, String[] argv,         ClassLoader classLoader) {     Class<?> cl;      try {         cl = Class.forName(className, true, classLoader);     } catch (ClassNotFoundException ex) {         throw new RuntimeException(                 "Missing class when invoking static main " + className,                 ex);     }      Method m;     try {         m = cl.getMethod("main", new Class[] { String[].class }); // 1     } catch (NoSuchMethodException ex) {         throw new RuntimeException(                 "Missing static main on " + className, ex);     } catch (SecurityException ex) {         throw new RuntimeException(                 "Problem getting static main on " + className, ex);     }      int modifiers = m.getModifiers();     if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {         throw new RuntimeException(                 "Main method is not public and static on " + className);     }      /*      * This throw gets caught in ZygoteInit.main(), which responds      * by invoking the exception's run() method. This arrangement      * clears up all the stack frames that were required in setting      * up the process.      */     return new MethodAndArgsCaller(m, argv); // 2 }  static class MethodAndArgsCaller implements Runnable {     /** method to call */     private final Method mMethod;      /** argument array */     private final String[] mArgs;      public MethodAndArgsCaller(Method method, String[] args) {         mMethod = method;         mArgs = args;     }      public void run() {         try {             mMethod.invoke(null, new Object[] { mArgs }); // 3         } catch (IllegalAccessException ex) {             throw new RuntimeException(ex);         } catch (InvocationTargetException ex) {             Throwable cause = ex.getCause();             if (cause instanceof RuntimeException) {                 throw (RuntimeException) cause;             } else if (cause instanceof Error) {                 throw (Error) cause;             }             throw new RuntimeException(ex);         }     } } 

MethodAndArgsCaller.run 方法最终会进入到 ActivityThread.main 方法中。

根Activity 启动时序图

根Activity 启动时序图

// frameworks/base/core/java/android/app/ActivityThread.java public static void main(String[] args) {     ...      Looper.prepareMainLooper();      ...     ActivityThread thread = new ActivityThread();     thread.attach(false, startSeq);      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"); }  private void attach(boolean system, long startSeq) {     ...     if (!system) {         ...         final IActivityManager mgr = ActivityManager.getService();         try {             mgr.attachApplication(mAppThread, startSeq);         } catch (RemoteException ex) {             throw ex.rethrowFromSystemServer();         }         ...     } else {         ... } 
// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java public ActivityTaskManagerInternal mAtmInternal;  @Override public final void attachApplication(IApplicationThread thread, long startSeq) {     if (thread == null) {         throw new SecurityException("Invalid application interface");     }     synchronized (this) {         int callingPid = Binder.getCallingPid();         final int callingUid = Binder.getCallingUid();         final long origId = Binder.clearCallingIdentity();         attachApplicationLocked(thread, callingPid, callingUid, startSeq);         Binder.restoreCallingIdentity(origId);     } }   private boolean attachApplicationLocked(@NonNull IApplicationThread thread,         int pid, int callingUid, long startSeq) {      ...     try {         ...                  if (app.getIsolatedEntryPoint() != null) {             ...         } else if (instr2 != null) {             thread.bindApplication(processName, appInfo,                     app.sdkSandboxClientAppVolumeUuid, app.sdkSandboxClientAppPackage,                     providerList,                     instr2.mClass,                     profilerInfo, instr2.mArguments,                     instr2.mWatcher,                     instr2.mUiAutomationConnection, testMode,                     mBinderTransactionTrackingEnabled, enableTrackAllocation,                     isRestrictedBackupMode || !normalMode, app.isPersistent(),                     new Configuration(app.getWindowProcessController().getConfiguration()),                     app.getCompat(), getCommonServicesLocked(app.isolated),                     mCoreSettingsObserver.getCoreSettingsLocked(),                     buildSerial, autofillOptions, contentCaptureOptions,                     app.getDisabledCompatChanges(), serializedSystemFontMap,                     app.getStartElapsedTime(), app.getStartUptime());         } else {             thread.bindApplication(processName, appInfo,                     app.sdkSandboxClientAppVolumeUuid, app.sdkSandboxClientAppPackage,                     providerList, null, profilerInfo, null, null, null, testMode,                     mBinderTransactionTrackingEnabled, enableTrackAllocation,                     isRestrictedBackupMode || !normalMode, app.isPersistent(),                     new Configuration(app.getWindowProcessController().getConfiguration()),                     app.getCompat(), getCommonServicesLocked(app.isolated),                     mCoreSettingsObserver.getCoreSettingsLocked(),                     buildSerial, autofillOptions, contentCaptureOptions,                     app.getDisabledCompatChanges(), serializedSystemFontMap,                     app.getStartElapsedTime(), app.getStartUptime());         }         ...     } catch (Exception e) {         ...     }        // See if the top visible activity is waiting to run in this process...     if (normalMode) {         try {             didSomething = mAtmInternal.attachApplication(app.getWindowProcessController()); // 2         } catch (Exception e) {             Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);             badApp = true;         }     }      ... } 
// frameworks/base/core/java/android/app/ActivityThread.java private class ApplicationThread extends IApplicationThread.Stub {     @Override     public final void bindApplication(String processName, ApplicationInfo appInfo,             String sdkSandboxClientAppVolumeUuid, String sdkSandboxClientAppPackage,             ProviderInfoList providerList, ComponentName instrumentationName,             ProfilerInfo profilerInfo, Bundle instrumentationArgs,             IInstrumentationWatcher instrumentationWatcher,             IUiAutomationConnection instrumentationUiConnection, int debugMode,             boolean enableBinderTracking, boolean trackAllocation,             boolean isRestrictedBackupMode, boolean persistent, Configuration config,             CompatibilityInfo compatInfo, Map services, Bundle coreSettings,             String buildSerial, AutofillOptions autofillOptions,             ContentCaptureOptions contentCaptureOptions, long[] disabledCompatChanges,             SharedMemory serializedSystemFontMap,             long startRequestedElapsedTime, long startRequestedUptime) {         ...          AppBindData data = new AppBindData();         data.processName = processName;         data.appInfo = appInfo;         data.sdkSandboxClientAppVolumeUuid = sdkSandboxClientAppVolumeUuid;         data.sdkSandboxClientAppPackage = sdkSandboxClientAppPackage;         data.providers = providerList.getList();         data.instrumentationName = instrumentationName;         data.instrumentationArgs = instrumentationArgs;         data.instrumentationWatcher = instrumentationWatcher;         data.instrumentationUiAutomationConnection = instrumentationUiConnection;         data.debugMode = debugMode;         data.enableBinderTracking = enableBinderTracking;         data.trackAllocation = trackAllocation;         data.restrictedBackupMode = isRestrictedBackupMode;         data.persistent = persistent;         data.config = config;         data.compatInfo = compatInfo;         data.initProfilerInfo = profilerInfo;         data.buildSerial = buildSerial;         data.autofillOptions = autofillOptions;         data.contentCaptureOptions = contentCaptureOptions;         data.disabledCompatChanges = disabledCompatChanges;         data.mSerializedSystemFontMap = serializedSystemFontMap;         data.startRequestedElapsedTime = startRequestedElapsedTime;         data.startRequestedUptime = startRequestedUptime;         sendMessage(H.BIND_APPLICATION, data);     } }  void sendMessage(int what, Object obj) {   	sendMessage(what, obj, 0, 0, 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); }  class H extends Handler {        public void handleMessage(Message msg) {               if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));               switch (msg.what) {                  case BIND_APPLICATION:                       Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");                       AppBindData data = (AppBindData)msg.obj;                       handleBindApplication(data);                       Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);                       break;                   ...               }       ...     }    } 
// frameworks/base/core/java/android/app/ActivityThread.java private void handleBindApplication(AppBindData data) {     ...      // send up app name; do this *before* waiting for debugger     Process.setArgV0(data.processName);     android.ddm.DdmHandleAppName.setAppName(data.processName,                                             data.appInfo.packageName,                                             UserHandle.myUserId());     VMRuntime.setProcessPackageName(data.appInfo.packageName);      // Pass data directory path to ART. This is used for caching information and     // should be set before any application code is loaded.     VMRuntime.setProcessDataDirectory(data.appInfo.dataDir);      if (mProfiler.profileFd != null) {         mProfiler.startProfiling();     }      ...      // Instrumentation info affects the class loader, so load it before     // setting up the app context.     final InstrumentationInfo ii;     if (data.instrumentationName != null) {         ii = prepareInstrumentation(data);     } else {         ii = null;     }      final ContextImpl appContext = ContextImpl.createAppContext(this, data.info);     mConfigurationController.updateLocaleListFromAppContext(appContext);      ...      // Continue loading instrumentation.     if (ii != null) {         initInstrumentation(ii, data, appContext);     } else {         mInstrumentation = new Instrumentation();         mInstrumentation.basicInit(this);     }      ...      // Allow disk access during application and provider setup. This could     // block processing ordered broadcasts, but later processing would     // probably end up doing the same disk access.     Application app;     final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskWrites();     final StrictMode.ThreadPolicy writesAllowedPolicy = StrictMode.getThreadPolicy();     try {         // If the app is being launched for full backup or restore, bring it up in         // a restricted environment with the base application class.         app = data.info.makeApplicationInner(data.restrictedBackupMode, null); // 1          ...          // Do this after providers, since instrumentation tests generally start their         // test thread at this point, and we don't want that racing.         try {             mInstrumentation.onCreate(data.instrumentationArgs);         }         catch (Exception e) {             throw new RuntimeException(                 "Exception thrown in onCreate() of "                 + data.instrumentationName + ": " + e.toString(), e);         }         try {             mInstrumentation.callApplicationOnCreate(app); // 2         } catch (Exception e) {             if (!mInstrumentation.onException(app, e)) {                 throw new RuntimeException(                   "Unable to create application " + app.getClass().getName()                   + ": " + e.toString(), e);             }         }     } finally {         // If the app targets < O-MR1, or doesn't change the thread policy         // during startup, clobber the policy to maintain behavior of b/36951662         if (data.appInfo.targetSdkVersion < Build.VERSION_CODES.O_MR1                 || StrictMode.getThreadPolicy().equals(writesAllowedPolicy)) {             StrictMode.setThreadPolicy(savedPolicy);         }     }  } 
// frameworks/base/core/java/android/app/LoadedApk.java public Application makeApplicationInner(boolean forceDefaultAppClass,         Instrumentation instrumentation) {     return makeApplicationInner(forceDefaultAppClass, instrumentation,             /* allowDuplicateInstances= */ false); }  private Application makeApplicationInner(boolean forceDefaultAppClass,         Instrumentation instrumentation, boolean allowDuplicateInstances) {     ...      Application app = null;      final String myProcessName = Process.myProcessName();     String appClass = mApplicationInfo.getCustomApplicationClassNameForProcess(             myProcessName);     if (forceDefaultAppClass || (appClass == null)) {         appClass = "android.app.Application";     }      try {         final java.lang.ClassLoader cl = getClassLoader();         if (!mPackageName.equals("android")) {             Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,                     "initializeJavaContextClassLoader");             initializeJavaContextClassLoader();             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);         }          ...          ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);         // The network security config needs to be aware of multiple         // applications in the same process to handle discrepancies         NetworkSecurityConfigProvider.handleNewApplication(appContext);         app = mActivityThread.mInstrumentation.newApplication(                 cl, appClass, appContext); // 1         appContext.setOuterContext(app);     } catch (Exception e) {         ...     }     mActivityThread.mAllApplications.add(app);     mApplication = app;     if (!allowDuplicateInstances) {         synchronized (sApplications) {             sApplications.put(mPackageName, app);         }     }      if (instrumentation != null) {         try {             instrumentation.callApplicationOnCreate(app); // 2         } catch (Exception e) {             if (!instrumentation.onException(app, e)) {                 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);                 throw new RuntimeException(                     "Unable to create application " + app.getClass().getName()                     + ": " + e.toString(), e);             }         }     }      Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);      return app; } 
// frameworks/base/core/java/android/app/Instrumentation.java public Application newApplication(ClassLoader cl, String className, Context context)         throws InstantiationException, IllegalAccessException,          ClassNotFoundException {     Application app = getFactory(context.getPackageName())             .instantiateApplication(cl, className);     app.attach(context);     return app; } 
// frameworks/base/core/java/android/app/Application.java /* package */ final void attach(Context context) {       attachBaseContext(context);       mLoadedApk = ContextImpl.getImpl(context).mPackageInfo;   } 
// frameworks/base/core/java/android/app/Instrumentation.java public void callApplicationOnCreate(Application app) {     app.onCreate(); } 
// frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerInternal.java public abstract class ActivityTaskManagerInternal {     /** Called by AM when an application process attaches. */     public abstract boolean attachApplication(WindowProcessController wpc) throws         RemoteException; } 
// frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java RootWindowContainer mRootWindowContainer; final class LocalService extends ActivityTaskManagerInternal {     @HotPath(caller = HotPath.PROCESS_CHANGE)     @Override     public boolean attachApplication(WindowProcessController wpc) throws RemoteException {         synchronized (mGlobalLockWithoutBoost) {             if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {                 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);             }             try {                 return mRootWindowContainer.attachApplication(wpc);             } finally {                 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);             }         }     } } 
// frameworks/base/services/core/java/com/android/server/wm/RootWindowContainer.java private final AttachApplicationHelper mAttachApplicationHelper = new AttachApplicationHelper(); boolean attachApplication(WindowProcessController app) throws RemoteException {     try {         return mAttachApplicationHelper.process(app);     } finally {         mAttachApplicationHelper.reset();     } }  private class AttachApplicationHelper implements Consumer<Task>, Predicate<ActivityRecord> {     boolean process(WindowProcessController app) throws RemoteException {         mApp = app;         for (int displayNdx = getChildCount() - 1; displayNdx >= 0; --displayNdx) {             getChildAt(displayNdx).forAllRootTasks(this);             if (mRemoteException != null) {                 throw mRemoteException;             }         }         if (!mHasActivityStarted) {             ensureActivitiesVisible(null /* starting */, 0 /* configChanges */,                     false /* preserveWindows */);         }         return mHasActivityStarted;     } } 
// frameworks/base/services/core/java/com/android/server/wm/WindowContainer.java boolean forAllRootTasks(Predicate<Task> callback) {   return forAllRootTasks(callback, true /* traverseTopToBottom */); }  boolean forAllRootTasks(Predicate<Task> callback, boolean traverseTopToBottom) {   int count = mChildren.size();   if (traverseTopToBottom) {       for (int i = count - 1; i >= 0; --i) {           if (mChildren.get(i).forAllRootTasks(callback, traverseTopToBottom)) {               return true;           }       }   } else {       for (int i = 0; i < count; i++) {           if (mChildren.get(i).forAllRootTasks(callback, traverseTopToBottom)) {               return true;           }           // Root tasks may be removed from this display. Ensure each task will be processed           // and the loop will end.           int newCount = mChildren.size();           i -= count - newCount;           count = newCount;       }   }   return false; } 
// frameworks/base/services/core/java/com/android/server/wm/Task.java @Override void forAllRootTasks(Consumer<Task> callback, boolean traverseTopToBottom) {     if (isRootTask()) {         callback.accept(this);     } } 
// frameworks/base/services/core/java/com/android/server/wm/RootWindowContainer.java private class AttachApplicationHelper implements Consumer<Task>, Predicate<ActivityRecord> {     @Override     public void accept(Task rootTask) {         if (mRemoteException != null) {             return;         }         if (rootTask.getVisibility(null /* starting */)                 == TASK_FRAGMENT_VISIBILITY_INVISIBLE) {             return;         }         mTop = rootTask.topRunningActivity();         rootTask.forAllActivities(this);     } } 
// frameworks/base/services/core/java/com/android/server/wm/WindowContainer.java boolean forAllActivities(Predicate<ActivityRecord> callback) {   return forAllActivities(callback, true /*traverseTopToBottom*/); }  boolean forAllActivities(Predicate<ActivityRecord> callback, boolean traverseTopToBottom) {   if (traverseTopToBottom) {       for (int i = mChildren.size() - 1; i >= 0; --i) {           if (mChildren.get(i).forAllActivities(callback, traverseTopToBottom)) return true;       }   } else {       final int count = mChildren.size();       for (int i = 0; i < count; i++) {           if (mChildren.get(i).forAllActivities(callback, traverseTopToBottom)) return true;       }   }    return false; } 
// frameworks/base/services/core/java/com/android/server/wm/ActivityRecord.java @Override boolean forAllActivities(Predicate<ActivityRecord> callback, boolean traverseTopToBottom) {     return callback.test(this); } 
// frameworks/base/services/core/java/com/android/server/wm/RootWindowContainer.java private class AttachApplicationHelper implements Consumer<Task>, Predicate<ActivityRecord> {     @Override     public boolean test(ActivityRecord r) {         if (r.finishing || !r.showToCurrentUser() || !r.visibleIgnoringKeyguard                 || r.app != null || mApp.mUid != r.info.applicationInfo.uid                 || !mApp.mName.equals(r.processName)) {             return false;         }          try {             if (mTaskSupervisor.realStartActivityLocked(r, mApp,                     mTop == r && r.getTask().canBeResumed(r) /* andResume */,                     true /* checkConfig */)) {                 mHasActivityStarted = true;             }         } catch (RemoteException e) {             Slog.w(TAG, "Exception in new application when starting activity " + mTop, e);             mRemoteException = e;             return true;         }         return false;     } } 

Activity 启动流程

参考

Android13 Activity启动流程
Android10 客户端事务管理ClientLifecycleManager源码解析
Android Task详解
Android的Task管理
【framework】应用进程启动流程

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!