当前位置:   article > 正文

Android Activity启动过程详解_android activity启动流程

android activity启动流程

 Android系统启动篇

1,《android系统启动流程简介》

2,《android init进程启动流程》

3,《android zygote进程启动流程》

4,《Android SystemServer进程启动流程》

5,《android launcher启动流程》

6,《Android Activity启动过程详解》

Android系统开发准备篇

1,《Android 源码下载和编译》

2,《android 11源码编译和pixel3 刷机》

3,《Android Framework代码IDE加载和调试》

Android系统开发实践篇

1,《android设置默认输入法》

2,《android framework预制APK应用》

3,《Android系统层面限制应用开机自启动详解》

4,《android单独编译framework模块并push》

5,《Android Framework开发系统问题分析》

Android系统开发核心知识储备篇

1,《Android编译系统-envsetup和lunch代码篇》

2,《Android编译系统-概念篇》

3,《android日志系统详解》

4,《Android系统Handler详解》

5,《Android系统Binder详解》

6,《Android中Activity、View和Window关系详解》

7,《android view绘制流程详解》

8,《Android读取系统属性详解》

9,《android 窗口管理机制详解》

10,《初识Android系统》

11,《android中AMS进程通知Zygote进程fork新进程的通信方式》

Android核心功能详解篇

1,《android应用市场点击下载APK安装详解》

2,《Android 手势导航(从下往上滑动进入多任务页面)》

3,《android手势分析(应用界面左往右边滑动退出应用)》

4,《android应用安装流程详解》

5,《android11安装应用触发桌面图标刷新流程》

6,《Android系统多任务Recents详解》

7,《android系统导航栏视图分析》

———————————————————————————————————————————

目录

一,背景介绍

二,Activity启动过程

2.1 调用 ATMS 系统进程

2.1.1 时序图

2.1.2 Launcher 桌面的 App 图标入口

2.1.3 startActivitySafely() 方法

2.1.4 execStartActivity() 方法

2.2 ATMS 向 AMS 发送创建应用进程的过程

2.2.1 时序图

2.2.2 ATMS(ActivityTaskManagerService)

2.2.3 ActivityStartController

2.2.4 ActivityStarter

2.2.5 RootWindowContainer

2.2.6 ActivityStack

2.2.7 ActivityStackSupervisor

2.3 AMS 向 Zygote 进程发送创建应用进程 ActivityThread 的过程

2.3.1 时序图​编辑

2.3.2 ActivityTaskManagerService 启动进程

2.3.3 ActivityManagerService

2.3.4 ProcessList

2.3.5 Process

2.3.6 ZygoteProcess

2.3.7 ZygoteProcess 开启 socket 连接

2.3.8 ZygoteProcess 发送请求参数

2.4  Zygote 进程fork并启动应用进程

2.4.1 时序图

2.4.2 Zygote 进程启动、解析 Socket 传入的参数

2.4.3 ZygoteServer 开启 Loop 循环监听 Socket

2.4.4 ZygoteConnection

2.4.5 Zygote 创建子进程(native 层创建)

2.4.6 ZygoteConnection # handleChildProc() 方法

2.4.7 ZygoteInit # zygoteInit() 方法

2.4.8 RuntimeInit # applicationInit() 方法

2.4.9 RuntimeInit # MethodAndArgsCaller

2.4.10. 小结

2.5 应用进程 ActivityThread 启动 Activity 的过程

2.5.1 时序图

2.5.2 ActivityThread 入口方法

2.5.3 AMS 绑定 ApplicationThread

2.5.4 ActivityThread 创建并绑定 Application

2.5.5 ProcessRecord 保存 ApplicationThread

2.5.6 ATMS 绑定 WindowProcessController、启动根 Activity

2.5.7 RootWindowContainer 绑定 WindowProcessController

2.5.8 获取 ClientTransaction、添加 Callback、设置 LifecycleStateRequest

2.5.9 ClientTransaction 获取、添加事务回调

2.5.10 ClientLifecycleManager 客户端生命周期事务转换管理器

2.5.11 ClientTransaction # schedule() 调度事务

2.5.12 ActivityThread 调度事务

2.5.13 TransactionExecutor 事务转换执行器

2.5.14 LaunchActivityItem 请求启动 Activity

2.5.15 ActivityThread 执行启动 Activity 事务

2.5.16 ActivityThread 执行生命周期事务

2.5.17 TransactionExecutor 执行中间态生命周期请求事务

2.5.18 TransactionExecutorHelper 获取待执行生命周期的状态序列

2.5.19 TransactionExecutor 执行生命周期事务的最终转换

三,总结


一,背景介绍

        Activity启动流程两种类型:一是在activity中通过startActivity(Intent intent)方法启动一个Activity;二是我们在桌面点击应用图标启动一个App然后显示Activity;第二种方式相较于第一种方式流程更加全面和复杂,所以本文会以第二种流程来分析讲解。

        启动流程大致分为下面五个阶段:

1,Launcher进程请求调用ATMS系统进程过程
2,ATMS 向 AMS 发送创建应用进程的过程
3,AMS 向 Zygote 进程发送创建应用进程 ActivityThread 的过程
4,Zygote 进程接收请求 fork 并启动应用进程 ActivityThread 的过程
5,应用进程 ActivityThread 启动 Activity 的过程

二,Activity启动过程

        点击 Launcher 中某一个应用图标到应用第一个 Activity 展示出来的流程,当系统开机后,Launcher 会被 AMS 启动,然后将已经安装的应用程序图标显示到桌面上,所以当我们点击一个应用图标其实就是相当于点击 Activity 中的一个 Button,其相应事件就是 Launcher 进程请求 ATMS 来启动该应用程序。


2.1 调用 ATMS 系统进程

2.1.1 时序图

2.1.2 Launcher 桌面的 App 图标入口

        Launcher3的manifest.xml定义,路径packages/apps/Launcher3/AndroidManifest.xml

  1. <activity
  2. android:name="com.android.launcher3.Launcher"
  3. android:launchMode="singleTask"
  4. android:clearTaskOnLaunch="true"
  5. android:stateNotNeeded="true"
  6. android:windowSoftInputMode="adjustPan"
  7. android:screenOrientation="unspecified"
  8. android:configChanges="keyboard|keyboardHidden|mcc|mnc|navigation|orientation|screenSize|screenLayout|smallestScreenSize"
  9. android:resizeableActivity="true"
  10. android:resumeWhilePausing="true"
  11. android:taskAffinity=""
  12. android:enabled="true">
  13. <intent-filter>
  14. <action android:name="android.intent.action.MAIN" />
  15. <category android:name="android.intent.category.HOME" />
  16. <category android:name="android.intent.category.DEFAULT" />
  17. <category android:name="android.intent.category.MONKEY"/>
  18. <category android:name="android.intent.category.LAUNCHER_APP" />
  19. </intent-filter>
  20. <meta-data
  21. android:name="com.android.launcher3.grid.control"
  22. android:value="${packageName}.grid_control" />
  23. </activity>

        上面定义可知,com.android.launcher3.Launcher.java文件为桌面首页,源码如下:

  1. public class Launcher extends StatefulActivity<LauncherState> implements LauncherExterns,Callbacks, InvariantDeviceProfile.OnIDPChangeListener, PluginListener<OverlayPlugin>,LauncherOverlayCallbacks {
  2. @Override
  3. @TargetApi(Build.VERSION_CODES.S)
  4. protected void onCreate(Bundle savedInstanceState) {
  5. super.onCreate(savedInstanceState);
  6. ......
  7. // 分析1 -- 加载、展示布局文件
  8. inflateRootView(R.layout.launcher);
  9. }
  10. }

        布局文件R.layout.launcher如下,

  1. <!-- R.layout.launcher -->
  2. <?xml version="1.0" encoding="utf-8"?>
  3. <com.android.launcher3.LauncherRootView
  4. xmlns:android="http://schemas.android.com/apk/res/android"
  5. xmlns:launcher="http://schemas.android.com/apk/res-auto"
  6. android:id="@+id/launcher"
  7. android:layout_width="match_parent"
  8. android:layout_height="match_parent"
  9. android:fitsSystemWindows="true">
  10. <com.android.launcher3.dragndrop.DragLayer
  11. android:id="@+id/drag_layer"
  12. android:layout_width="match_parent"
  13. android:layout_height="match_parent"
  14. android:clipChildren="false"
  15. android:clipToPadding="false"
  16. android:importantForAccessibility="no">
  17. <!-- 这里是展示所有 App 图标的布局,我们只看相关代码 -->
  18. <include
  19. android:id="@+id/apps_view"
  20. layout="@layout/all_apps"
  21. android:layout_width="match_parent"
  22. android:layout_height="match_parent" />
  23. </com.android.launcher3.dragndrop.DragLayer>
  24. </com.android.launcher3.LauncherRootView>
  25. <!-- R.layout.apps_view -->
  26. <?xml version="1.0" encoding="utf-8"?>
  27. <com.android.launcher3.allapps.LauncherAllAppsContainerView
  28. xmlns:android="http://schemas.android.com/apk/res/android"
  29. android:id="@+id/apps_view"
  30. android:theme="?attr/allAppsTheme"
  31. android:layout_width="match_parent"
  32. android:layout_height="match_parent"
  33. android:clipChildren="true"
  34. android:clipToPadding="false"
  35. android:focusable="false"
  36. android:saveEnabled="false">
  37. <!-- 展示所有已安装 app 的 AllAppsRecyclerView 继承自 RecyclerView -->
  38. <include
  39. layout="@layout/all_apps_rv_layout"
  40. android:visibility="gone" />
  41. </com.android.launcher3.allapps.LauncherAllAppsContainerView>
  42. <!-- R.layout.all_apps_rv_layout -->
  43. <?xml version="1.0" encoding="utf-8"?>
  44. <com.android.launcher3.allapps.AllAppsRecyclerView
  45. xmlns:android="http://schemas.android.com/apk/res/android"
  46. android:id="@+id/apps_list_view"
  47. android:layout_width="match_parent"
  48. android:layout_height="match_parent"
  49. android:layout_below="@id/search_container_all_apps"
  50. android:clipToPadding="false"
  51. android:descendantFocusability="afterDescendants"
  52. android:focusable="true" />

        AllAppsRecyclerView 外层是 LauncherAllAppsContainerView,它是 AllAppsContainerView 的子类。给 AllAppsRecyclerView 设置 Adapter 被封装到了 AllAppsContainerView 里面,看一下代码:

  1. /**
  2. * The all apps view container.
  3. */
  4. public class AllAppsContainerView extends SpringRelativeLayout implements DragSource,
  5. Insettable, OnDeviceProfileChangeListener, OnActivePageChangedListener,
  6. ScrimView.ScrimDrawingController {
  7. protected void rebindAdapters(boolean force) {
  8. ......
  9. if (mUsingTabs) {
  10. ......
  11. // 这里只分析不使用 Tabs 的情况,感兴趣的童鞋可以继续追源码
  12. } else {
  13. // AllAppsRecyclerView 设置 Adapter 等信息
  14. mAH[AdapterHolder.MAIN].setup(findViewById(R.id.apps_list_view), null);
  15. mAH[AdapterHolder.WORK].recyclerView = null;
  16. }
  17. ......
  18. }
  19. public class AdapterHolder {
  20. public static final int MAIN = 0;
  21. public static final int WORK = 1;
  22. public final AllAppsGridAdapter adapter;
  23. final LinearLayoutManager layoutManager;
  24. final AlphabeticalAppsList appsList;
  25. AllAppsRecyclerView recyclerView;
  26. AdapterHolder(boolean isWork) {
  27. mIsWork = isWork;
  28. appsList = new AlphabeticalAppsList(mLauncher, mAllAppsStore,
  29. isWork ? mWorkManager.getAdapterProvider() : null);
  30. BaseAdapterProvider[] adapterProviders =
  31. isWork ? new BaseAdapterProvider[]{mSearchAdapterProvider,
  32. mWorkManager.getAdapterProvider()}
  33. : new BaseAdapterProvider[]{mSearchAdapterProvider};
  34. adapter = new AllAppsGridAdapter(mLauncher, getLayoutInflater(), appsList,
  35. adapterProviders);
  36. appsList.setAdapter(adapter);
  37. layoutManager = adapter.getLayoutManager();
  38. }
  39. void setup(@NonNull View rv, @Nullable ItemInfoMatcher matcher) {
  40. appsList.updateItemFilter(matcher);
  41. recyclerView = (AllAppsRecyclerView) rv;
  42. recyclerView.setEdgeEffectFactory(createEdgeEffectFactory());
  43. recyclerView.setApps(appsList);
  44. recyclerView.setLayoutManager(layoutManager);
  45. // AllAppsRecyclerView 设置 AllAppsGridAdapter
  46. recyclerView.setAdapter(adapter);
  47. }
  48. }
  49. }

         源码中在 AllAppsContainerView 中为 AllAppsRecyclerView 设置了 AllAppsGridAdapter,然后在 AllAppsGridAdapter # onCreateViewHolder() 方法中为子项 itemView 设置点击事件 ItemClickHandler.INSTANCE,点击事件由 launcher.getItemOnClickListener() 方法获取。看一下 ItemClickHandler 是怎么处理点击事件的,代码如下:

  1. /**
  2. * Class for handling clicks on workspace and all-apps items
  3. */
  4. public class ItemClickHandler {
  5. private static final String TAG = ItemClickHandler.class.getSimpleName();
  6. /**
  7. * Instance used for click handling on items
  8. * 单例方式获取点击事件
  9. */
  10. public static final OnClickListener INSTANCE = ItemClickHandler::onClick;
  11. private static void onClick(View v) {
  12. if (v.getWindowToken() == null) return;
  13. Launcher launcher = Launcher.getLauncher(v.getContext());
  14. if (!launcher.getWorkspace().isFinishedSwitchingState()) return;
  15. Object tag = v.getTag();
  16. if (tag instanceof WorkspaceItemInfo) {
  17. onClickAppShortcut(v, (WorkspaceItemInfo) tag, launcher);
  18. } else if (tag instanceof FolderInfo) {
  19. if (v instanceof FolderIcon) {
  20. onClickFolderIcon(v);
  21. }
  22. } else if (tag instanceof AppInfo) {
  23. // 点击 App 图标
  24. startAppShortcutOrInfoActivity(v, (AppInfo) tag, launcher
  25. );
  26. } else if (tag instanceof LauncherAppWidgetInfo) {
  27. if (v instanceof PendingAppWidgetHostView) {
  28. onClickPendingWidget((PendingAppWidgetHostView) v, launcher);
  29. }
  30. } else if (tag instanceof SearchActionItemInfo) {
  31. onClickSearchAction(launcher, (SearchActionItemInfo) tag);
  32. }
  33. }
  34. private static void startAppShortcutOrInfoActivity(View v, ItemInfo item, Launcher launcher) {
  35. Intent intent;
  36. if (item instanceof ItemInfoWithIcon
  37. && (((ItemInfoWithIcon) item).runtimeStatusFlags
  38. & ItemInfoWithIcon.FLAG_INSTALL_SESSION_ACTIVE) != 0) {
  39. ItemInfoWithIcon appInfo = (ItemInfoWithIcon) item;
  40. intent = new PackageManagerHelper(launcher)
  41. .getMarketIntent(appInfo.getTargetComponent().getPackageName());
  42. } else {
  43. intent = item.getIntent();
  44. }
  45. if (intent == null) {
  46. throw new IllegalArgumentException("Input must have a valid intent");
  47. }
  48. if (item instanceof WorkspaceItemInfo) {
  49. WorkspaceItemInfo si = (WorkspaceItemInfo) item;
  50. if (si.hasStatusFlag(WorkspaceItemInfo.FLAG_SUPPORTS_WEB_UI)
  51. && Intent.ACTION_VIEW.equals(intent.getAction())) {
  52. intent = new Intent(intent);
  53. intent.setPackage(null);
  54. }
  55. if ((si.options & WorkspaceItemInfo.FLAG_START_FOR_RESULT) != 0) {
  56. launcher.startActivityForResult(item.getIntent(), 0);
  57. InstanceId instanceId = new InstanceIdSequence().newInstanceId();
  58. launcher.logAppLaunch(launcher.getStatsLogManager(), item, instanceId);
  59. return;
  60. }
  61. }
  62. if (v != null && launcher.supportsAdaptiveIconAnimation(v)) {
  63. // Preload the icon to reduce latency b/w swapping the floating view with the original.
  64. FloatingIconView.fetchIcon(launcher, v, item, true /* isOpening */);
  65. }
  66. // 调用 Launcher # startActivitySafely() 启动 Activity
  67. launcher.startActivitySafely(v, intent, item);
  68. }
  69. }

         回答上面的问题,AllAppsRecyclerView 在 AllAppsContainerView 中设置了 AllAppsGridAdapter,在 AllAppsGridAdapter # onCreateViewHolder() 方法中为子项 itemView 设置点击事件 ItemClickHandler.INSTANCE。

2.1.3 startActivitySafely() 方法

  1. /**
  2. * Default launcher application.
  3. */
  4. public class Launcher extends StatefulActivity<LauncherState> implements LauncherExterns,
  5. Callbacks, InvariantDeviceProfile.OnIDPChangeListener, PluginListener<OverlayPlugin>,
  6. LauncherOverlayCallbacks {
  7. @Override
  8. public boolean startActivitySafely(View v, Intent intent, ItemInfo item) {
  9. if (!hasBeenResumed()) {
  10. addOnResumeCallback(() -> startActivitySafely(v, intent, item));
  11. if (mOnDeferredActivityLaunchCallback != null) {
  12. mOnDeferredActivityLaunchCallback.run();
  13. mOnDeferredActivityLaunchCallback = null;
  14. }
  15. return true;
  16. }
  17. boolean success = super.startActivitySafely(v, intent, item);
  18. if (success && v instanceof BubbleTextView) {
  19. BubbleTextView btv = (BubbleTextView) v;
  20. btv.setStayPressed(true);
  21. addOnResumeCallback(() -> btv.setStayPressed(false));
  22. }
  23. return success;
  24. }
  25. }
  26. /**
  27. * Extension of BaseActivity allowing support for drag-n-drop
  28. */
  29. @SuppressWarnings("NewApi")
  30. public abstract class BaseDraggingActivity extends BaseActivity
  31. implements OnColorsChangedListener, DisplayInfoChangeListener {
  32. public boolean startActivitySafely(View v, Intent intent, @Nullable ItemInfo item) {
  33. ......
  34. Bundle optsBundle = (v != null) ? getActivityLaunchOptions(v, item).toBundle() : null;
  35. UserHandle user = item == null ? null : item.user;
  36. // Prepare intent
  37. // 添加 FLAG_ACTIVITY_NEW_TASK,即在新的 Task 中启动 Activity
  38. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  39. if (v != null) {
  40. intent.setSourceBounds(Utilities.getViewBounds(v));
  41. }
  42. try {
  43. boolean isShortcut = (item instanceof WorkspaceItemInfo)
  44. && (item.itemType == Favorites.ITEM_TYPE_SHORTCUT
  45. || item.itemType == Favorites.ITEM_TYPE_DEEP_SHORTCUT)
  46. && !((WorkspaceItemInfo) item).isPromise();
  47. if (isShortcut) {
  48. // Shortcuts need some special checks due to legacy reasons.
  49. startShortcutIntentSafely(intent, optsBundle, item);
  50. } else if (user == null || user.equals(Process.myUserHandle())) {
  51. // Could be launching some bookkeeping activity
  52. // 点击 App 图标 启动 App
  53. startActivity(intent, optsBundle);
  54. } else {
  55. getSystemService(LauncherApps.class).startMainActivity(
  56. intent.getComponent(), user, intent.getSourceBounds(), optsBundle);
  57. }
  58. if (item != null) {
  59. InstanceId instanceId = new InstanceIdSequence().newInstanceId();
  60. logAppLaunch(getStatsLogManager(), item, instanceId);
  61. }
  62. return true;
  63. } catch (NullPointerException | ActivityNotFoundException | SecurityException e) {
  64. ......
  65. }
  66. return false;
  67. }
  68. }

        根 Activity 启动时,添加 FLAG_ACTIVITY_NEW_TASK,即在新的任务栈 Task 中启动 Activity,然后调⽤到 Activity # startActivity() ⽅法,传⼊参数为 intent 和 Bundle。代码如下:

  1. public class Activity extends ContextThemeWrapper
  2. implements ... {
  3. @Override
  4. public void startActivity(Intent intent, @Nullable Bundle options) {
  5. if (options != null) {
  6. // 通过 startActivityForResult 启动 Activity
  7. startActivityForResult(intent, -1, options);
  8. } else {
  9. startActivityForResult(intent, -1);
  10. }
  11. }
  12. public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
  13. @Nullable Bundle options) {
  14. // mParent 表示当前 Activity 的父 Activity,一般情况下 mParent 为空
  15. if (mParent == null) {
  16. options = transferSpringboardActivityOptions(options);
  17. Instrumentation.ActivityResult ar =
  18. mInstrumentation.execStartActivity(
  19. this, mMainThread.getApplicationThread(), mToken, this,
  20. intent, requestCode, options);
  21. if (ar != null) {
  22. mMainThread.sendActivityResult(
  23. mToken, mEmbeddedID, requestCode, ar.getResultCode(),
  24. ar.getResultData());
  25. }
  26. if (requestCode >= 0) {
  27. mStartedActivity = true;
  28. }
  29. cancelInputsAndStartExitTransition(options);
  30. } else {
  31. if (options != null) {
  32. mParent.startActivityFromChild(this, intent, requestCode, options);
  33. } else {
  34. mParent.startActivityFromChild(this, intent, requestCode);
  35. }
  36. }
  37. }
  38. }

        Activity # startActivity() 方法调用 Activity # startActivityForResult() 方法,Activity # startActivity() 第二个参数为-1表示 Launcher 不需要知道根 Activity 的启动结果。由于 mParent=null(mParent 表示当前 Activity 的父 Activity,一般情况下 mParent 为空),所以我们只需要关注 mParent=null 的情况,此时会调用 Instrumentation # execStartActivity() 方法。

2.1.4 execStartActivity() 方法

        Instrumentation 负责调用 Activity 和 Application 的生命周期,每个 Activity 都持有 Instrumentation 对象的一个引用,但是整个进程只会存在一个 Instrumentation 对象。跟进去看看 Instrumentation # execStartActivity () 方法,代码如下:

  1. @UnsupportedAppUsage
  2. public ActivityResult execStartActivity(
  3. Context who, IBinder contextThread, IBinder token, Activity target,
  4. Intent intent, int requestCode, Bundle options) {
  5. ......
  6. try {
  7. intent.migrateExtraStreamToClipData();
  8. intent.prepareToLeaveProcess(who);
  9. // 获取 ActivityTaskManagerService 的代理对象
  10. int result = ActivityTaskManager.getService()
  11. .startActivity(whoThread, who.getBasePackageName(), intent,
  12. intent.resolveTypeIfNeeded(who.getContentResolver()),
  13. token, target != null ? target.mEmbeddedID : null,
  14. requestCode, 0, null, options);
  15. checkStartActivityResult(result, intent);
  16. } catch (RemoteException e) {
  17. throw new RuntimeException("Failure from system", e);
  18. }
  19. return null;
  20. }

        Instrumentation # execStartActivity() 方法会调用 ActivityTaskManager # getService() 方法来获取 ActivityTaskManagerService 的代理对象,然后调用这个代理对象的 startActivity() 方法。

  1. public static IActivityTaskManager getService() {
  2. return IActivityTaskManagerSingleton.get();
  3. }
  4. @UnsupportedAppUsage(trackingBug = 129726065)
  5. private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton =
  6. new Singleton<IActivityTaskManager>() {
  7. @Override
  8. protected IActivityTaskManager create() {
  9. final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
  10. return IActivityTaskManager.Stub.asInterface(b);
  11. }
  12. };

        在 Singleton 的 create() 方法中,获取 ActivityTaskManagerService 的引用,这是一个 IBinder 类型的引用,且 ActivityTaskManagerService 作为服务端处于 system_server 进程,与当前作为客户端的 Launcher 进程不在同一个进程。 所以这里方法返回的是 IActivityTaskManager.Stub 的代理对象,而 ActivityTaskManagerService 则是对应的实现类,继承了 IActivityTaskManager.Stub 并实现相应的方法,通过代理对象可以跨进程调用服务端 ActivityTaskManagerService 的方法。

2.2 ATMS 向 AMS 发送创建应用进程的过程

        system_server 进程中 startBootstrapServices() 方法启动系统引导服务,引导服务中启动了 ATMS(ActivityTaskManagerServici)、AMS 等服务,其中 ATMS 是 Android 10 中新增的,本来都是 AMS 来管理,Google 考虑到 AMS 职责太多、代码太庞大,所以单独拆出来 ATMS 用于管理 Activity及其容器类,如 Task、Stack、Display 等,分担 AMS 部分职责。
 

2.2.1 时序图

2.2.2 ATMS(ActivityTaskManagerService)

通过上面的分析,启动过程走到了 ATMS 中,调用 ATMS # startActivity() 方法,代码如下:

  1. @Override
  2. public final int startActivity(IApplicationThread caller, String callingPackage,
  3. String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
  4. String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
  5. Bundle bOptions) {
  6. // UserHandle.getCallingUserId() 方法会获取调用者的 UserId
  7. return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
  8. resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
  9. UserHandle.getCallingUserId());
  10. }
  11. @Override
  12. public int startActivityAsUser(IApplicationThread caller, String callingPackage,
  13. String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
  14. String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
  15. Bundle bOptions, int userId) {
  16. return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
  17. resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
  18. true /*validateIncomingUser*/);
  19. }
  20. private int startActivityAsUser(IApplicationThread caller, String callingPackage,
  21. @Nullable String callingFeatureId, Intent intent, String resolvedType,
  22. IBinder resultTo, String resultWho, int requestCode, int startFlags,
  23. ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
  24. assertPackageMatchesCallingUid(callingPackage);
  25. // 检查调用者的进程是否隔离,如果 isIsolated 则抛出 SecurityException 异常
  26. enforceNotIsolatedCaller("startActivityAsUser");
  27. // 检查调用者权限,ATMS 根据传入的 UserId 来确定调用者的权限
  28. userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
  29. Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
  30. // TODO: Switch to user app stacks here.
  31. return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
  32. .setCaller(caller)
  33. .setCallingPackage(callingPackage)
  34. .setCallingFeatureId(callingFeatureId)
  35. .setResolvedType(resolvedType)
  36. .setResultTo(resultTo)
  37. .setResultWho(resultWho)
  38. .setRequestCode(requestCode)
  39. .setStartFlags(startFlags)
  40. .setProfilerInfo(profilerInfo)
  41. .setActivityOptions(bOptions)
  42. .setUserId(userId)
  43. .execute();
  44. }
  45. // 获取 ActivityStartController
  46. ActivityStartController getActivityStartController() {
  47. return mActivityStartController;
  48. }

2.2.3 ActivityStartController

  1. /**
  2. * @return A starter to configure and execute starting an activity. It is valid until after
  3. * {@link ActivityStarter#execute} is invoked. At that point, the starter should be
  4. * considered invalid and no longer modified or used.
  5. */
  6. ActivityStarter obtainStarter(Intent intent, String reason) {
  7. return mFactory.obtain().setIntent(intent).setReason(reason);
  8. }

        获取 ActivityStarter 对象后通过 Builder 模式设置启动所需的各种参数值,然后执行启动 Activity。ActivityStarter 是 Android 7.0 中增加的,用来加载启动 Activity 的控制类。

2.2.4 ActivityStarter

  1. class ActivityStarter {
  2. @VisibleForTesting
  3. interface Factory {
  4. // Sets the {@link ActivityStartController} to be passed to {@link ActivityStarter}.
  5. void setController(ActivityStartController controller);
  6. // 生成一个准备处理新启动请求的 ActivityStarter,ActivityStartController 持有这个实例对象
  7. ActivityStarter obtain();
  8. // Recycles a starter for reuse.
  9. void recycle(ActivityStarter starter);
  10. }
  11. // Default implementation of {@link StarterFactory}.
  12. static class DefaultFactory implements Factory {
  13. // 被激活的启动器的最大数
  14. private final int MAX_STARTER_COUNT = 3;
  15. private ActivityStartController mController;
  16. private ActivityTaskManagerService mService;
  17. private ActivityStackSupervisor mSupervisor;
  18. private ActivityStartInterceptor mInterceptor;
  19. private SynchronizedPool<ActivityStarter> mStarterPool =
  20. new SynchronizedPool<>(MAX_STARTER_COUNT);
  21. DefaultFactory(ActivityTaskManagerService service,
  22. ActivityStackSupervisor supervisor, ActivityStartInterceptor interceptor) {
  23. mService = service;
  24. mSupervisor = supervisor;
  25. mInterceptor = interceptor;
  26. }
  27. @Override
  28. public void setController(ActivityStartController controller) {
  29. mController = controller;
  30. }
  31. @Override
  32. public ActivityStarter obtain() {
  33. ActivityStarter starter = mStarterPool.acquire();
  34. if (starter == null) {
  35. starter = new ActivityStarter(mController, mService, mSupervisor, mInterceptor);
  36. }
  37. return starter;
  38. }
  39. @Override
  40. public void recycle(ActivityStarter starter) {
  41. starter.reset(true /* clearRequest*/);
  42. mStarterPool.release(starter);
  43. }
  44. }
  45. /**
  46. * Resolve necessary information according the request parameters provided earlier, and execute
  47. * the request which begin the journey of starting an activity.
  48. * @return The starter result.
  49. */
  50. int execute() {
  51. try {
  52. int res;
  53. synchronized (mService.mGlobalLock) {
  54. final boolean globalConfigWillChange = mRequest.globalConfig != null
  55. && mService.getGlobalConfiguration().diff(mRequest.globalConfig) != 0;
  56. final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
  57. if (stack != null) {
  58. stack.mConfigWillChange = globalConfigWillChange;
  59. }
  60. final long origId = Binder.clearCallingIdentity();
  61. res = resolveToHeavyWeightSwitcherIfNeeded();
  62. if (res != START_SUCCESS) {
  63. return res;
  64. }
  65. // 继续调用 executeRequest() 方法
  66. res = executeRequest(mRequest);
  67. Binder.restoreCallingIdentity(origId);
  68. if (globalConfigWillChange) {
  69. ......
  70. mService.updateConfigurationLocked(mRequest.globalConfig, null, false);
  71. }
  72. // Notify ActivityMetricsLogger that the activity has launched.
  73. // ActivityMetricsLogger will then wait for the windows to be drawn and populate
  74. // WaitResult.
  75. mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(launchingState, res,
  76. mLastStartActivityRecord);
  77. return getExternalResult(mRequest.waitResult == null ? res
  78. : waitForResult(res, mLastStartActivityRecord));
  79. }
  80. } finally {
  81. onExecutionComplete();
  82. }
  83. }
  84. private int executeRequest(Request request) {
  85. ......
  86. // 创建 ActivityRecord,保存 Activity 的所有信息
  87. final ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
  88. callingPackage, callingFeatureId, intent, resolvedType, aInfo,
  89. mService.getGlobalConfiguration(), resultRecord, resultWho, requestCode,
  90. request.componentSpecified, voiceSession != null, mSupervisor, checkedOptions,
  91. sourceRecord);
  92. mLastStartActivityRecord = r;
  93. ......
  94. final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
  95. mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession,
  96. request.voiceInteractor, startFlags, true /* doResume */, checkedOptions, inTask,
  97. restrictedBgActivity, intentGrants);
  98. ......
  99. return mLastStartActivityResult;
  100. }
  101. private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
  102. IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
  103. int startFlags, boolean doResume, ActivityOptions options, Task inTask,
  104. boolean restrictedBgActivity, NeededUriGrants intentGrants) {
  105. int result = START_CANCELED;
  106. try {
  107. mService.deferWindowLayout();
  108. result = startActivityInner(r, sourceRecord, voiceSession, voiceInteractor,
  109. startFlags, doResume, options, inTask, restrictedBgActivity, intentGrants);
  110. }
  111. ......
  112. return result;
  113. }
  114. @VisibleForTesting
  115. int startActivityInner(final ActivityRecord r, ActivityRecord sourceRecord,
  116. IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
  117. int startFlags, boolean doResume, ActivityOptions options, Task inTask,
  118. boolean restrictedBgActivity, NeededUriGrants intentGrants) {
  119. ......
  120. if (mDoResume) {
  121. final ActivityRecord topTaskActivity =
  122. mStartActivity.getTask().topRunningActivityLocked();
  123. if (!mTargetStack.isTopActivityFocusable()
  124. || (topTaskActivity != null && topTaskActivity.isTaskOverlay()
  125. && mStartActivity != topTaskActivity)) {
  126. ......
  127. mTargetStack.ensureActivitiesVisible(null /* starting */,
  128. 0 /* configChanges */, !PRESERVE_WINDOWS);
  129. // Go ahead and tell window manager to execute app transition for this activity
  130. // since the app transition will not be triggered through the resume channel.
  131. mTargetStack.getDisplay().mDisplayContent.executeAppTransition();
  132. } else {
  133. ......
  134. mRootWindowContainer.resumeFocusedStacksTopActivities(
  135. mTargetStack, mStartActivity, mOptions);
  136. }
  137. }
  138. }
  139. }

        在上面的第一步中获取 ActivityStartController,调用其 obtainStarter() 方法,通过内部实现的 DefaultFactory 来获取 ActivityStarter,如果在 mStarterPool 中没有获取到,则新创建一个。

        上面介绍了 ActivityStarter 类是用来加载启动 Activity 的控制类,在ActivityStarter # execute() 方法中,会继续调用 ActivityStarter # executeRequest() 方法,这里会处理启动 Activity 的请求,并开始一个 Activity 启动的流程。

        ActivityStarter # executeRequest() 方法会进行初步的检查并且确认权限,并且在这里组装对应 Activity 的 ActivityRecord,其包含了对应 Activity 的所有信息,并储存在任务栈 TaskRecord 中。在 Activity 的启动过程中,Activity 都是通过 ActivityRecord 来表示的。然后继续调用 ActivityStarter # startActivityUnchecked() 方法,接着 ActivityStarter # startActivityUnchecked() 方法会调用 ActivityStarter # startActivityInner() 方法。

        在 ActivityStarter # startActivityInner() 方法中,主要就是处理 Activity 的启动模式有关的逻辑,并且在 ActivityStack 中处理对应 Activity 在任务栈中的相关事宜,包括但不限于将对应的 ActivityRecord 添加到 TaskRecord 栈中、将对应的 ActivityRecord 提到 TaskRecord 栈中最顶部。

        最后调用 RootWindowContainer # resumeFocusedStacksTopActivities() 方法,将启动流程交给 RootWindowContainer 处理。

2.2.5 RootWindowContainer

  1. boolean resumeFocusedStacksTopActivities(
  2. ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
  3. ......
  4. boolean result = false;
  5. if (targetStack != null && (targetStack.isTopStackInDisplayArea()
  6. || getTopDisplayFocusedStack() == targetStack)) {
  7. result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
  8. }
  9. for (int displayNdx = getChildCount() - 1; displayNdx >= 0; --displayNdx) {
  10. boolean resumedOnDisplay = false;
  11. ......
  12. if (!resumedOnDisplay) {
  13. // In cases when there are no valid activities (e.g. device just booted or launcher
  14. // crashed) it's possible that nothing was resumed on a display. Requesting resume
  15. // of top activity in focused stack explicitly will make sure that at least home
  16. // activity is started and resumed, and no recursion occurs.
  17. final ActivityStack focusedStack = display.getFocusedStack();
  18. if (focusedStack != null) {
  19. result |= focusedStack.resumeTopActivityUncheckedLocked(target, targetOptions);
  20. } else if (targetStack == null) {
  21. result |= resumeHomeActivity(null /* prev */, "no-focusable-task",
  22. display.getDefaultTaskDisplayArea());
  23. }
  24. }
  25. }
  26. return result;
  27. }

        RootWindowContainer 是窗口容器(WindowContainer)的根容器,管理所有的窗口容器,设备上所有的窗口(Window)、显示(Display)都是由它来管理的。

        RootWindowContainer # resumeFocusedStacksTopActivities() 方法会恢复对应任务栈顶部的 Activity,方法中会检查一些可见性相关的属性,后转交给 ActivityStack # resumeTopActivityUncheckedLocked() 方法来继续启动流程。

2.2.6 ActivityStack

  1. @GuardedBy("mService")
  2. boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
  3. if (mInResumeTopActivity) {
  4. // Don't even start recursing.
  5. return false;
  6. }
  7. boolean result = false;
  8. try {
  9. // Protect against recursion.
  10. mInResumeTopActivity = true;
  11. result = resumeTopActivityInnerLocked(prev, options);
  12. // When resuming the top activity, it may be necessary to pause the top activity (for
  13. // example, returning to the lock screen. We suppress the normal pause logic in
  14. // {@link #resumeTopActivityUncheckedLocked}, since the top activity is resumed at the
  15. // end. We call the {@link ActivityStackSupervisor#checkReadyForSleepLocked} again here
  16. // to ensure any necessary pause logic occurs. In the case where the Activity will be
  17. // shown regardless of the lock screen, the call to
  18. // {@link ActivityStackSupervisor#checkReadyForSleepLocked} is skipped.
  19. final ActivityRecord next = topRunningActivity(true /* focusableOnly */);
  20. if (next == null || !next.canTurnScreenOn()) {
  21. checkReadyForSleep();
  22. }
  23. } finally {
  24. mInResumeTopActivity = false;
  25. }
  26. return result;
  27. }
  28. @GuardedBy("mService")
  29. private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
  30. if (next.attachedToProcess()) {
  31. ......
  32. ActivityRecord lastResumedActivity =
  33. lastFocusedStack == null ? null : lastFocusedStack.mResumedActivity;
  34. final ActivityState lastState = next.getState();
  35. next.setState(RESUMED, "resumeTopActivityInnerLocked");
  36. next.app.updateProcessInfo(false /* updateServiceConnectionActivities */,
  37. true /* activityChange */, true /* updateOomAdj */,
  38. true /* addPendingTopUid */);
  39. // From this point on, if something goes wrong there is no way
  40. // to recover the activity.
  41. try {
  42. next.completeResumeLocked();
  43. } catch (Exception e) {
  44. ......
  45. mStackSupervisor.startSpecificActivity(next, true, false);
  46. return true;
  47. }
  48. } else {
  49. // Whoops, need to restart this activity!
  50. ......
  51. }
  52. return true;
  53. }

        ActivityStack 是一个管理类,用来管理系统所有 Activity 的各种状态,其内部维护了 TaskRecord 的列表,每个 TaskRecord 又包含了若干个 ActivityRecord,每个 ActivityRecord 对应了一个 Activity。这里 TaskRecord 相当于在启动模式中的“任务栈”,根据启动模式的不同,在启动 Activity 的时候,会对 TaskRecord 进行不同的操作。

        由于前一步已经将对应 Activity 的 ActivityRecord 添加到了栈顶,所以 ActivityStack # resumeTopActivityUncheckedLocked() 方法恢复的就是将启动的栈顶 Activity,然后继续调用 ActivityStack # resumeTopActivityInnerLocked() 方法来继续启动流程,该方法中做了一系列判断,确保待启动 Activity 可见性、预定 Activity 的切换动画等。后转交给 ActivityStackSupervisor # startSpecificActivity() 方法来启动栈顶特定的 Activity。

2.2.7 ActivityStackSupervisor

  1. void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {
  2. // Is this activity's application already running?
  3. // 获取即将要启动的 Activity 的所在的应用程序进程已经运行了吗?
  4. final WindowProcessController wpc =
  5. mService.getProcessController(r.processName, r.info.applicationInfo.uid);
  6. boolean knownToBeDead = false;
  7. // wpc.hasThread() 内部通过判断 IApplicationThread 是否被赋值,如果已赋值,即应用进程已运行
  8. // 启动 Activity 的应用程序进程已经创建运行则走 Activity 的生命周期
  9. // 即普通 Activity 的启动走 realStartActivityLocked() 方法继续 Activity 的创建
  10. if (wpc != null && wpc.hasThread()) {
  11. try {
  12. realStartActivityLocked(r, wpc, andResume, checkConfig);
  13. return;
  14. } catch (RemoteException e) {
  15. ......
  16. }
  17. // If a dead object exception was thrown -- fall through to
  18. // restart the application.
  19. knownToBeDead = true;
  20. }
  21. r.notifyUnknownVisibilityLaunchedForKeyguardTransition();
  22. final boolean isTop = andResume && r.isTopRunningActivity();
  23. // 如果未赋值,即应用进程还不存在,则需要创建应用进程,由于是根 Activity 的启动所以应用进程还未被创建并启动
  24. mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity");
  25. }

        ActivityStackSupervisor 是用来辅助 ATMS 对 Activity 和 Task 进行管理的,其中 ActivityStackSupervisor 是对 ActivityStack 进行管理的,用 ActivityStack 对 Acitivity 进行状态管理。

        ActivityStackSupervisor 内部管理了 mHomeStack、mFocusedStack 和 mLastFocusedStack 三个 ActivityStack:

    1,mHomeStack 管理的是 Launcher 相关的 Activity 栈,stackId为0。
    2,mFocusedStack 管理的是当前显示在前台 Activity 的 Activity 栈。
    3,mLastFocusedStack 管理的是上一次显示在前台 Activity 的 Activity 栈。

        ActivityStackSupervisor # startSpecificActivity() 方法中获取 WindowProcessController ,通过 wpc # hasThread() 方法判断应用进程是否已创建并运行中,其内部是通过 IApplicationThread 是否已经被赋值来判断的,如果已被赋值则表示应用进程已创建且运行中,此时进入判断体内部,走 ActivityStackSupervisor # realStartActivityLocked() 方法继续 Activity 的启动流程,即普通 Activity 的启动流程。如果未被赋值,则需要创建应用进程,这里由于是根 Activity 的启动所以应用进程还未被创建并启动。


2.3 AMS 向 Zygote 进程发送创建应用进程 ActivityThread 的过程

2.3.1 时序图

2.3.2 ActivityTaskManagerService 启动进程

  1. void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
  2. String hostingType) {
  3. try {
  4. if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
  5. Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
  6. + activity.processName);
  7. }
  8. // Post message to start process to avoid possible deadlock of calling into AMS with the
  9. // ATMS lock held.
  10. // 发送 Handler 消息来启动进程,以避免在持有 ATMS 锁的情况下调用 AMS 时可能发生的死锁
  11. final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
  12. mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
  13. isTop, hostingType, activity.intent.getComponent());
  14. mH.sendMessage(m);
  15. } finally {
  16. Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
  17. }
  18. }

        方法中需要发送 Handler 消息来启动进程,在获取 Message 消息对象时跟我们平时的使用方式不太一样,这里是用到 PooledLambda # obtainMessage() 函数,代码如下:

  1. static <A, B, C, D, E, F> Message obtainMessage(
  2. HexConsumer<? super A, ? super B, ? super C, ? super D, ? super E, ? super F> function,
  3. A arg1, B arg2, C arg3, D arg4, E arg5, F arg6) {
  4. synchronized (Message.sPoolSync) {
  5. PooledRunnable callback = acquire(PooledLambdaImpl.sMessageCallbacksPool,
  6. function, 6, 0, ReturnType.VOID, arg1, arg2, arg3, arg4, arg5, arg6, null, null,
  7. null, null, null);
  8. return Message.obtain().setCallback(callback.recycleOnUse());
  9. }
  10. }

        可以看到这是一个静态函数,可以在接口外部直接被调用,这是 Java 1.8 的新特性,被 static 或 default 修饰的接口方法可以有默认实现,感兴趣的童鞋可以自行查阅哈。接口里面使用了经典的 lambda 定义方式,这个泛型的定义巧妙的将我们的函数以及需要传入的参数类型连接起来,第一个传入的 lambda 接口跟后面的参数类型紧密有关,调用这个函数的时候直接将需要传入的参数一并传入。这里需要提到的是 lambda 里面的中间接口是一种隐藏式的存在,我们在调用的过程中可以直接匿名忽略掉,上面的调用实例就是如此,直接使用了 ::符号 直接链接到目标函数 startProcess()。

        所以语法含义是调用 ActivityManagerInternal 类的 startProcess() 方法,后面的那些变量就是传递到 startProcess() 方法的入参。具体的再说就偏离主题了,感兴趣的可以自行查阅,简要说明就是这里通过 acquire() 函数获取到一个 PooledRunnable 实例,又通过它的 recycleOnUse() 函数得到一个 PooledLambdaImpl(实现了 PooledLambda 接口)的实例,所以当我们后续再调用 sendMessage() 的时候这个 PooledRunnable 的 run() 方法会得到执行,也即 ActivityManagerInternal # startProcess() 方法。

        ActivityManagerInternal 是一个抽象类,它是 Activity 管理本地服务接口的,它的实现为 AMS 的内部类 LocalService,在 AMS 启动的过程,通过 LocalServices # addService() 注册到 LocalServices,此类的使用方式与 ServiceManager 相似,不同之处在于,此处注册的服务不是 Binder 对象,并且只能在同一进程(system_server进程)中使用。也就是说 ActivityManagerInternal 实现类 LocalService 是 system_server 进程的本地服务 Service,通过本地服务注册到 LocalServices 中,而 AMS 也是运行在 system_server 进程,因此可以直接使用 LocalService。

        LocalServices 可以理解为是一个公开缓存池,内部使用 ArrayMap 来存储本地服务对象。system_server 进程中每个服务都可以通过 LocalServices # addService() 注册到 LocalServices 中,需要使用存储的 LocalService 时通过 LocalServices # getService() 获取注册的本地服务。
 

2.3.3 ActivityManagerService

  1. public class ActivityManagerService extends IActivityManager.Stub
  2. implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
  3. @VisibleForTesting
  4. public final class LocalService extends ActivityManagerInternal {
  5. ......
  6. @Override
  7. public void startProcess(String processName, ApplicationInfo info, boolean knownToBeDead,
  8. boolean isTop, String hostingType, ComponentName hostingName) {
  9. try {
  10. if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
  11. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "startProcess:"
  12. + processName);
  13. }
  14. synchronized (ActivityManagerService.this) {
  15. // If the process is known as top app, set a hint so when the process is
  16. // started, the top priority can be applied immediately to avoid cpu being
  17. // preempted by other processes before attaching the process of top app.
  18. startProcessLocked(processName, info, knownToBeDead, 0 /* intentFlags */,
  19. new HostingRecord(hostingType, hostingName, isTop),
  20. ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE, false /* allowWhileBooting */,
  21. false /* isolated */, true /* keepIfLarge */);
  22. }
  23. } finally {
  24. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  25. }
  26. }
  27. ......
  28. }
  29. @GuardedBy("this")
  30. final ProcessRecord startProcessLocked(String processName,
  31. ApplicationInfo info, boolean knownToBeDead, int intentFlags,
  32. HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting,
  33. boolean isolated, boolean keepIfLarge) {
  34. return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags,
  35. hostingRecord, zygotePolicyFlags, allowWhileBooting, isolated, 0 /* isolatedUid */,
  36. keepIfLarge, null /* ABI override */, null /* entryPoint */,
  37. null /* entryPointArgs */, null /* crashHandler */);
  38. }
  39. }

startProcess() 方法调用 AMS # startProcessLocked() 方法,并返回 ProcessRecord 实例记录管理启动进程的信息。

2.3.4 ProcessList

  1. @GuardedBy("mService")
  2. final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
  3. boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord,
  4. int zygotePolicyFlags, boolean allowWhileBooting, boolean isolated, int isolatedUid,
  5. boolean keepIfLarge, String abiOverride, String entryPoint, String[] entryPointArgs,
  6. Runnable crashHandler) {
  7. ......
  8. // ProcessRecord 记录每个进程的信息,进程名、uid 等
  9. ProcessRecord app = getProcessRecordLocked(processName, info.uid, keepIfLarge);
  10. checkSlow(startTime, "startProcess: stepping in to startProcess");
  11. final boolean success =
  12. startProcessLocked(app, hostingRecord, zygotePolicyFlags, abiOverride);
  13. checkSlow(startTime, "startProcess: done starting proc!");
  14. return success ? app : null;
  15. }
  16. @GuardedBy("mService")
  17. final boolean startProcessLocked(ProcessRecord app, HostingRecord hostingRecord,
  18. int zygotePolicyFlags, String abiOverride) {
  19. return startProcessLocked(app, hostingRecord, zygotePolicyFlags,
  20. false /* disableHiddenApiChecks */, false /* disableTestApiChecks */,
  21. false /* mountExtStorageFull */, abiOverride);
  22. }
  23. /**
  24. * @return {@code true} if process start is successful, false otherwise.
  25. */
  26. @GuardedBy("mService")
  27. boolean startProcessLocked(ProcessRecord app, HostingRecord hostingRecord,
  28. int zygotePolicyFlags, boolean disableHiddenApiChecks, boolean disableTestApiChecks,
  29. boolean mountExtStorageFull, String abiOverride) {
  30. ......
  31. try {
  32. app.gids = gids;
  33. app.setRequiredAbi(requiredAbi);
  34. app.instructionSet = instructionSet;
  35. // Start the process. It will either succeed and return a result containing
  36. // the PID of the new process, or else throw a RuntimeException.
  37. // 配置新创建进程的启动文件:ActivityThread,经过层层封装后经 Socket 传输到 Zygote 进程
  38. // Zygote 进程 fork 出新进程后要加载启动的类文件名
  39. final String entryPoint = "android.app.ActivityThread";
  40. return startProcessLocked(hostingRecord, entryPoint, app, uid, gids,
  41. runtimeFlags, zygotePolicyFlags, mountExternal, seInfo, requiredAbi,
  42. instructionSet, invokeWith, startTime);
  43. }
  44. ......
  45. }
  46. @GuardedBy("mService")
  47. boolean startProcessLocked(HostingRecord hostingRecord, String entryPoint, ProcessRecord app,
  48. int uid, int[] gids, int runtimeFlags, int zygotePolicyFlags, int mountExternal,
  49. String seInfo, String requiredAbi, String instructionSet, String invokeWith,
  50. long startTime) {
  51. ......
  52. if (mService.mConstants.FLAG_PROCESS_START_ASYNC) {
  53. ......
  54. } else {
  55. try {
  56. final Process.ProcessStartResult startResult = startProcess(hostingRecord,
  57. entryPoint, app,
  58. uid, gids, runtimeFlags, zygotePolicyFlags, mountExternal, seInfo,
  59. requiredAbi, instructionSet, invokeWith, startTime);
  60. handleProcessStartedLocked(app, startResult.pid, startResult.usingWrapper,
  61. startSeq, false);
  62. }
  63. ......
  64. return app.pid > 0;
  65. }
  66. }
  67. private Process.ProcessStartResult startProcess(HostingRecord hostingRecord, String entryPoint,
  68. ProcessRecord app, int uid, int[] gids, int runtimeFlags, int zygotePolicyFlags,
  69. int mountExternal, String seInfo, String requiredAbi, String instructionSet,
  70. String invokeWith, long startTime) {
  71. try {
  72. ......
  73. final Process.ProcessStartResult startResult;
  74. if (hostingRecord.usesWebviewZygote()) {
  75. startResult = startWebView(entryPoint,
  76. app.processName, uid, uid, gids, runtimeFlags, mountExternal,
  77. app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
  78. app.info.dataDir, null, app.info.packageName, app.mDisabledCompatChanges,
  79. new String[]{PROC_START_SEQ_IDENT + app.startSeq});
  80. } else if (hostingRecord.usesAppZygote()) {
  81. final AppZygote appZygote = createAppZygoteForProcessIfNeeded(app);
  82. // We can't isolate app data and storage data as parent zygote already did that.
  83. startResult = appZygote.getProcess().start(entryPoint,
  84. app.processName, uid, uid, gids, runtimeFlags, mountExternal,
  85. app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
  86. app.info.dataDir, null, app.info.packageName,
  87. /*zygotePolicyFlags=*/ ZYGOTE_POLICY_FLAG_EMPTY, isTopApp,
  88. app.mDisabledCompatChanges, pkgDataInfoMap, whitelistedAppDataInfoMap,
  89. false, false,
  90. new String[]{PROC_START_SEQ_IDENT + app.startSeq});
  91. } else {
  92. startResult = Process.start(entryPoint,
  93. app.processName, uid, uid, gids, runtimeFlags, mountExternal,
  94. app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
  95. app.info.dataDir, invokeWith, app.info.packageName, zygotePolicyFlags,
  96. isTopApp, app.mDisabledCompatChanges, pkgDataInfoMap,
  97. whitelistedAppDataInfoMap, bindMountAppsData, bindMountAppStorageDirs,
  98. new String[]{PROC_START_SEQ_IDENT + app.startSeq});
  99. }
  100. return startResult;
  101. } finally {
  102. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  103. }
  104. }

经过调用 4 个 startProcessLocked() 方法后,调用到了 startProcess() 方法,然后在 startProcess() 方法里做了一个判断,根据不同的参数调用不同的方法启动进程,这里跟进 Process # start() 继续追踪源码。

2.3.5 Process

  1. /**
  2. * State associated with the zygote process.
  3. * @hide
  4. */
  5. public static final ZygoteProcess ZYGOTE_PROCESS = new ZygoteProcess();
  6. public static ProcessStartResult start(@NonNull final String processClass,
  7. @Nullable final String niceName,
  8. int uid, int gid, @Nullable int[] gids,
  9. int runtimeFlags,
  10. int mountExternal,
  11. int targetSdkVersion,
  12. @Nullable String seInfo,
  13. @NonNull String abi,
  14. @Nullable String instructionSet,
  15. @Nullable String appDataDir,
  16. @Nullable String invokeWith,
  17. @Nullable String packageName,
  18. int zygotePolicyFlags,
  19. boolean isTopApp,
  20. @Nullable long[] disabledCompatChanges,
  21. @Nullable Map<String, Pair<String, Long>>
  22. pkgDataInfoMap,
  23. @Nullable Map<String, Pair<String, Long>>
  24. whitelistedDataInfoMap,
  25. boolean bindMountAppsData,
  26. boolean bindMountAppStorageDirs,
  27. @Nullable String[] zygoteArgs) {
  28. return ZYGOTE_PROCESS.start(processClass, niceName, uid, gid, gids,
  29. runtimeFlags, mountExternal, targetSdkVersion, seInfo,
  30. abi, instructionSet, appDataDir, invokeWith, packageName,
  31. zygotePolicyFlags, isTopApp, disabledCompatChanges,
  32. pkgDataInfoMap, whitelistedDataInfoMap, bindMountAppsData,
  33. bindMountAppStorageDirs, zygoteArgs);
  34. }

ZYGOTE_PROCESSZygoteProcessProcess 类中的静态实例,所以流程调用走到 Process # start() 方法继续进程的启动流程。

2.3.6 ZygoteProcess

  1. public final Process.ProcessStartResult start(@NonNull final String processClass,
  2. final String niceName,
  3. int uid, int gid, @Nullable int[] gids,
  4. int runtimeFlags, int mountExternal,
  5. int targetSdkVersion,
  6. @Nullable String seInfo,
  7. @NonNull String abi,
  8. @Nullable String instructionSet,
  9. @Nullable String appDataDir,
  10. @Nullable String invokeWith,
  11. @Nullable String packageName,
  12. int zygotePolicyFlags,
  13. boolean isTopApp,
  14. @Nullable long[] disabledCompatChanges,
  15. @Nullable Map<String, Pair<String, Long>>
  16. pkgDataInfoMap,
  17. @Nullable Map<String, Pair<String, Long>>
  18. whitelistedDataInfoMap,
  19. boolean bindMountAppsData,
  20. boolean bindMountAppStorageDirs,
  21. @Nullable String[] zygoteArgs) {
  22. // TODO (chriswailes): Is there a better place to check this value?
  23. if (fetchUsapPoolEnabledPropWithMinInterval()) {
  24. informZygotesOfUsapPoolStatus();
  25. }
  26. try {
  27. // 继续调用 startViaZygote,即通过 Zygote 来启动进程
  28. return startViaZygote(processClass, niceName, uid, gid, gids,
  29. runtimeFlags, mountExternal, targetSdkVersion, seInfo,
  30. abi, instructionSet, appDataDir, invokeWith, /*startChildZygote=*/ false,
  31. packageName, zygotePolicyFlags, isTopApp, disabledCompatChanges,
  32. pkgDataInfoMap, whitelistedDataInfoMap, bindMountAppsData,
  33. bindMountAppStorageDirs, zygoteArgs);
  34. }
  35. ......
  36. }
  37. private Process.ProcessStartResult startViaZygote(@NonNull final String processClass,
  38. @Nullable final String niceName,
  39. final int uid, final int gid,
  40. @Nullable final int[] gids,
  41. int runtimeFlags, int mountExternal,
  42. int targetSdkVersion,
  43. @Nullable String seInfo,
  44. @NonNull String abi,
  45. @Nullable String instructionSet,
  46. @Nullable String appDataDir,
  47. @Nullable String invokeWith,
  48. boolean startChildZygote,
  49. @Nullable String packageName,
  50. int zygotePolicyFlags,
  51. boolean isTopApp,
  52. @Nullable long[] disabledCompatChanges,
  53. @Nullable Map<String, Pair<String, Long>>
  54. pkgDataInfoMap,
  55. @Nullable Map<String, Pair<String, Long>>
  56. whitelistedDataInfoMap,
  57. boolean bindMountAppsData,
  58. boolean bindMountAppStorageDirs,
  59. @Nullable String[] extraArgs)
  60. throws ZygoteStartFailedEx {
  61. // 创建字符串列表 argsForZygote,将应用进程的启动参数保存在 argsForZygote 中
  62. // 包括 uid、gid、targetSdkVersion、应用程序进程启动文件:android.app.ActivityThread 等参数
  63. ArrayList<String> argsForZygote = new ArrayList<>();
  64. ...... // 添加各种参数值
  65. argsForZygote.add(processClass);
  66. ......
  67. synchronized(mLock) {
  68. // The USAP pool can not be used if the application will not use the systems graphics
  69. // driver. If that driver is requested use the Zygote application start path.
  70. // 调用 zygoteSendArgsAndGetResult(),将传入的应用进程的启动参数 argsForZygote 写入到 ZygoteState 中
  71. return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi),
  72. zygotePolicyFlags, argsForZygote);
  73. }
  74. }

ZygoteProcess # start() 方法中,继续调用 ZygoteProcess # startViaZygote() 方法,即通过 Zygote 来启动进程,方法流程如下:

    建字符串列表 argsForZygote,将应用进程的启动参数保存在 argsForZygote 列表中,包括 uid、gid、targetSdkVersion、应用进程的启动文件:android.app.ActivityThread 等参数。
    调用 ZygoteProcess # openZygoteSocketIfNeeded() 方法,如果与 Zygote 进程的 socket 连接未开启,则尝试开启,可能会产生阻塞和重试。连接调用的是 ZygoteState # connect() 方法,ZygoteState 是 ZygoteProcess 的内部类。
    调用 ZygoteProcess # zygoteSendArgsAndGetResult() 方法,向 Zygote 进程发送参数列表,启动一个新的子进程并返回子进程的 pid。注意:当前实现将参数列表中的换行符替换为空格。
 

2.3.7 ZygoteProcess 开启 socket 连接

  1. @GuardedBy("mLock")
  2. private ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx {
  3. try {
  4. // 与 Zygote 进程建立 Socket 连接
  5. attemptConnectionToPrimaryZygote();
  6. if (primaryZygoteState.matches(abi)) {
  7. return primaryZygoteState;
  8. }
  9. if (mZygoteSecondarySocketAddress != null) {
  10. // The primary zygote didn't match. Try the secondary.
  11. attemptConnectionToSecondaryZygote();
  12. if (secondaryZygoteState.matches(abi)) {
  13. return secondaryZygoteState;
  14. }
  15. }
  16. } catch (IOException ioe) {
  17. throw new ZygoteStartFailedEx("Error connecting to zygote", ioe);
  18. }
  19. throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);
  20. }
  21. private static class ZygoteState implements AutoCloseable {
  22. ......
  23. // 上面 Primary、Secondary 都是调用 ZygoteState.connect() 方法来创建一个使用给定 Zygote socket 地址的 Socket 连接
  24. static ZygoteState connect(@NonNull LocalSocketAddress zygoteSocketAddress,
  25. @Nullable LocalSocketAddress usapSocketAddress)
  26. throws IOException {
  27. DataInputStream zygoteInputStream;
  28. BufferedWriter zygoteOutputWriter;
  29. final LocalSocket zygoteSessionSocket = new LocalSocket();
  30. if (zygoteSocketAddress == null) {
  31. throw new IllegalArgumentException("zygoteSocketAddress can't be null");
  32. }
  33. try {
  34. zygoteSessionSocket.connect(zygoteSocketAddress);
  35. zygoteInputStream = new DataInputStream(zygoteSessionSocket.getInputStream());
  36. zygoteOutputWriter =
  37. new BufferedWriter(
  38. new OutputStreamWriter(zygoteSessionSocket.getOutputStream()),
  39. Zygote.SOCKET_BUFFER_SIZE);
  40. } catch (IOException ex) {
  41. try {
  42. zygoteSessionSocket.close();
  43. } catch (IOException ignore) { }
  44. throw ex;
  45. }
  46. // socket、DataInputStream、BufferedWriter 封装成 ZygoteState 对象供外部调用
  47. return new ZygoteState(zygoteSocketAddress, usapSocketAddress,
  48. zygoteSessionSocket, zygoteInputStream, zygoteOutputWriter,
  49. getAbiList(zygoteOutputWriter, zygoteInputStream));
  50. }
  51. }

        ZygoteProcess # openZygoteSocketIfNeeded() 方法,打开与 Zygote 进程的 socket 连接,如果连接未建立,则尝试调用 ZygoteState # connect() 方法创建一个使用给定 Zygote socket 地址的 Socket 连接,然后连接到 Zygote 的远程服务端,同时创建 BufferedWriter 和 DataInputStream 进行参数数据的传输与读取,最后将 socket、DataInputStream、BufferedWriter 等封装成 ZygoteState 对象供外部调用。
 

2.3.8 ZygoteProcess 发送请求参数

  1. @GuardedBy("mLock")
  2. private Process.ProcessStartResult zygoteSendArgsAndGetResult(
  3. ZygoteState zygoteState, int zygotePolicyFlags, @NonNull ArrayList<String> args)
  4. throws ZygoteStartFailedEx {
  5. ......
  6. if (shouldAttemptUsapLaunch(zygotePolicyFlags, args)) {
  7. try {
  8. return attemptUsapSendArgsAndGetResult(zygoteState, msgStr);
  9. } catch (IOException ex) {
  10. // If there was an IOException using the USAP pool we will log the error and
  11. // attempt to start the process through the Zygote.
  12. Log.e(LOG_TAG, "IO Exception while communicating with USAP pool - "
  13. + ex.getMessage());
  14. }
  15. }
  16. return attemptZygoteSendArgsAndGetResult(zygoteState, msgStr);
  17. }
  18. // 用来 fork 出一个新的 Launcher 进程
  19. private Process.ProcessStartResult attemptZygoteSendArgsAndGetResult(
  20. ZygoteState zygoteState, String msgStr) throws ZygoteStartFailedEx {
  21. try {
  22. final BufferedWriter zygoteWriter = zygoteState.mZygoteOutputWriter;
  23. final DataInputStream zygoteInputStream = zygoteState.mZygoteInputStream;
  24. zygoteWriter.write(msgStr);
  25. zygoteWriter.flush();
  26. // Always read the entire result from the input stream to avoid leaving
  27. // bytes in the stream for future process starts to accidentally stumble
  28. // upon.
  29. Process.ProcessStartResult result = new Process.ProcessStartResult();
  30. result.pid = zygoteInputStream.readInt();
  31. result.usingWrapper = zygoteInputStream.readBoolean();
  32. if (result.pid < 0) {
  33. // 进程创建失败
  34. throw new ZygoteStartFailedEx("fork() failed");
  35. }
  36. return result;
  37. } catch (IOException ex) {
  38. zygoteState.close();
  39. Log.e(LOG_TAG, "IO Exception while communicating with Zygote - "
  40. + ex.toString());
  41. throw new ZygoteStartFailedEx(ex);
  42. }
  43. }

        ZygoteProcess # attemptZygoteSendArgsAndGetResult() 方法中使用创建的 ZygoteState 中保存的 BufferedWriter 和 DataInputStream 来进行 Socket 通信,通过它们进行数据流的传输与读取操作。system_server 进程通过 BufferedWriter 将参数写给 Zygote 进程的 socket 的 server 端,然后阻塞等待 Zygote 进程的 socket 返回 pid 和 usingWrapper 后封装到 ProcessStartResult。
 

2.4  Zygote 进程fork并启动应用进程

2.4.1 时序图

2.4.2 Zygote 进程启动、解析 Socket 传入的参数

        Android 系统底层是基于 Linux 的,和 Linux 一样,init 进程是 Linux 系统用户进程的第一个进程,它是由 Linux 内核(kenerl)启动的,用来启动属性服务(类似Windows中的注册表)、启动进程。其它所有的用户进程都是 init 进程的子进程,我们接下来分析的 Zygote 进程也是由 init 进程而创建的,Zygote 如何启动这里暂不讨论,Zygote 启动之后会调用 ZygoteInit # main() 方法,所以我们先从 main() 方法来看 socket 创建和消息读取。代码如下:

  1. public static void main(String argv[]) {
  2. ZygoteServer zygoteServer = null;
  3. ......
  4. Runnable caller;
  5. try {
  6. ......
  7. // 解析参数
  8. boolean startSystemServer = false;
  9. String zygoteSocketName = "zygote";
  10. String abiList = null;
  11. boolean enableLazyPreload = false;
  12. for (int i = 1; i < argv.length; i++) {
  13. if ("start-system-server".equals(argv[i])) {
  14. startSystemServer = true;
  15. } else if ("--enable-lazy-preload".equals(argv[i])) {
  16. enableLazyPreload = true;
  17. } else if (argv[i].startsWith(ABI_LIST_ARG)) {
  18. abiList = argv[i].substring(ABI_LIST_ARG.length());
  19. } else if (argv[i].startsWith(SOCKET_NAME_ARG)) {
  20. zygoteSocketName = argv[i].substring(SOCKET_NAME_ARG.length());
  21. } else {
  22. throw new RuntimeException("Unknown command line argument: " + argv[i]);
  23. }
  24. }
  25. ......
  26. zygoteServer = new ZygoteServer(isPrimaryZygote);
  27. ......
  28. // 调用 runSelectLoop() 开启 Loop 循环来监听 client socket 发来的消息
  29. caller = zygoteServer.runSelectLoop(abiList);
  30. } catch (Throwable ex) {
  31. Log.e(TAG, "System zygote died with exception", ex);
  32. throw ex;
  33. } finally {
  34. if (zygoteServer != null) {
  35. zygoteServer.closeServerSocket();
  36. }
  37. }
  38. // We're in the child process and have exited the select loop. Proceed to execute the command.
  39. // 子进程的启动
  40. if (caller != null) {
  41. caller.run();
  42. }
  43. }

        方法中新建 ZygoteServer 实例对象,调用 ZygoteServer # runSelectLoop() 方法开启 loop 无限循环来监听 client socket 发来的消息,当接收到创建新进程的请求时,立即唤醒并执行相应工作。如果 fork 出系统进程,则加入到列表,然后继续阻塞等待;如果 fork 出子进程,则退出 loop 循环,返回创建的应用子进程,并执行子进程的启动。
 

2.4.3 ZygoteServer 开启 Loop 循环监听 Socket

  1. ZygoteServer(boolean isPrimaryZygote) {
  2. mUsapPoolEventFD = Zygote.getUsapPoolEventFD();
  3. if (isPrimaryZygote) {
  4. mZygoteSocket = Zygote.createManagedSocketFromInitSocket(Zygote.PRIMARY_SOCKET_NAME);
  5. mUsapPoolSocket =
  6. Zygote.createManagedSocketFromInitSocket(
  7. Zygote.USAP_POOL_PRIMARY_SOCKET_NAME);
  8. } else {
  9. mZygoteSocket = Zygote.createManagedSocketFromInitSocket(Zygote.SECONDARY_SOCKET_NAME);
  10. mUsapPoolSocket =
  11. Zygote.createManagedSocketFromInitSocket(
  12. Zygote.USAP_POOL_SECONDARY_SOCKET_NAME);
  13. }
  14. mUsapPoolSupported = true;
  15. fetchUsapPoolPolicyProps();
  16. }
  17. /**
  18. * Runs the zygote process's select loop. Accepts new connections as
  19. * they happen, and reads commands from connections one spawn-request's
  20. * worth at a time.
  21. */
  22. Runnable runSelectLoop(String abiList) {
  23. ArrayList<FileDescriptor> socketFDs = new ArrayList<>();
  24. ArrayList<ZygoteConnection> peers = new ArrayList<>();
  25. // mZygoteSocket 是服务端的 socket 对象,也就是 Zygote 进程所在 socket 放在 fds[0] 位置
  26. socketFDs.add(mZygoteSocket.getFileDescriptor());
  27. // 刚开始默认 peers[0] = null
  28. peers.add(null);
  29. mUsapPoolRefillTriggerTimestamp = INVALID_TIMESTAMP;
  30. // 开启轮询等待
  31. while (true) {
  32. fetchUsapPoolPolicyPropsWithMinInterval();
  33. mUsapPoolRefillAction = UsapPoolRefillAction.NONE;
  34. int[] usapPipeFDs = null;
  35. StructPollfd[] pollFDs;
  36. if (mUsapPoolEnabled) {
  37. usapPipeFDs = Zygote.getUsapPipeFDs();
  38. pollFDs = new StructPollfd[socketFDs.size() + 1 + usapPipeFDs.length];
  39. } else {
  40. pollFDs = new StructPollfd[socketFDs.size()];
  41. }
  42. int pollIndex = 0;
  43. ......
  44. int pollTimeoutMs;
  45. if (mUsapPoolRefillTriggerTimestamp == INVALID_TIMESTAMP) {
  46. pollTimeoutMs = -1;
  47. } else {
  48. long elapsedTimeMs = System.currentTimeMillis() - mUsapPoolRefillTriggerTimestamp;
  49. if (elapsedTimeMs >= mUsapPoolRefillDelayMs) {
  50. pollTimeoutMs = -1;
  51. } else if (elapsedTimeMs <= 0) {
  52. pollTimeoutMs = mUsapPoolRefillDelayMs;
  53. } else {
  54. pollTimeoutMs = (int) (mUsapPoolRefillDelayMs - elapsedTimeMs);
  55. }
  56. }
  57. int pollReturnValue;
  58. try {
  59. // 处理轮询状态,当 pollFds 有事件到来则往下执行,否则阻塞在这里
  60. pollReturnValue = Os.poll(pollFDs, pollTimeoutMs);
  61. } catch (ErrnoException ex) {
  62. throw new RuntimeException("poll failed", ex);
  63. }
  64. if (pollReturnValue == 0) {
  65. mUsapPoolRefillTriggerTimestamp = INVALID_TIMESTAMP;
  66. mUsapPoolRefillAction = UsapPoolRefillAction.DELAYED;
  67. } else {
  68. boolean usapPoolFDRead = false;
  69. // 倒序处理,即优先处理已建立连接的信息,后处理新建连接的请求
  70. while (--pollIndex >= 0) {
  71. // 采用I/O多路复用 epoll 机制,当接收到客户端请求到来,则往下执行;否则跳出本次循环
  72. if ((pollFDs[pollIndex].revents & POLLIN) == 0) {
  73. continue;
  74. }
  75. if (pollIndex == 0) {
  76. // Zygote server socket
  77. // pollIndex==0 表示有新的客户端请求连接到来,调用server socket端的 accpet 函数建立通信连接
  78. // zygote 进程与 system server 进程建立了连接
  79. ZygoteConnection newPeer = acceptCommandPeer(abiList);
  80. // 加入到 peers 和 fds, 即开始下一次监听
  81. peers.add(newPeer);
  82. socketFDs.add(newPeer.getFileDescriptor());
  83. } else if (pollIndex < usapPoolEventFDIndex) {
  84. // Session socket accepted from the Zygote server socket
  85. // socket 连接成功之后从 Zygote 服务器的 socket 接受到的 Session socket
  86. try {
  87. ZygoteConnection connection = peers.get(pollIndex);
  88. final Runnable command = connection.processOneCommand(this);
  89. // TODO (chriswailes): Is this extra check necessary?
  90. if (mIsForkChild) {
  91. ......
  92. return command;
  93. } else {
  94. // 如果不是 fork 子进程则关闭连接,删除当前 fd 消息
  95. if (connection.isClosedByPeer()) {
  96. connection.closeSocket();
  97. peers.remove(pollIndex);
  98. socketFDs.remove(pollIndex);
  99. }
  100. }
  101. } catch (Exception e) {
  102. ......
  103. } finally {
  104. ......
  105. mIsForkChild = false;
  106. }
  107. }
  108. }
  109. ......
  110. }
  111. ......
  112. }
  113. }

runSelectLoop() 方法中获取 zygoteSendArgsAndGetResult() 方法中传输过来的应用进程的启动参数等,即和 Zygote 进程建立起连接,其方法流程如下:

    开启 Loop 死循环监听 socket 事件,没有连接时就阻塞在那里,当有连接到来时唤醒继续往下执行。
    pollIndex==0 时,说明收到请求连接的事件,请求和 Zygote 建立 socket 连接,调用 acceptCommandPeer() 方法创建 ZygoteConnection 对象,并调用 mZygoteSocket # accept() 方法建立 socket 连接,然后添加到监听列表 peers 中,等待与该 socket 有关的命令的到来。
    pollIndex < usapPoolEventFDIndex 时,表示是已经连接的 socket 上的命令到来,此时调用 ZygoteConnection # processOneCommand() 方法来接收客户端传输过来的应用进程的启动参数,并执行进程创建工作,处理完后,就会断开与客户端的连接,并把用于连接的 socket 从监听列表 peers 中移除。
 

2.4.4 ZygoteConnection

  1. Runnable processOneCommand(ZygoteServer zygoteServer) {
  2. String[] args;
  3. try {
  4. // 逐行读取 client 端通过 socket write 过来的启动参数(字符串数组)
  5. args = Zygote.readArgumentList(mSocketReader);
  6. } catch (IOException ex) {
  7. throw new IllegalStateException("IOException on command socket", ex);
  8. }
  9. ......
  10. int pid;
  11. FileDescriptor childPipeFd = null;
  12. FileDescriptor serverPipeFd = null;
  13. // 将数据解析成 ZygoteArguments 格式
  14. ZygoteArguments parsedArgs = new ZygoteArguments(args);
  15. ......
  16. int[][] rlimits = null;
  17. if (parsedArgs.mRLimits != null) {
  18. rlimits = parsedArgs.mRLimits.toArray(Zygote.INT_ARRAY_2D);
  19. }
  20. int[] fdsToIgnore = null;
  21. if (parsedArgs.mInvokeWith != null) {
  22. try {
  23. FileDescriptor[] pipeFds = Os.pipe2(O_CLOEXEC);
  24. childPipeFd = pipeFds[1];
  25. serverPipeFd = pipeFds[0];
  26. Os.fcntlInt(childPipeFd, F_SETFD, 0);
  27. fdsToIgnore = new int[]{childPipeFd.getInt$(), serverPipeFd.getInt$()};
  28. } catch (ErrnoException errnoEx) {
  29. throw new IllegalStateException("Unable to set up pipe for invoke-with", errnoEx);
  30. }
  31. }
  32. // 将 client 端 fd 和 server 端 fd 存入 fdsToClose 数组中,然后 fd 置位 null
  33. int [] fdsToClose = { -1, -1 };
  34. FileDescriptor fd = mSocket.getFileDescriptor();
  35. if (fd != null) {
  36. fdsToClose[0] = fd.getInt$();
  37. }
  38. fd = zygoteServer.getZygoteSocketFileDescriptor();
  39. if (fd != null) {
  40. fdsToClose[1] = fd.getInt$();
  41. }
  42. // 调用 forkAndSpecialize() 方法来 fork 子进程
  43. pid = Zygote.forkAndSpecialize(parsedArgs.mUid, parsedArgs.mGid, parsedArgs.mGids,
  44. parsedArgs.mRuntimeFlags, rlimits, parsedArgs.mMountExternal, parsedArgs.mSeInfo,
  45. parsedArgs.mNiceName, fdsToClose, fdsToIgnore, parsedArgs.mStartChildZygote,
  46. parsedArgs.mInstructionSet, parsedArgs.mAppDataDir, parsedArgs.mIsTopApp,
  47. parsedArgs.mPkgDataInfoList, parsedArgs.mWhitelistedDataInfoList,
  48. parsedArgs.mBindMountAppDataDirs, parsedArgs.mBindMountAppStorageDirs);
  49. try {
  50. if (pid == 0) {
  51. // in child
  52. // pid = 0 表示创建成功,则进入子进程中,即应用程序进程
  53. zygoteServer.setForkChild();
  54. // 关闭 socket 连接
  55. zygoteServer.closeServerSocket();
  56. IoUtils.closeQuietly(serverPipeFd);
  57. serverPipeFd = null;
  58. // 进入子进程执行相关操作
  59. return handleChildProc(parsedArgs, childPipeFd, parsedArgs.mStartChildZygote);
  60. } else {
  61. // In the parent. A pid < 0 indicates a failure and will be handled in handleParentProc.
  62. // pid < 0表示创建失败,则进入父进程返回消息给 client socket 表示启动失败
  63. IoUtils.closeQuietly(childPipeFd);
  64. childPipeFd = null;
  65. // 进入父进程执行相关操作
  66. handleParentProc(pid, serverPipeFd);
  67. return null;
  68. }
  69. } finally {
  70. IoUtils.closeQuietly(childPipeFd);
  71. IoUtils.closeQuietly(serverPipeFd);
  72. }
  73. }

该方法主要作用如下:

    读取 system_server 端 socket 写入的数据,并将存入字符串数组的数据封装成 ZygoteArguments 格式。
    调用 Zygote # forkAndSpecialize() 方法来 fork 子进程,并返回 pid,这里的 pid 并非是进程 id,而是返回结果值,0 表示创建成功,-1 则失败。
    子进程创建成功后进入子进程执行。
 

2.4.5 Zygote 创建子进程(native 层创建)

  1. static int forkAndSpecialize(int uid, int gid, int[] gids, int runtimeFlags,
  2. int[][] rlimits, int mountExternal, String seInfo, String niceName, int[] fdsToClose,
  3. int[] fdsToIgnore, boolean startChildZygote, String instructionSet, String appDataDir,
  4. boolean isTopApp, String[] pkgDataInfoList, String[] whitelistedDataInfoList,
  5. boolean bindMountAppDataDirs, boolean bindMountAppStorageDirs) {
  6. ZygoteHooks.preFork();
  7. // 通过 JNI 调用 native 层方法
  8. int pid = nativeForkAndSpecialize(
  9. uid, gid, gids, runtimeFlags, rlimits, mountExternal, seInfo, niceName, fdsToClose,
  10. fdsToIgnore, startChildZygote, instructionSet, appDataDir, isTopApp,
  11. pkgDataInfoList, whitelistedDataInfoList, bindMountAppDataDirs,
  12. bindMountAppStorageDirs);
  13. if (pid == 0) {
  14. // Note that this event ends at the end of handleChildProc,
  15. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "PostFork");
  16. // If no GIDs were specified, don't make any permissions changes based on groups.
  17. if (gids != null && gids.length > 0) {
  18. NetworkUtils.setAllowNetworkingForProcess(containsInetGid(gids));
  19. }
  20. }
  21. // Set the Java Language thread priority to the default value for new apps.
  22. Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
  23. ZygoteHooks.postForkCommon();
  24. return pid;
  25. }

        方法中调用 native 层的 nativeForkAndSpecialize() 方法创建进程,然后返回进程的 pid(父进程中,返回新建的子进程的 pid,子进程中,则返回 0,出现错误时返回负数),具体 native 层的源码就不跟了,大致看了一下过程:

    调用 Linux 的 fork() 方法创建进程,设置进程的主线程的 name,如果是 null 或者 system_server,则为 system_server。
    调用 CallStaticVoidMethod() 方法返回 Zygote # callPostForkChildHooks() 方法处理 fork 子线程之后的 gc/线程池管理等操作。
 

2.4.6 ZygoteConnection # handleChildProc() 方法

  1. private Runnable handleChildProc(ZygoteArguments parsedArgs,
  2. FileDescriptor pipeFd, boolean isZygote) {
  3. // 关闭 socket 连接
  4. closeSocket();
  5. // 设置应用进程的 name 名
  6. Zygote.setAppProcessName(parsedArgs, TAG);
  7. // End of the postFork event.
  8. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  9. if (parsedArgs.mInvokeWith != null) {
  10. WrapperInit.execApplication(parsedArgs.mInvokeWith,
  11. parsedArgs.mNiceName, parsedArgs.mTargetSdkVersion,
  12. VMRuntime.getCurrentInstructionSet(),
  13. pipeFd, parsedArgs.mRemainingArgs);
  14. // Should not get here.
  15. throw new IllegalStateException("WrapperInit.execApplication unexpectedly returned");
  16. } else {
  17. if (!isZygote) {
  18. return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
  19. parsedArgs.mDisabledCompatChanges,
  20. parsedArgs.mRemainingArgs, null /* classLoader */);
  21. } else {
  22. return ZygoteInit.childZygoteInit(parsedArgs.mTargetSdkVersion,
  23. parsedArgs.mRemainingArgs, null /* classLoader */);
  24. }
  25. }
  26. }

该方法就是进入子进程执行不同的初始化操作,因为已经 fork() 成功,关闭 socket 连接等释放资源,设置应用进程的 name,最后调用 ZygoteInit # zygoteInit() 方法初始化 Zygote。

2.4.7 ZygoteInit # zygoteInit() 方法

  1. public static final Runnable zygoteInit(int targetSdkVersion, long[] disabledCompatChanges,
  2. String[] argv, ClassLoader classLoader) {
  3. ......
  4. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");
  5. RuntimeInit.redirectLogStreams();
  6. // 进程初始化配置,如设置异常捕获 Handler、时区、重置 LogManager 等等
  7. RuntimeInit.commonInit();
  8. // native 层初始化 -- 打开/dev/binder 驱动,映射内核的地址空间,创建 binder 线程用于 IPC 通信
  9. ZygoteInit.nativeZygoteInit();
  10. return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv,
  11. classLoader);
  12. }

方法流程如下:

    日志流重定向,将系统输出和系统错误重定向到 Android 日志。
    进程初始化配置,如设置异常捕获 Handler、时区、重置 LogManager 等等。
    native 层初始化,打开 /dev/binder 驱动,映射内核的地址空间,创建 binder 线程用于 IPC 通信。
    调用 RuntimeInit # applicationInit() 方法,返回创建的 Runnable 对象。
 

2.4.8 RuntimeInit # applicationInit() 方法

  1. protected static Runnable applicationInit(int targetSdkVersion, long[] disabledCompatChanges,
  2. String[] argv, ClassLoader classLoader) {
  3. // 如果应用程序调用了 System.exit() 方法立即终止进程,可能会导致剩余的运行线程在进程实际退出之前崩溃
  4. nativeSetExitWithoutCleanup(true);
  5. VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);
  6. VMRuntime.getRuntime().setDisabledCompatChanges(disabledCompatChanges);
  7. final Arguments args = new Arguments(argv);
  8. // The end of of the RuntimeInit event (see #zygoteInit).
  9. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  10. // Remaining arguments are passed to the start class's static main
  11. return findStaticMain(args.startClass, args.startArgs, classLoader);
  12. }
  13. protected static Runnable findStaticMain(String className, String[] argv,
  14. ClassLoader classLoader) {
  15. // 待加载的类、这里是指 ActivityThread,也就是我们第三节中在 ProcessList 中指明的 entryPoint
  16. Class<?> cl;
  17. try {
  18. // 加载 android.app.ActivityThread 类
  19. cl = Class.forName(className, true, classLoader);
  20. } catch (ClassNotFoundException ex) {
  21. throw new RuntimeException(
  22. "Missing class when invoking static main " + className, ex);
  23. }
  24. // 获取 main 方法
  25. Method m;
  26. try {
  27. // 获取 ActivityThread # main() 函数
  28. m = cl.getMethod("main", new Class[] { String[].class });
  29. } catch (NoSuchMethodException ex) {
  30. throw new RuntimeException("Missing static main on " + className, ex);
  31. } catch (SecurityException ex) {
  32. throw new RuntimeException("Problem getting static main on " + className, ex);
  33. }
  34. // 判断 main 方法是不是 public 并且 static 类型
  35. int modifiers = m.getModifiers();
  36. if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
  37. throw new RuntimeException("Main method is not public and static on " + className);
  38. }
  39. // 返回 Caller,即本小节第一部分的 ZygoteInit.main() 中的 caller
  40. return new MethodAndArgsCaller(m, argv);
  41. }

        applicationInit() 方法中首先做了一个 System.exit() 的保护,防止退出进程时发生 crash,设置 targetSDKVersion 等参数,最后调用 findStaticMain() 方法去加载 ActivityThread 类以及方法。

        findStaticMain() 方法中通过 ClassLoader 加载获取目标类 ActivityThread,后获取其静态 main 方法,然后封装成 MethodAndArgsCaller 对象返回,MethodAndArgsCaller 实现了 Runnable 接口。即返回到 2. Zygote 进程启动、解析 Socket 传入的参数 这节中 ZygoteInit # main() 方法的 caller,如果 caller!=null 会调用这个 Runnable 的 run() 方法。

2.4.9 RuntimeInit # MethodAndArgsCaller

  1. static class MethodAndArgsCaller implements Runnable {
  2. /** method to call */
  3. private final Method mMethod;
  4. /** argument array */
  5. private final String[] mArgs;
  6. public MethodAndArgsCaller(Method method, String[] args) {
  7. mMethod = method;
  8. mArgs = args;
  9. }
  10. public void run() {
  11. try {
  12. mMethod.invoke(null, new Object[] { mArgs });
  13. } catch (IllegalAccessException ex) {
  14. throw new RuntimeException(ex);
  15. } catch (InvocationTargetException ex) {
  16. ......
  17. }
  18. }
  19. }

        MethodAndArgsCaller # run() 方法中使用了 invoke 反射调用,至此 ActivityThread 的 main() 方法得以执行,应用进程也就成功启动 ActivityThread。


2.4.10. 小结

Zygote 进程启动流程:

    init 进程为用户空间(相对于内核空间)的第一个进程,根据 init.rc 启动 Zygote 进程。
    Zygote 进程启动步骤:创建虚拟机、注册JNI、执行 ZygoteInit # main() 方法。
    Zygote 进程启动 system_server 进程(Zygote 启动的第一个进程),这个本小节没有具体分析。
    Zygote 创建 socket 连接通道,阻塞并等待新建进程的指令到来,通过 fork 新建用户进程。
    Zygote 新加了一个优化进程创建的机制,UsapPool - 池化机制,我跟了一下源码,是预先缓存了几个进程。
 

2.5 应用进程 ActivityThread 启动 Activity 的过程

        ActivityThread 类是应用初始化类,它的 main() 方法是应用的入口方法,它也是我们说的“主线程”,但是 ActivityThread 本身不是一个线程,之所以称它为“主线程”,是因为它运行在主线程中。所以说 ActivityThread 是主线程的一部分,但不并能代表主线程。

    1,ActivityThread 负责创建 Application 对象以及管理其生命周期方法调用。
    2,ActivityThread 管理着四大组件的生命周期方法调用。
 

2.5.1 时序图

2.5.2 ActivityThread 入口方法

  1. public final class ActivityThread extends ClientTransactionHandler {
  2. // 初始化 ApplicationThread
  3. final ApplicationThread mAppThread = new ApplicationThread();
  4. // 初始化 Handler,ApplicationThread 和 ActivityThread 通信使用
  5. final H mH = new H();
  6. public static void main(String[] args) {
  7. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
  8. ......
  9. // Call per-process mainline module initialization.
  10. initializeMainlineModules();
  11. Process.setArgV0("<pre-initialized>");
  12. // 初始化主线程的 Looper
  13. Looper.prepareMainLooper();
  14. ...... // 获取 startSeq
  15. // 实例化 ActivityThread
  16. ActivityThread thread = new ActivityThread();
  17. //
  18. thread.attach(false, startSeq);
  19. if (sMainThreadHandler == null) {
  20. // sMainThreadHandler = mH
  21. sMainThreadHandler = thread.getHandler();
  22. }
  23. // End of event ActivityThreadMain.
  24. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  25. // 开启 Looper 循环,等待接收消息
  26. Looper.loop();
  27. // 正常不会走到这里,除非是非正常退出了 looper 循环
  28. throw new RuntimeException("Main thread loop unexpectedly exited");
  29. }
  30. private void attach(boolean system, long startSeq) {
  31. sCurrentActivityThread = this;
  32. mSystemThread = system;
  33. if (!system) {
  34. android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
  35. UserHandle.myUserId());
  36. RuntimeInit.setApplicationObject(mAppThread.asBinder());
  37. final IActivityManager mgr = ActivityManager.getService();
  38. try {
  39. mgr.attachApplication(mAppThread, startSeq);
  40. }
  41. ......
  42. } else {
  43. android.ddm.DdmHandleAppName.setAppName("system_process",
  44. UserHandle.myUserId());
  45. try {
  46. mInstrumentation = new Instrumentation();
  47. mInstrumentation.basicInit(this);
  48. ContextImpl context = ContextImpl.createAppContext(
  49. this, getSystemContext().mPackageInfo);
  50. mInitialApplication = context.mPackageInfo.makeApplication(true, null);
  51. mInitialApplication.onCreate();
  52. }
  53. ......
  54. }
  55. ......
  56. }
  57. }

        ActivityThread # attach() 方法中,使用 Binder 通信跨进程调用到 system_server 进程中 AMS 的 attachApplication() 方法,并将 ApplicationThread 作为参数传递过去。

2.5.3 AMS 绑定 ApplicationThread

  1. // ActivityTaskManagerInternal 是一个抽象类,实现类是 ATMS 的内部类 LocalService
  2. // ATMS 启动的时候,通过 LocalServices # addService() 注册到 LocalServices
  3. public ActivityTaskManagerInternal mAtmInternal;
  4. public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
  5. ......
  6. mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);
  7. ......
  8. }
  9. @Override
  10. public final void attachApplication(IApplicationThread thread, long startSeq) {
  11. if (thread == null) {
  12. throw new SecurityException("Invalid application interface");
  13. }
  14. synchronized (this) {
  15. int callingPid = Binder.getCallingPid();
  16. final int callingUid = Binder.getCallingUid();
  17. final long origId = Binder.clearCallingIdentity();
  18. attachApplicationLocked(thread, callingPid, callingUid, startSeq);
  19. Binder.restoreCallingIdentity(origId);
  20. }
  21. }
  22. @GuardedBy("this")
  23. private boolean attachApplicationLocked(@NonNull IApplicationThread thread,
  24. int pid, int callingUid, long startSeq) {
  25. ......
  26. // 保存当前正在运行的进程的所有信息
  27. ProcessRecord app;
  28. ......
  29. try {
  30. ......
  31. // 跨进程调用应用进程 ApplicationThread # bindApplication()创建绑定 Application
  32. thread.bindApplication(processName, appInfo, providerList, null, profilerInfo,
  33. null, null, null, testMode,
  34. mBinderTransactionTrackingEnabled, enableTrackAllocation,
  35. isRestrictedBackupMode || !normalMode, app.isPersistent(),
  36. new Configuration(app.getWindowProcessController().getConfiguration()),
  37. app.compat, getCommonServicesLocked(app.isolated),
  38. mCoreSettingsObserver.getCoreSettingsLocked(),
  39. buildSerial, autofillOptions, contentCaptureOptions,
  40. app.mDisabledCompatChanges);
  41. // Make app active after binding application or client may be running requests (e.g
  42. // starting activities) before it is ready.
  43. // 保存 应用进程 IApplicationThread
  44. app.makeActive(thread, mProcessStats);
  45. ......
  46. }
  47. ......
  48. boolean didSomething = false;
  49. // See if the top visible activity is waiting to run in this process...
  50. if (normalMode) {
  51. try {
  52. // 通过 ATMS 启动根 Activity
  53. didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
  54. }
  55. ......
  56. }
  57. return true;
  58. }

        AMS # attachApplication() 方法,在获取到 pid、uid 后继续调用 AMS # attachApplicationLocked() 方法。
AMS # attachApplicationLocked() 方法中关注以下流程:

        通过跨进程通信调用应用进程中 ApplicationThread # bindApplication() 创建并绑定 Application。
        ProcessRecord 调用 makeActive() 方法保存应用进程 IApplicationThread。通过 ActivityTaskManagerInternal 本地服务过渡到 ATMS 启动根 Activity。

2.5.4 ActivityThread 创建并绑定 Application

        IApplicationThread # bindApplication() 方法调用的是应用进程中的实现类 ApplicationThread # bindApplication() 方法,方法中通过内部类 H 发送 Handler 消息,进而调用到 ActivityThread # handleBindApplication() 方法,代码如下:

  1. @UnsupportedAppUsage
  2. private void handleBindApplication(AppBindData data) {
  3. ......
  4. final ContextImpl appContext = ContextImpl.createAppContext(this, data.info);
  5. updateLocaleListFromAppContext(appContext,
  6. mResourcesManager.getConfiguration().getLocales());
  7. ......
  8. if (ii != null) {
  9. ......
  10. final LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
  11. appContext.getClassLoader(), false, true, false);
  12. final ContextImpl instrContext = ContextImpl.createAppContext(this, pi,
  13. appContext.getOpPackageName());
  14. try {
  15. // 获取 ClassLoader 加载类文件
  16. final ClassLoader cl = instrContext.getClassLoader();
  17. // 获取 Instrumentation 类并构建实例对象
  18. mInstrumentation = (Instrumentation)
  19. cl.loadClass(data.instrumentationName.getClassName()).newInstance();
  20. }
  21. ......
  22. final ComponentName component = new ComponentName(ii.packageName, ii.name);
  23. mInstrumentation.init(this, instrContext, appContext, component,
  24. data.instrumentationWatcher, data.instrumentationUiAutomationConnection);
  25. ......
  26. }
  27. ......
  28. Application app;
  29. ......
  30. try {
  31. // 创建 Application
  32. app = data.info.makeApplication(data.restrictedBackupMode, null);
  33. ......
  34. mInitialApplication = app;
  35. ......
  36. try {
  37. mInstrumentation.onCreate(data.instrumentationArgs);
  38. }
  39. ......
  40. try {
  41. // 内部调用 Application # onCreate() 的方法
  42. // 故 Application # onCreate() 比 ActivityThread 的 main() 方法慢执行
  43. // 但是会比所有该应用 Activity 的生命周期先调用,因为此时的 Activity 还没启动
  44. mInstrumentation.callApplicationOnCreate(app);
  45. }
  46. ......
  47. }
  48. ......
  49. }

2.5.5 ProcessRecord 保存 ApplicationThread

  1. public void makeActive(IApplicationThread _thread, ProcessStatsService tracker) {
  2. ......
  3. thread = _thread;
  4. mWindowProcessController.setThread(thread);
  5. }

        方法内将流程交给 WindowProcessController 并调用其 setThread() 方法存储 IApplicationThread,代码如下:

  1. public class WindowProcessController extends ConfigurationContainer<ConfigurationContainer>
  2. implements ConfigurationContainerListener {
  3. private IApplicationThread mThread;
  4. @HotPath(caller = HotPath.PROCESS_CHANGE)
  5. public void setThread(IApplicationThread thread) {
  6. synchronized (mAtm.mGlobalLockWithoutBoost) {
  7. mThread = thread;
  8. if (thread != null) {
  9. setLastReportedConfiguration(getConfiguration());
  10. }
  11. }
  12. }
  13. IApplicationThread getThread() {
  14. return mThread;
  15. }
  16. boolean hasThread() {
  17. return mThread != null;
  18. }
  19. }

        WindowProcessController # setThread() 方法中将传入的 IApplicationThread 赋值给 mThread 中保存,此时 WindowProcessController 中的 IApplicationThread 才有值,同时也解释了第二部分最后提出的问题。而我们在启动根 Activity 的时候,在第二部分的 7. ActivityStackSupervisor 的 startSpecificActivity() 方法中通过 wpc.hasThread() 是获取不到 IApplicationThread,是因为那时应用进程还没创建好,也就没有给 WindowProcessController 中的 IApplicationThread 赋值。

2.5.6 ATMS 绑定 WindowProcessController、启动根 Activity

  1. public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
  2. // 启动的时候注册到 LocalServices 中
  3. private void start() {
  4. LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
  5. }
  6. final class LocalService extends ActivityTaskManagerInternal {
  7. ......
  8. @HotPath(caller = HotPath.PROCESS_CHANGE)
  9. @Override
  10. public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
  11. synchronized (mGlobalLockWithoutBoost) {
  12. if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
  13. Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
  14. }
  15. try {
  16. // 调用 RootWindowContainer # attachApplication()
  17. return mRootWindowContainer.attachApplication(wpc);
  18. } finally {
  19. Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
  20. }
  21. }
  22. }
  23. ......
  24. }
  25. }

        ActivityTaskManagerInternal 是一个抽象类,实现类是 ATMS 的内部类 LocalService,这是一个本地服务,在 ATMS 启动的时候,通过 LocalServices # addService() 注册到 LocalServices 中。在 AMS 的构造方法中通过 LocalServices # getService() 方法获取到注册的本地服务。所以 AMS 中调用 ActivityTaskManagerInternal 的方法,实际上调用的是 ATMS 中的 实现类 LocalService 的方法。该方法继续调用 RootWindowContainer # attachApplication() 方法,启动流程交给 RootWindowContainer 处理。
 

2.5.7 RootWindowContainer 绑定 WindowProcessController

  1. boolean attachApplication(WindowProcessController app) throws RemoteException {
  2. final String processName = app.mName;
  3. boolean didSomething = false;
  4. for (int displayNdx = getChildCount() - 1; displayNdx >= 0; --displayNdx) {
  5. final DisplayContent display = getChildAt(displayNdx);
  6. final ActivityStack stack = display.getFocusedStack();
  7. if (stack == null) {
  8. continue;
  9. }
  10. mTmpRemoteException = null;
  11. mTmpBoolean = false; // Set to true if an activity was started.
  12. final PooledFunction c = PooledLambda.obtainFunction(
  13. RootWindowContainer::startActivityForAttachedApplicationIfNeeded, this,
  14. PooledLambda.__(ActivityRecord.class), app, stack.topRunningActivity());
  15. stack.forAllActivities(c);
  16. c.recycle();
  17. if (mTmpRemoteException != null) {
  18. throw mTmpRemoteException;
  19. }
  20. didSomething |= mTmpBoolean;
  21. }
  22. if (!didSomething) {
  23. ensureActivitiesVisible(null, 0, false /* preserve_windows */);
  24. }
  25. return didSomething;
  26. }
  27. private boolean startActivityForAttachedApplicationIfNeeded(ActivityRecord r,
  28. WindowProcessController app, ActivityRecord top) {
  29. if (r.finishing || !r.okToShowLocked() || !r.visibleIgnoringKeyguard || r.app != null
  30. || app.mUid != r.info.applicationInfo.uid || !app.mName.equals(r.processName)) {
  31. return false;
  32. }
  33. try {
  34. if (mStackSupervisor.realStartActivityLocked(r, app, top == r /*andResume*/,
  35. true /*checkConfig*/)) {
  36. mTmpBoolean = true;
  37. }
  38. } catch (RemoteException e) {
  39. .....
  40. return true;
  41. }
  42. return false;
  43. }

        RootWindowContainer # attachApplication() 方法中,调用到 RootWindowContainer # startActivityForAttachedApplicationIfNeeded() 方法,如何调用到的该方法可以参考第三部分 2. ActivityTaskManagerService 启动进程。RootWindowContainer # startActivityForAttachedApplicationIfNeeded() 方法中继续调用 ActivityStackSupervisor # realStartActivityLocked() 方法来真正的启动 Activity。

2.5.8 获取 ClientTransaction、添加 Callback、设置 LifecycleStateRequest

  1. boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
  2. boolean andResume, boolean checkConfig) throws RemoteException {
  3. final Task task = r.getTask();
  4. final ActivityStack stack = task.getStack();
  5. beginDeferResume();
  6. try {
  7. r.startFreezingScreenLocked(proc, 0);
  8. ......
  9. try {
  10. ......
  11. // Create activity launch transaction.
  12. // 获取 ClientTransaction 实例
  13. final ClientTransaction clientTransaction = ClientTransaction.obtain(
  14. proc.getThread(), r.appToken);
  15. final DisplayContent dc = r.getDisplay().mDisplayContent;
  16. // ClientTransaction 实例添加 ClientTransactionItem 类型的回调消息
  17. clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
  18. System.identityHashCode(r), r.info,
  19. // TODO: Have this take the merged configuration instead of separate global
  20. // and override configs.
  21. mergedConfiguration.getGlobalConfiguration(),
  22. mergedConfiguration.getOverrideConfiguration(), r.compat,
  23. r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(),
  24. r.getSavedState(), r.getPersistentSavedState(), results, newIntents,
  25. dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
  26. r.assistToken, r.createFixedRotationAdjustmentsIfNeeded()));
  27. // 所需的最终生命周期状态请求
  28. final ActivityLifecycleItem lifecycleItem;
  29. // 判断此时的生命周期状态是走 onResume 还是 onPause
  30. if (andResume) {
  31. // 由于此时 ActivityStack 栈中只有一个 Activity,所以 top == r 为 true,因此应赋值为 ResumeActivityItem
  32. lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
  33. } else {
  34. lifecycleItem = PauseActivityItem.obtain();
  35. }
  36. // 设置执行 transaction 后的最终的生命周期状态请求
  37. clientTransaction.setLifecycleStateRequest(lifecycleItem);
  38. // ClientLifecycleManager 调度 ClientTransaction
  39. mService.getLifecycleManager().scheduleTransaction(clientTransaction);
  40. ......
  41. } catch (RemoteException e) {
  42. // 启动失败,移除 ActivityRecord
  43. r.launchFailed = true;
  44. proc.removeActivity(r);
  45. throw e;
  46. }
  47. } finally {
  48. endDeferResume();
  49. }
  50. return true;
  51. }

该方法执行流程如下:

    创建 ClientTransaction 实例,其中参数 proc.getThread() 是 IApplicationThread 类型,mActivityToken 为 IBinder 类型。
    ClientTransaction 实例添加 ClientTransactionItem 类型的回调消息,注意:这里添加的是 LaunchActivityItem 实例,LaunchActivityItem 继承自 ClientTransactionItem 抽象类并实现其中的方法。
    获取 ClientLifecycleManager 实例,调用其 scheduleTransaction() 方法去调度转换事务 Transaction 的执行。
 

2.5.9 ClientTransaction 获取、添加事务回调

  1. // 客户端的单个回调列表
  2. @UnsupportedAppUsage
  3. private List<ClientTransactionItem> mActivityCallbacks;
  4. // 执行事务后客户端活动应处于的最终生命周期状态
  5. private ActivityLifecycleItem mLifecycleStateRequest;
  6. /** Target client. */
  7. private IApplicationThread mClient;
  8. /** Target client activity. Might be null if the entire transaction is targeting an app. */
  9. private IBinder mActivityToken;
  10. /** Obtain an instance initialized with provided params. */
  11. // 获取 ClientTransaction 实例
  12. public static ClientTransaction obtain(IApplicationThread client, IBinder activityToken) {
  13. ClientTransaction instance = ObjectPool.obtain(ClientTransaction.class);
  14. if (instance == null) {
  15. instance = new ClientTransaction();
  16. }
  17. instance.mClient = client;
  18. instance.mActivityToken = activityToken;
  19. return instance;
  20. }
  21. /**
  22. * 在 ClientTransaction 的 callbacks 列表尾部添加 ClientTransactionItem 类型的消息
  23. * 参数:包含生命周期请求或回调的单个消息
  24. * @param activityCallback A single message that can contain a lifecycle request/callback.
  25. */
  26. public void addCallback(ClientTransactionItem activityCallback) {
  27. if (mActivityCallbacks == null) {
  28. mActivityCallbacks = new ArrayList<>();
  29. }
  30. mActivityCallbacks.add(activityCallback);
  31. }
  32. /**
  33. * Set the lifecycle state in which the client should be after executing the transaction.
  34. * 设置客户端在执行事务后应处于的生命周期状态
  35. * @param stateRequest A lifecycle request initialized with right parameters.
  36. */
  37. public void setLifecycleStateRequest(ActivityLifecycleItem stateRequest) {
  38. mLifecycleStateRequest = stateRequest;
  39. }

ClientTransaction 是保存一系列待发送给客户端处理的事务消息的容器,包括一个 Callback 列表和一个最终生命周期状态。

2.5.10 ClientLifecycleManager 客户端生命周期事务转换管理器

  1. /**
  2. * Schedule a transaction, which may consist of multiple callbacks and a lifecycle request.
  3. * 安排调度一个事务(启动、暂停等 Activity 事务),可能包含多个回调和一个生命周期请求
  4. * @param transaction A sequence of client transaction items.
  5. * @throws RemoteException
  6. *
  7. * @see ClientTransaction
  8. */
  9. void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
  10. final IApplicationThread client = transaction.getClient();
  11. transaction.schedule();
  12. if (!(client instanceof Binder)) {
  13. // If client is not an instance of Binder - it's a remote call and at this point it is
  14. // safe to recycle the object. All objects used for local calls will be recycled after
  15. // the transaction is executed on client in ActivityThread.
  16. transaction.recycle();
  17. }
  18. }

ClientLifecycleManager 能够组合多个客户端生命周期转换请求与回调,并将其作为单个事务调度执行。

2.5.11 ClientTransaction # schedule() 调度事务

  1. /**
  2. * Schedule the transaction after it was initialized. It will be send to client and all its
  3. * individual parts will be applied in the following sequence:
  4. * 1. The client calls {@link #preExecute(ClientTransactionHandler)}, which triggers all work
  5. * that needs to be done before actually scheduling the transaction for callbacks and
  6. * lifecycle state request.
  7. * 2. The transaction message is scheduled.
  8. * 3. The client calls {@link TransactionExecutor#execute(ClientTransaction)}, which executes
  9. * all callbacks and necessary lifecycle transitions.
  10. */
  11. public void schedule() throws RemoteException {
  12. mClient.scheduleTransaction(this);
  13. }

看一下方法的注释,大概意思是事务初始化之后调度事务,其所有单独部分将按以下顺序发送到客户端:

    客户端调用 preExecute() 方法,在实际调度事务的回调和生命周期状态请求之前,触发所有需要完成的任务。
    事务消息已被调度。
    客户端调用 TransactionExecutor # execute() 方法,执行所有回调和必要的生命周期转换。

通过上面第 8、9 小节的源码解析可以看出,这里 mClient 是 IApplicationThread 类型,它是极其重要的一个 Binder 接口,维护了应用进程和 system_server 进程中 AMS 之间的 IPC 通讯,mClient 就是应用进程在系统进程中的代理对象,AMS 通过 mClient 与此时作为服务端的应用进程进行通信。而应用进程中的实现类 ApplicationThread 是 ActivityThread 的内部类,继承自 IApplicationThread.Stub,实现了 Binder 接口,此时作为服务端接受 system_server 进程中 AMS 发出的请求并执行,也就是流程切到应用进程继续执行。
 

2.5.12 ActivityThread 调度事务

  1. public abstract class ClientTransactionHandler {
  2. /** Prepare and schedule transaction for execution. */
  3. void scheduleTransaction(ClientTransaction transaction) {
  4. transaction.preExecute(this);
  5. // 发送 Handler 消息到 ActivityThread.H 中
  6. sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
  7. }
  8. /**
  9. * Get the {@link TransactionExecutor} that will be performing lifecycle transitions and
  10. * callbacks for activities.
  11. */
  12. abstract TransactionExecutor getTransactionExecutor();
  13. // ActivityThread 实现该抽象方法,然后调用其内部的 mH 发送消息并处理
  14. abstract void sendMessage(int what, Object obj);
  15. }
  16. public final class ActivityThread extends ClientTransactionHandler {
  17. final H mH = new H();
  18. // An executor that performs multi-step transactions.
  19. private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);
  20. // 应用进程中 IApplicationThread 的实现类,继续调用 ActivityThread 的方法
  21. private class ApplicationThread extends IApplicationThread.Stub {
  22. @Override
  23. public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
  24. // 执行父类 ClientTransactionHandler # scheduleTransaction()
  25. ActivityThread.this.scheduleTransaction(transaction);
  26. }
  27. }
  28. class H extends Handler {
  29. ......
  30. public static final int EXECUTE_TRANSACTION = 159; // 执行事务
  31. public void handleMessage(Message msg) {
  32. ......
  33. switch (msg.what) {
  34. ......
  35. case EXECUTE_TRANSACTION:
  36. // 获取传递过来的 ClientTransaction
  37. final ClientTransaction transaction = (ClientTransaction) msg.obj;
  38. // TransactionExecutor
  39. mTransactionExecutor.execute(transaction);
  40. if (isSystem()) {
  41. // Client transactions inside system process are recycled on the client side
  42. // instead of ClientLifecycleManager to avoid being cleared before this
  43. // message is handled.
  44. transaction.recycle();
  45. }
  46. // TODO(lifecycler): Recycle locally scheduled transactions.
  47. break;
  48. ......
  49. }
  50. ......
  51. }
  52. }
  53. void sendMessage(int what, Object obj) {
  54. sendMessage(what, obj, 0, 0, false);
  55. }
  56. ......
  57. private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
  58. ......
  59. Message msg = Message.obtain();
  60. msg.what = what;
  61. msg.obj = obj;
  62. msg.arg1 = arg1;
  63. msg.arg2 = arg2;
  64. if (async) {
  65. msg.setAsynchronous(true);
  66. }
  67. mH.sendMessage(msg);
  68. }
  69. }

执行流程如下:

    ApplicationThread # scheduleTransaction() 方法中又继续调用 ActivityThread # scheduleTransaction() 方法,而 ActivityThread 自身没有这个方法,因此执行父类 ClientTransactionHandler # scheduleTransaction() 方法。
    ClientTransactionHandler # scheduleTransaction() 方法中通过继承自 Handler 的实现类 H 发送消息到 ActivityThread 中,并重写了其 handleMessage() 方法。
    H # handleMessage() 方法中获取传递过来的 ClientTransaction,并由 TransactionExecutor # execute() 执行该 ClientTransaction 的转换。
 

2.5.13 TransactionExecutor 事务转换执行器

  1. public void execute(ClientTransaction transaction) {
  2. final IBinder token = transaction.getActivityToken();
  3. if (token != null) {
  4. final Map<IBinder, ClientTransactionItem> activitiesToBeDestroyed =
  5. mTransactionHandler.getActivitiesToBeDestroyed();
  6. final ClientTransactionItem destroyItem = activitiesToBeDestroyed.get(token);
  7. if (destroyItem != null) {
  8. if (transaction.getLifecycleStateRequest() == destroyItem) {
  9. // 执行销毁与该 token 有关的 Activity 的事务,然后与此有关的记录将被移除
  10. activitiesToBeDestroyed.remove(token);
  11. }
  12. if (mTransactionHandler.getActivityClient(token) == null) {
  13. // Activity 还未完成创建就请求销毁,所以与这个 token 有关的事务都要取消
  14. Slog.w(TAG, tId(transaction) + "Skip pre-destroyed transaction:\n"
  15. + transactionToString(transaction, mTransactionHandler));
  16. return;
  17. }
  18. }
  19. }
  20. // 执行事务的回调 -- 第 8 小节中添加到 ClientTransaction 中的回调 -- LaunchActivityItem
  21. executeCallbacks(transaction);
  22. // 执行生命周期状态
  23. executeLifecycleState(transaction);
  24. mPendingActions.clear();
  25. }
  26. /**
  27. * Cycle through all states requested by callbacks and execute them at proper times.
  28. * 循环遍历回调列表中的所有状态请求,在适当的时间执行它们
  29. */
  30. @VisibleForTesting
  31. public void executeCallbacks(ClientTransaction transaction) {
  32. final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
  33. if (callbacks == null || callbacks.isEmpty()) {
  34. return;
  35. }
  36. final IBinder token = transaction.getActivityToken();
  37. ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
  38. final ActivityLifecycleItem finalStateRequest = transaction.getLifecycleStateRequest();
  39. final int finalState = finalStateRequest != null ? finalStateRequest.getTargetState()
  40. : UNDEFINED;
  41. // Index of the last callback that requests some post-execution state.
  42. final int lastCallbackRequestingState = lastCallbackRequestingState(transaction);
  43. final int size = callbacks.size();
  44. for (int i = 0; i < size; ++i) {
  45. final ClientTransactionItem item = callbacks.get(i);
  46. ......// 执行回调并输出日志
  47. final int postExecutionState = item.getPostExecutionState();
  48. final int closestPreExecutionState = mHelper.getClosestPreExecutionState(r,
  49. item.getPostExecutionState());
  50. if (closestPreExecutionState != UNDEFINED) {
  51. cycleToPath(r, closestPreExecutionState, transaction);
  52. }
  53. // 获取到 LaunchActivityItem 并调用其 execute() 方法
  54. item.execute(mTransactionHandler, token, mPendingActions);
  55. item.postExecute(mTransactionHandler, token, mPendingActions);
  56. if (r == null) {
  57. // 启动活动请求将创建一个活动记录
  58. r = mTransactionHandler.getActivityClient(token);
  59. }
  60. if (postExecutionState != UNDEFINED && r != null) {
  61. final boolean shouldExcludeLastTransition =
  62. i == lastCallbackRequestingState && finalState == postExecutionState;
  63. cycleToPath(r, postExecutionState, shouldExcludeLastTransition, transaction);
  64. }
  65. }
  66. }

TransactionExecutor # executeCallbacks() 方法中,循环遍历回调列表中的所有状态请求,并在适当的时间执行添加的状态请求,这里即 8. 获取 ClientTransaction、添加 Callback、设置 LifecycleStateRequest 中添加到 ClientTransaction 中的 LaunchActivityItem。
 

2.5.14 LaunchActivityItem 请求启动 Activity

  1. /**
  2. 1. Request to launch an activity.
  3. 2. 请求启动 Activity
  4. 3. @hide
  5. */
  6. public class LaunchActivityItem extends ClientTransactionItem {
  7. @Override
  8. public void execute(ClientTransactionHandler client, IBinder token,
  9. PendingTransactionActions pendingActions) {
  10. Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
  11. ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
  12. mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
  13. mPendingResults, mPendingNewIntents, mIsForward,
  14. mProfilerInfo, client, mAssistToken, mFixedRotationAdjustments);
  15. client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
  16. Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
  17. }
  18. }

ClientTransactionHandler 是一个抽象类,ActivityThread 继承自 ClientTransactionHandler 并实现了其抽象方法,所以这里又回到了 ActivityThread 类,调用其 handleLaunchActivity() 方法来启动 Activity。
 

2.5.15 ActivityThread 执行启动 Activity 事务

  1. @Override
  2. public Activity handleLaunchActivity(ActivityClientRecord r,
  3. PendingTransactionActions pendingActions, Intent customIntent) {
  4. ......
  5. WindowManagerGlobal.initialize();
  6. // Hint the GraphicsEnvironment that an activity is launching on the process.
  7. GraphicsEnvironment.hintActivityLaunch();
  8. final Activity a = performLaunchActivity(r, customIntent);
  9. if (a != null) {
  10. r.createdConfig = new Configuration(mConfiguration);
  11. reportSizeConfigurations(r);
  12. if (!r.activity.mFinished && pendingActions != null) {
  13. pendingActions.setOldState(r.state);
  14. pendingActions.setRestoreInstanceState(true);
  15. pendingActions.setCallOnPostCreate(true);
  16. }
  17. } else {
  18. // 启动 Activity 发生异常,不论是什么原因,通知 ATMS 终止此 Activity
  19. try {
  20. ActivityTaskManager.getService()
  21. .finishActivity(r.token, Activity.RESULT_CANCELED, null,
  22. Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
  23. } catch (RemoteException ex) {
  24. throw ex.rethrowFromSystemServer();
  25. }
  26. }
  27. return a;
  28. }
  29. /** Core implementation of activity launch. */
  30. private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
  31. ActivityInfo aInfo = r.activityInfo;
  32. if (r.packageInfo == null) {
  33. r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
  34. Context.CONTEXT_INCLUDE_CODE);
  35. }
  36. ......
  37. // 创建 Activity 的 Context
  38. ContextImpl appContext = createBaseContextForActivity(r);
  39. Activity activity = null;
  40. try {
  41. // 通过 ClassLoader 反射获取 Activity 的实例
  42. java.lang.ClassLoader cl = appContext.getClassLoader();
  43. activity = mInstrumentation.newActivity(
  44. cl, component.getClassName(), r.intent);
  45. StrictMode.incrementExpectedActivityCount(activity.getClass());
  46. r.intent.setExtrasClassLoader(cl);
  47. r.intent.prepareToEnterProcess();
  48. if (r.state != null) {
  49. r.state.setClassLoader(cl);
  50. }
  51. } catch (Exception e) {
  52. ......
  53. }
  54. try {
  55. // 创建 Application
  56. Application app = r.packageInfo.makeApplication(false, mInstrumentation);
  57. ......
  58. if (activity != null) {
  59. ......
  60. appContext.getResources().addLoaders(
  61. app.getResources().getLoaders().toArray(new ResourcesLoader[0]));
  62. appContext.setOuterContext(activity);
  63. // 执行 Activity 的 attach、初始化 Window 等
  64. activity.attach(appContext, this, getInstrumentation(), r.token,
  65. r.ident, app, r.intent, r.activityInfo, title, r.parent,
  66. r.embeddedID, r.lastNonConfigurationInstances, config,
  67. r.referrer, r.voiceInteractor, window, r.configCallback,
  68. r.assistToken);
  69. ......
  70. activity.mCalled = false;
  71. // 执行 Activity 的 onCreate
  72. if (r.isPersistable()) {
  73. mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
  74. } else {
  75. mInstrumentation.callActivityOnCreate(activity, r.state);
  76. }
  77. ......
  78. r.activity = activity;
  79. mLastReportedWindowingMode.put(activity.getActivityToken(),
  80. config.windowConfiguration.getWindowingMode());
  81. }
  82. // 设置生命周期的状态为 ON_CREATE
  83. r.setState(ON_CREATE);
  84. synchronized (mResourcesManager) {
  85. mActivities.put(r.token, r);
  86. }
  87. }
  88. ......
  89. return activity;
  90. }

performLaunchActivity() 方法执行流程:

    调用 createBaseContextForActivity() 方法创建 ContextImpl 对象,该方法中调用 ContextImpl # createActivityContext() 方法创建 ContextImpl 对象。
    调用 Instrumentation # newActivity() 方法加载并新建 Activity,该方法中调用 AppComponentFactory # instantiateActivity() 方法,后通过在 performLaunchActivity() 方法中新建的 ClassLoader 加载新建 Activity 类。
    通过 LoadApk # makeApplication() 方法创建一个 Application 对象,过程跟加载新建 Activity 类似,用到 ClassLoader。
    执行 Activity # attach() 方法,ContextImpl 通过该方法来和 Activity 建立关联,除此之外,方法中还完成了 Window 实例的创建并建立自己和 Window 的关联,这样当 Window 接收到外部输入事件后就可以将事件传递给 Activity。
    执行 Instrumentation # callActivityOnCreate() 方法,该方法中调用 Activity # performCreate() 方法,Activity # performCreate() 方法中调用 Activity # onCreate() 方法。

流程走到这里 Activity # onCreate() 方法执行完,并设置生命周期的状态为 ON_CREATE,还有 onStart、onResume 等生命周期方法呢?
 

2.5.16 ActivityThread 执行生命周期事务

回看 13. TransactionExecutor 事务转换执行器,之前我们只分析了 TransactionExecutor # executeCallbacks(transaction) 执行回调有关的流程,现在我们来看一下 TransactionExecutor # executeLifecycleState(transaction) 方法。
 

  1. /** Transition to the final state if requested by the transaction. */
  2. private void executeLifecycleState(ClientTransaction transaction) {
  3. // 获取之前设置的生命周期状态请求
  4. final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
  5. if (lifecycleItem == null) {
  6. // No lifecycle request, return early.
  7. return;
  8. }
  9. final IBinder token = transaction.getActivityToken();
  10. // 获取 ActivityClientRecord,该对象保存 Activity 的启动信息
  11. final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
  12. ......
  13. if (r == null) {
  14. // Ignore requests for non-existent client records for now.
  15. return;
  16. }
  17. // Cycle to the state right before the final requested state.
  18. // 执行当前已设置的生命周期请求最终状态之前的状态
  19. cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction);
  20. // Execute the final transition with proper parameters.
  21. // 执行设置的生命周期事务的最终转换
  22. lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
  23. lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
  24. }

TransactionExecutor # executeLifecycleState(transaction) 方法主要是用来转换 Activity 的生命周期状态至设置的最终状态并执行,流程如下:

    获取 8. 获取 ClientTransaction、添加 Callback、设置 LifecycleStateRequest 中设置的执行 transaction 后的最终的生命周期状态请求,也就是设置的 ResumeActivityItem。
    获取保存 Activity 启动信息的 ActivityRecord 对象,调用 cycleToPath() 方法获取并执行设置的生命周期请求最终状态之前的状态。
    调用 ActivityLifecycleItem # execute() 方法执行设置的生命周期事务的最终转换,这里实际调用的是 ResumeActivityItem # execute() 方法。
 

2.5.17 TransactionExecutor 执行中间态生命周期请求事务

何为中间态生命周期请求事务? Android 系统针对 Activity 的生命周期,定义了与之相对应的 XXXActivityItem 类,如 StartActivityItem、PauseActivityItem 等,即为处于中间态的生命周期请求事务。

那这些中间态的生命周期请求事务什么时候会被执行呢?如 StartActivityItem 对应的 Activity 的生命周期请求 onStart 是在何时触发的呢?
 

  1. private void cycleToPath(ActivityClientRecord r, int finish, boolean excludeLastState,
  2. ClientTransaction transaction) {
  3. final int start = r.getLifecycleState();
  4. ......
  5. final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
  6. performLifecycleSequence(r, path, transaction);
  7. }
  8. /** Transition the client through previously initialized state sequence. */
  9. private void performLifecycleSequence(ActivityClientRecord r, IntArray path,
  10. ClientTransaction transaction) {
  11. final int size = path.size();
  12. for (int i = 0, state; i < size; i++) {
  13. state = path.get(i);
  14. .......
  15. switch (state) {
  16. case ON_CREATE:
  17. mTransactionHandler.handleLaunchActivity(r, mPendingActions,
  18. null /* customIntent */);
  19. break;
  20. case ON_START:
  21. mTransactionHandler.handleStartActivity(r.token, mPendingActions);
  22. break;
  23. ......
  24. }
  25. }
  26. }

方法的执行流程如下:

    获取待启动 Activity 当前的生命周期状态,由于 Activity # onCreate() 方法执行完,并设置生命周期的状态为 ON_CREATE,所以 start 为 ON_CREATE。在上一节中我们知道设置的最终的生命周期状态请求是 ResumeActivityItem,其 getTargetState() 方法返回的是 ON_RESUME。
    通过 TransactionExecutorHelper 对象调用其 getLifecyclePath() 方法,获取此次要执行生命周期的路径,方法中根据 start 和 finish 状态来构造一个 IntArray 类型的状态数组。
    调用 TransactionExecutor # performLifecycleSequence() 方法中,遍历构建的状态序列执行应用进程中对应的 ActivityThread # handleXXXActivity() 方法完成生命周期状态的转换。

看到这里,还是未明确找到 Activity 生命周期的 onStart 在何时、何地执行的?但是 TransactionExecutorHelper 这个辅助类值得关注,通过 TransactionExecutorHelper # getLifecyclePath() 方法来获取此次要执行生命周期的路径,看看这个方法怎么做的?
 

2.5.18 TransactionExecutorHelper 获取待执行生命周期的状态序列

先看一下 ON_START、ON_RESUME 等这些生命周期状态的定义,方便我们理解后续流程。

  1. /**
  2. * 请求 Activity 应该达到的生命周期状态
  3. */
  4. public abstract class ActivityLifecycleItem extends ClientTransactionItem {
  5. ......
  6. @Retention(RetentionPolicy.SOURCE)
  7. public @interface LifecycleState{}
  8. public static final int UNDEFINED = -1;
  9. public static final int PRE_ON_CREATE = 0;
  10. public static final int ON_CREATE = 1;
  11. public static final int ON_START = 2;
  12. public static final int ON_RESUME = 3;
  13. public static final int ON_PAUSE = 4;
  14. public static final int ON_STOP = 5;
  15. public static final int ON_DESTROY = 6;
  16. public static final int ON_RESTART = 7;
  17. /** A final lifecycle state that an activity should reach. */
  18. @LifecycleState
  19. public abstract int getTargetState();
  20. }

        与 Activity 生命周期有关的 StartActivityItem、ResumeActivityItem 等继承自该抽象类并实现其抽象方法 getTargetState(),方法中返回对应的生命周期,注意:LaunchActivityItem 直接继承自 ClientTransactionItem。

结合上面这个抽象类来分析 TransactionExecutorHelper # getLifecyclePath() 方法,代码如下:
 

  1. @VisibleForTesting
  2. public IntArray getLifecyclePath(int start, int finish, boolean excludeLastState) {
  3. ......
  4. // 清空生命周期状态序列
  5. mLifecycleSequence.clear();
  6. if (finish >= start) {
  7. if (start == ON_START && finish == ON_STOP) {
  8. // 如果很快从 ON_START 转换到 ON_STOP 状态,此时不需要经历恢复、暂停状态
  9. mLifecycleSequence.add(ON_STOP);
  10. } else {
  11. // 添加 start 到 finish 之间的生命周期状态
  12. for (int i = start + 1; i <= finish; i++) {
  13. mLifecycleSequence.add(i);
  14. }
  15. }
  16. }
  17. ......
  18. // 根据条件判断移除最后的生命周期状态
  19. if (excludeLastState && mLifecycleSequence.size() != 0) {
  20. mLifecycleSequence.remove(mLifecycleSequence.size() - 1);
  21. }
  22. return mLifecycleSequence;
  23. }

        经过之前的分析,可知 TransactionExecutorHelper # getLifecyclePath() 方法中传入的 start 为 ON_CREATE,finish 为 ON_RESUME,excludeLastState 为 true。由 ActivityLifecycleItem 抽象类定义可知 finish >= start,因此方法中可以只关注这部分的逻辑处理,通过比较可以发现 ON_CREATE 和 ON_RESUME 中间还有 ON_START 这个中间状态,所以在 mLifecycleSequence 状态序列中将添加 ON_START 和 ON_RESUME 状态,此时因为 excludeLastState 为 true,所以最后会移除掉 ON_RESUME 状态,故返回的状态序列中只包含 ON_START 状态,即 cycleToPath() 方法中获得的 path 中只包含 ON_START 状态。

所以此时,回到 17. TransactionExecutor 执行中间态生命周期请求事务 分析 performLifecycleSequence() 方法,此时遍历构建的状态序列中只有 ON_START 状态值,因此执行应用进程中对应的 ActivityThread # handleStartActivity() 方法完成生命周期状态的转换,方法调用流程如下:

    ActivityThread # handleStartActivity() 方法中调用 activity # performStart() 方法,设置生命周期的状态为 ON_START。
    Activity # performStart() 方法中调用 Instrumentation # callActivityOnStart() 方法,Instrumentation # callActivityOnStart() 方法中调用 Activity # onStart() 方法。

流程走到这里 Activity # onStart() 方法执行完,并设置生命周期的状态为 ON_START,继续分析 onResume 生命周期方法的调用过程?
 

2.5.19 TransactionExecutor 执行生命周期事务的最终转换

        回看 ActivityThread 执行生命周期事务 中,最后会执行已设置的生命周期事务的最终转换,通过前面的分析,这里执行的是 ResumeActivityItem # execute() 方法,代码如下:

  1. @Override
  2. public void execute(ClientTransactionHandler client, IBinder token,
  3. PendingTransactionActions pendingActions) {
  4. Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityResume");
  5. client.handleResumeActivity(token, true /* finalStateRequest */, mIsForward,
  6. "RESUME_ACTIVITY");
  7. Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
  8. }

        上面分析过 ClientTransactionHandler 是一个抽象类,ActivityThread 继承自 ClientTransactionHandler 并实现了其抽象方法,所以这里调用的是 ActivityThread # handleResumeActivity() 方法,不在贴源码,方法调用流程如下:

        ActivityThread # handleResumeActivity() 方法调用 ActivityThread # performResumeActivity() 方法,设置生命周期的状态为 ON_RESUME。
        ActivityThread # performResumeActivity() 方法调用 Activity # performResume() 方法。Activity # performResume() 方法中调用 Instrumentation # callActivityOnResume() 方法,Instrumentation # callActivityOnResume() 方法中调用 Activity # onResume() 方法。

       断点后,可查看调用关系如下,

 

三,总结

        至此,基于 Android R(11.0)我们终于解析完 Activity 的启动过程,本篇主要是分析从桌面点击应用ICON启动Activity 的启动流程,去掉本篇中关于启动进程 Launcher、孵化进程 Zygote 等有关的篇幅,也即普通 Activity 的启动过程,这里不再单独分析。

此外,有关 ClientTransaction 部分值得深入学习,这是 Android P(9.0)加入的,其作用如下:

    减少通信次数:系统进程中 AMS 到应用进程,一次通信,包含各种通信事件和内容。
    统筹消息域:将生命周期变化与事件更新分类统筹,分别处理。
    减少两端耦合:系统进程中 AMS 对于生命周期的发送要求,与应用进程对生命周期的处理需求并不对等,所以应用进程会自己组装完整的生命周期回调,处理逻辑更内聚。
————————————————
参考:CSDN博主「neuHenry」的原创文章,遵循CC 4.0 BY-SA版权协议
原文链接:https://blog.csdn.net/u010347226/article/details/124890884

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

闽ICP备14008679号