经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 移动开发 » Android » 查看文章
“无处不在” 的系统核心服务 —— ActivityManagerService 启动流程解析
来源:cnblogs  作者:秉心说  时间:2019/10/28 10:09:26  对本文有异议

本文基于 Android 9.0 , 代码仓库地址 : android_9.0.0_r45

系列文章目录:

Java 世界的盘古和女娲 —— Zygote

Zygote 家的大儿子 —— SystemServer

Android 世界中,谁喊醒了 Zygote ?

文中相关源码链接:

SystemServer.java

ActivityManagerService.java

之前介绍 SystemServer 启动流程 的时候说到,SystemServer 进程启动了一系列的系统服务,ActivityManagerService 是其中最核心的服务之一。它和四大组件的启动、切换、调度及应用进程的管理和调度息息相关,其重要性不言而喻。本文主要介绍其启动流程,它是在 SystemServermain() 中启动的,整个启动流程经历了 startBootstrapServicesstartCoreService()startOtherService()。下面就顺着源码来捋一捋 ActivityManagerService 的启动流程,下文中简称 AMS

  1. private void startBootstrapServices() {
  2. ...
  3. // 1. AMS 初始化
  4. mActivityManagerService = mSystemServiceManager.startService(
  5. ActivityManagerService.Lifecycle.class).getService();
  6. // 设置 AMS 的系统服务管理器
  7. mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
  8. // 设置 AMS 的应用安装器
  9. mActivityManagerService.setInstaller(installer);
  10. ...
  11. mActivityManagerService.initPowerManagement();
  12. ...
  13. // 2. AMS.setSystemProcess()
  14. mActivityManagerService.setSystemProcess();
  15. ...
  16. }
  17. private void startCoreServices{
  18. ...
  19. mActivityManagerService.setUsageStatsManager(
  20. LocalServices.getService(UsageStatsManagerInternal.class));
  21. ...
  22. }
  23. private void startherService{
  24. ...
  25. // 3. 安装系统 Provider
  26. mActivityManagerService.installSystemProviders();
  27. ...
  28. final Watchdog watchdog = Watchdog.getInstance();
  29. watchdog.init(context, mActivityManagerService);
  30. ...
  31. mActivityManagerService.setWindowManager(wm);
  32. ...
  33. networkPolicy = new NetworkPolicyManagerService(context, mActivityManagerService,
  34. networkManagement);
  35. ...
  36. if (safeMode) {
  37. traceBeginAndSlog("EnterSafeModeAndDisableJitCompilation");
  38. mActivityManagerService.enterSafeMode();
  39. // Disable the JIT for the system_server process
  40. VMRuntime.getRuntime().disableJitCompilation();
  41. traceEnd();
  42. }
  43. ...
  44. mPowerManagerService.systemReady(mActivityManagerService.getAppOpsService());
  45. ...
  46. // 4. AMS.systemReady()
  47. mActivityManagerService.systemReady(() -> {
  48. ...
  49. mActivityManagerService.startObservingNativeCrashes();
  50. }
  51. }

AMS 初始化

  1. mActivityManagerService = mSystemServiceManager.startService(
  2. ActivityManagerService.Lifecycle.class).getService();

AMS 通过 SystemServiceManager.startService() 方法初始化,startService() 在之前的文章中已经分析过,其作用是根据参数传入的类通过反射进行实例化,并回调其 onStart() 方法。注意这里传入的是 ActivityManagerService.Lifecycle.classLifeCycle 是 AMS 的一个静态内部类。

  1. public static final class Lifecycle extends SystemService {
  2. private final ActivityManagerService mService;
  3. // 构造函数中新建 ActivityManagerService 对象
  4. public Lifecycle(Context context) {
  5. super(context);
  6. mService = new ActivityManagerService(context);
  7. }
  8. @Override
  9. public void onStart() {
  10. mService.start();
  11. }
  12. @Override
  13. public void onBootPhase(int phase) {
  14. mService.mBootPhase = phase;
  15. if (phase == PHASE_SYSTEM_SERVICES_READY) {
  16. mService.mBatteryStatsService.systemServicesReady();
  17. mService.mServices.systemServicesReady();
  18. }
  19. }
  20. @Override
  21. public void onCleanupUser(int userId) {
  22. mService.mBatteryStatsService.onCleanupUser(userId);
  23. }
  24. public ActivityManagerService getService() {
  25. return mService;
  26. }
  27. }

Lifecycle 的构造函数中初始化了 AMS。再来看看 AMS 的构造函数。

  1. public ActivityManagerService(Context systemContext) {
  2. mInjector = new Injector();
  3. // AMS 上下文
  4. mContext = systemContext;
  5. mFactoryTest = FactoryTest.getMode();
  6. // ActivityThread 对象
  7. mSystemThread = ActivityThread.currentActivityThread();
  8. // ContextImpl 对象
  9. mUiContext = mSystemThread.getSystemUiContext();
  10. mPermissionReviewRequired = mContext.getResources().getBoolean(
  11. com.android.internal.R.bool.config_permissionReviewRequired);
  12. // 线程名为 ActivityManager 的前台线程,ServiceThread 继承于 HandlerThread
  13. mHandlerThread = new ServiceThread(TAG,
  14. THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
  15. mHandlerThread.start();
  16. // 获取 mHandlerThread 的 Handler 对象
  17. mHandler = new MainHandler(mHandlerThread.getLooper());
  18. // 创建名为 android.ui 的线程
  19. mUiHandler = mInjector.getUiHandler(this);
  20. // 不知道什么作用
  21. mProcStartHandlerThread = new ServiceThread(TAG + ":procStart",
  22. THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
  23. mProcStartHandlerThread.start();
  24. mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());
  25. mConstants = new ActivityManagerConstants(this, mHandler);
  26. /* static; one-time init here */
  27. // 根据优先级 kill 后台应用进程
  28. if (sKillHandler == null) {
  29. sKillThread = new ServiceThread(TAG + ":kill",
  30. THREAD_PRIORITY_BACKGROUND, true /* allowIo */);
  31. sKillThread.start();
  32. sKillHandler = new KillHandler(sKillThread.getLooper());
  33. }
  34. // 前台广播队列,超时时间为 10 秒
  35. mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
  36. "foreground", BROADCAST_FG_TIMEOUT, false);
  37. // 后台广播队列,超时时间为 60 秒
  38. mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
  39. "background", BROADCAST_BG_TIMEOUT, true);
  40. mBroadcastQueues[0] = mFgBroadcastQueue;
  41. mBroadcastQueues[1] = mBgBroadcastQueue;
  42. // 创建 ActiveServices
  43. mServices = new ActiveServices(this);
  44. mProviderMap = new ProviderMap(this);
  45. // 创建 AppErrors,用于处理应用中的错误
  46. mAppErrors = new AppErrors(mUiContext, this);
  47. // 创建 /data/system 目录
  48. File dataDir = Environment.getDataDirectory();
  49. File systemDir = new File(dataDir, "system");
  50. systemDir.mkdirs();
  51. mAppWarnings = new AppWarnings(this, mUiContext, mHandler, mUiHandler, systemDir);
  52. // TODO: Move creation of battery stats service outside of activity manager service.
  53. // 创建 BatteryStatsService,其信息保存在 /data/system/procstats 中
  54. // 这里有个 TODO,打算把 BatteryStatsService 的创建移除 AMS
  55. mBatteryStatsService = new BatteryStatsService(systemContext, systemDir, mHandler);
  56. mBatteryStatsService.getActiveStatistics().readLocked();
  57. mBatteryStatsService.scheduleWriteToDisk();
  58. mOnBattery = DEBUG_POWER ? true
  59. : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
  60. mBatteryStatsService.getActiveStatistics().setCallback(this);
  61. // 创建 ProcessStatsService,并将其信息保存在 /data/system/procstats 中
  62. mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
  63. mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);
  64. // 定义 ContentProvider 访问指定 Uri 数据的权限
  65. mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml"), "uri-grants");
  66. // 多用户管理
  67. mUserController = new UserController(this);
  68. mVrController = new VrController(this);
  69. // 获取 OpenGL 版本
  70. GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
  71. ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
  72. if (SystemProperties.getInt("sys.use_fifo_ui", 0) != 0) {
  73. mUseFifoUiScheduling = true;
  74. }
  75. mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
  76. mTempConfig.setToDefaults();
  77. mTempConfig.setLocales(LocaleList.getDefault());
  78. mConfigurationSeq = mTempConfig.seq = 1;
  79. // 创建 ActivityStackSupervisor ,用于管理 Activity 任务栈
  80. mStackSupervisor = createStackSupervisor();
  81. mStackSupervisor.onConfigurationChanged(mTempConfig);
  82. mKeyguardController = mStackSupervisor.getKeyguardController();
  83. mCompatModePackages = new CompatModePackages(this, systemDir, mHandler);
  84. mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
  85. mTaskChangeNotificationController =
  86. new TaskChangeNotificationController(this, mStackSupervisor, mHandler);
  87. // 创建 ActivityStartController 对象,用于管理 Activity 的启动
  88. mActivityStartController = new ActivityStartController(this);
  89. // 创建最近任务栈 RecentTask 对象
  90. mRecentTasks = createRecentTasks();
  91. mStackSupervisor.setRecentTasks(mRecentTasks);
  92. mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mHandler);
  93. mLifecycleManager = new ClientLifecycleManager();
  94. // 创建 CpuTracker 线程,追踪 CPU 状态
  95. mProcessCpuThread = new Thread("CpuTracker") {
  96. @Override
  97. public void run() {
  98. synchronized (mProcessCpuTracker) {
  99. mProcessCpuInitLatch.countDown();
  100. mProcessCpuTracker.init(); // 初始化 ProcessCpuTracker。注意同步问题
  101. }
  102. while (true) {
  103. try {
  104. try {
  105. synchronized(this) {
  106. final long now = SystemClock.uptimeMillis();
  107. long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
  108. long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
  109. //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
  110. // + ", write delay=" + nextWriteDelay);
  111. if (nextWriteDelay < nextCpuDelay) {
  112. nextCpuDelay = nextWriteDelay;
  113. }
  114. if (nextCpuDelay > 0) {
  115. mProcessCpuMutexFree.set(true);
  116. this.wait(nextCpuDelay);
  117. }
  118. }
  119. } catch (InterruptedException e) {
  120. }
  121. // 更新 Cpu 统计信息
  122. updateCpuStatsNow();
  123. } catch (Exception e) {
  124. Slog.e(TAG, "Unexpected exception collecting process stats", e);
  125. }
  126. }
  127. }
  128. };
  129. // hidden api 设置
  130. mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);
  131. // 设置 Watchdog 监控
  132. Watchdog.getInstance().addMonitor(this);
  133. Watchdog.getInstance().addThread(mHandler);
  134. // bind background thread to little cores
  135. // this is expected to fail inside of framework tests because apps can't touch cpusets directly
  136. // make sure we've already adjusted system_server's internal view of itself first
  137. // 更新进程的 oom_adj 值
  138. updateOomAdjLocked();
  139. try {
  140. Process.setThreadGroupAndCpuset(BackgroundThread.get().getThreadId(),
  141. Process.THREAD_GROUP_BG_NONINTERACTIVE);
  142. } catch (Exception e) {
  143. Slog.w(TAG, "Setting background thread cpuset failed");
  144. }
  145. }

AMS 的构造函数中做了很多事情,代码中作了很多注释,这里就不再展开细说了。

LifeCycle 的构造函数中初始化了 AMS,然后会调用 LifeCycle.onStart(),最终调用的是 AMS.start() 方法。

  1. private void start() {
  2. // 移除所有进程组
  3. removeAllProcessGroups();
  4. // 启动构造函数中创建的 CpuTracker 线程,监控 cpu 使用情况
  5. mProcessCpuThread.start();
  6. // 启动 BatteryStatsService,统计电池信息
  7. mBatteryStatsService.publish();
  8. mAppOpsService.publish(mContext);
  9. // 启动 LocalService ,将 ActivityManagerInternal 加入服务列表
  10. LocalServices.addService(ActivityManagerInternal.class, new LocalService());
  11. // 等待 mProcessCpuThread 线程中的同步代码块执行完毕。
  12. // 在执行 mProcessCpuTracker.init() 方法时访问 mProcessCpuTracker 将阻塞
  13. try {
  14. mProcessCpuInitLatch.await();
  15. } catch (InterruptedException e) {
  16. Thread.currentThread().interrupt();
  17. throw new IllegalStateException("Interrupted wait during start");
  18. }
  19. }

AMS 的初始化工作到这里就基本结束了,我们再回到 startBootstrapServices() 中,看看 AMS 的下一步动作 setSystemProcess()

AMS.setSystemProcess()

  1. public void setSystemProcess() {
  2. try {
  3. // 注册各种服务
  4. // 注册 AMS
  5. ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
  6. DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
  7. // 注册进程统计服务
  8. ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
  9. // 注册内存信息服务
  10. ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
  11. DUMP_FLAG_PRIORITY_HIGH);
  12. // 注册 GraphicsBinder
  13. ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
  14. // 注册 DbBinder
  15. ServiceManager.addService("dbinfo", new DbBinder(this));
  16. if (MONITOR_CPU_USAGE) {
  17. // 注册 DbBinder
  18. ServiceManager.addService("cpuinfo", new CpuBinder(this),
  19. /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
  20. }
  21. // 注册权限管理者 PermissionController
  22. ServiceManager.addService("permission", new PermissionController(this
  23. // 注册进程信息服务 ProcessInfoService
  24. ServiceManager.addService("processinfo", new ProcessInfoService(this));
  25. // 获取包名为 android 的应用信息,framework-res.apk
  26. ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
  27. "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
  28. mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
  29. synchronized (this) {
  30. // 创建 ProcessRecord
  31. ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0);
  32. app.persistent = true;
  33. app.pid = MY_PID;
  34. app.maxAdj = ProcessList.SYSTEM_ADJ;
  35. app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
  36. synchronized (mPidsSelfLocked) {
  37. mPidsSelfLocked.put(app.pid, app);
  38. }
  39. // 更新 mLruProcesses
  40. updateLruProcessLocked(app, false, null);
  41. // 更新进程对应的 oom_adj 值
  42. updateOomAdjLocked();
  43. }
  44. } catch (PackageManager.NameNotFoundException e) {
  45. throw new RuntimeException(
  46. "Unable to find android system package", e);
  47. }
  48. // Start watching app ops after we and the package manager are up and running.
  49. // 当 packager manager 启动并运行时开始监听 app ops
  50. mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null,
  51. new IAppOpsCallback.Stub() {
  52. @Override public void opChanged(int op, int uid, String packageName) {
  53. if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) {
  54. if (mAppOpsService.checkOperation(op, uid, packageName)
  55. != AppOpsManager.MODE_ALLOWED) {
  56. runInBackgroundDisabled(uid);
  57. }
  58. }
  59. }
  60. });
  61. }

setSystemProcess() 的主要工作就是向 ServiceManager 注册关联的系统服务。

AMS.installSystemProviders()

  1. public final void installSystemProviders() {
  2. List<ProviderInfo> providers;
  3. synchronized (this) {
  4. ProcessRecord app = mProcessNames.get("system", SYSTEM_UID);
  5. providers = generateApplicationProvidersLocked(app);
  6. if (providers != null) {
  7. for (int i=providers.size()-1; i>=0; i--) {
  8. ProviderInfo pi = (ProviderInfo)providers.get(i);
  9. if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
  10. Slog.w(TAG, "Not installing system proc provider " + pi.name
  11. + ": not system .apk");
  12. // 移除非系统 Provier
  13. providers.remove(i);
  14. }
  15. }
  16. }
  17. }
  18. // 安装系统 Provider
  19. if (providers != null) {
  20. mSystemThread.installSystemProviders(providers);
  21. }
  22. synchronized (this) {
  23. mSystemProvidersInstalled = true;
  24. }
  25. mConstants.start(mContext.getContentResolver());
  26. // 创建 CoreSettingsObserver ,监控核心设置的变化
  27. mCoreSettingsObserver = new CoreSettingsObserver(this);
  28. // 创建 FontScaleSettingObserver,监控字体的变化
  29. mFontScaleSettingObserver = new FontScaleSettingObserver();
  30. // 创建 DevelopmentSettingsObserver
  31. mDevelopmentSettingsObserver = new DevelopmentSettingsObserver();
  32. GlobalSettingsToPropertiesMapper.start(mContext.getContentResolver());
  33. // Now that the settings provider is published we can consider sending
  34. // in a rescue party.
  35. RescueParty.onSettingsProviderPublished(mContext);
  36. //mUsageStatsService.monitorPackages();
  37. }

installSystemProviders() 的主要工作是安装系统 Proviers。

AMS.systemReady()

AMS.systemReady() 是 AMS 启动流程的最后一步了。

  1. public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
  2. ...
  3. synchronized(this) {
  4. if (mSystemReady) { // 首次调用 mSystemReady 为 false
  5. // If we're done calling all the receivers, run the next "boot phase" passed in
  6. // by the SystemServer
  7. if (goingCallback != null) {
  8. goingCallback.run();
  9. }
  10. return;
  11. }
  12. // 一系列 systemReady()
  13. mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
  14. PackageManager.FEATURE_CANT_SAVE_STATE);
  15. mLocalDeviceIdleController
  16. = LocalServices.getService(DeviceIdleController.LocalService.class);
  17. mAssistUtils = new AssistUtils(mContext);
  18. mVrController.onSystemReady();
  19. // Make sure we have the current profile info, since it is needed for security checks.
  20. mUserController.onSystemReady();
  21. mRecentTasks.onSystemReadyLocked();
  22. mAppOpsService.systemReady();
  23. mSystemReady = true;
  24. }
  25. ...
  26. ArrayList<ProcessRecord> procsToKill = null;
  27. synchronized(mPidsSelfLocked) {
  28. for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
  29. ProcessRecord proc = mPidsSelfLocked.valueAt(i);
  30. if (!isAllowedWhileBooting(proc.info)){
  31. if (procsToKill == null) {
  32. procsToKill = new ArrayList<ProcessRecord>();
  33. }
  34. procsToKill.add(proc);
  35. }
  36. }
  37. }
  38. synchronized(this) {
  39. if (procsToKill != null) {
  40. for (int i=procsToKill.size()-1; i>=0; i--) {
  41. ProcessRecord proc = procsToKill.get(i);
  42. removeProcessLocked(proc, true, false, "system update done");
  43. }
  44. }
  45. // Now that we have cleaned up any update processes, we
  46. // are ready to start launching real processes and know that
  47. // we won't trample on them any more.
  48. mProcessesReady = true;
  49. }
  50. ...
  51. if (goingCallback != null) goingCallback.run();
  52. mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
  53. Integer.toString(currentUserId), currentUserId);
  54. mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
  55. Integer.toString(currentUserId), currentUserId);
  56. // 回调所有 SystemService 的 onStartUser() 方法
  57. mSystemServiceManager.startUser(currentUserId);
  58. synchronized (this) {
  59. // Only start up encryption-aware persistent apps; once user is
  60. // unlocked we'll come back around and start unaware apps
  61. startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);
  62. // Start up initial activity.
  63. mBooting = true;
  64. // Enable home activity for system user, so that the system can always boot. We don't
  65. // do this when the system user is not setup since the setup wizard should be the one
  66. // to handle home activity in this case.
  67. if (UserManager.isSplitSystemUser() &&
  68. Settings.Secure.getInt(mContext.getContentResolver(),
  69. Settings.Secure.USER_SETUP_COMPLETE, 0) != 0) {
  70. ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class);
  71. try {
  72. AppGlobals.getPackageManager().setComponentEnabledSetting(cName,
  73. PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0,
  74. UserHandle.USER_SYSTEM);
  75. } catch (RemoteException e) {
  76. throw e.rethrowAsRuntimeException();
  77. }
  78. }
  79. // 启动桌面 Home 应用
  80. startHomeActivityLocked(currentUserId, "systemReady");
  81. ...
  82. long ident = Binder.clearCallingIdentity();
  83. try {
  84. // 发送广播 USER_STARTED
  85. Intent intent = new Intent(Intent.ACTION_USER_STARTED);
  86. intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
  87. | Intent.FLAG_RECEIVER_FOREGROUND);
  88. intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
  89. broadcastIntentLocked(null, null, intent,
  90. null, null, 0, null, null, null, OP_NONE,
  91. null, false, false, MY_PID, SYSTEM_UID,
  92. currentUserId);
  93. // 发送广播 USER_STARTING
  94. intent = new Intent(Intent.ACTION_USER_STARTING);
  95. intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
  96. intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
  97. broadcastIntentLocked(null, null, intent,
  98. null, new IIntentReceiver.Stub() {
  99. @Override
  100. public void performReceive(Intent intent, int resultCode, String data,
  101. Bundle extras, boolean ordered, boolean sticky, int sendingUser)
  102. throws RemoteException {
  103. }
  104. }, 0, null, null,
  105. new String[] {INTERACT_ACROSS_USERS}, OP_NONE,
  106. null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
  107. } catch (Throwable t) {
  108. Slog.wtf(TAG, "Failed sending first user broadcasts", t);
  109. } finally {
  110. Binder.restoreCallingIdentity(ident);
  111. }
  112. mStackSupervisor.resumeFocusedStackTopActivityLocked();
  113. mUserController.sendUserSwitchBroadcasts(-1, currentUserId);
  114. BinderInternal.nSetBinderProxyCountWatermarks(6000,5500);
  115. BinderInternal.nSetBinderProxyCountEnabled(true);
  116. BinderInternal.setBinderProxyCountCallback(
  117. new BinderInternal.BinderProxyLimitListener() {
  118. @Override
  119. public void onLimitReached(int uid) {
  120. if (uid == Process.SYSTEM_UID) {
  121. Slog.i(TAG, "Skipping kill (uid is SYSTEM)");
  122. } else {
  123. killUid(UserHandle.getAppId(uid), UserHandle.getUserId(uid),
  124. "Too many Binders sent to SYSTEM");
  125. }
  126. }
  127. }, mHandler);
  128. }
  129. }

systemReady() 方法源码很长,上面做了很多删减。注意其中的 startHomeActivityLocked() 方法会启动桌面 Activity 。

  1. boolean startHomeActivityLocked(int userId, String reason) {
  2. ...
  3. Intent intent = getHomeIntent();
  4. ActivityInfo aInfo = resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
  5. if (aInfo != null) {
  6. intent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name));
  7. // Don't do this if the home app is currently being
  8. // instrumented.
  9. aInfo = new ActivityInfo(aInfo);
  10. aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
  11. ProcessRecord app = getProcessRecordLocked(aInfo.processName,
  12. aInfo.applicationInfo.uid, true);
  13. if (app == null || app.instr == null) {
  14. intent.setFlags(intent.getFlags() | FLAG_ACTIVITY_NEW_TASK);
  15. final int resolvedUserId = UserHandle.getUserId(aInfo.applicationInfo.uid);
  16. // For ANR debugging to verify if the user activity is the one that actually
  17. // launched.
  18. final String myReason = reason + ":" + userId + ":" + resolvedUserId;
  19. // 启动桌面 Activity
  20. mActivityStartController.startHomeActivity(intent, aInfo, myReason);
  21. }
  22. } else {
  23. Slog.wtf(TAG, "No home screen found for " + intent, new Throwable());
  24. }
  25. return true;
  26. }

ActivityStartController 负责启动 Activity,至此,桌面应用就启动了。

最后

整篇写下来感觉就像小学生流水日记一样,但是读源码,就像有钱人的生活一样,往往是那么朴实无华,且枯燥。我不经意间看了看我的劳力士,太晚了,时序图后面再补上吧!

最后,下集预告,接着这篇,Activity 的启动流程分析,敬请期待!

文章首发微信公众号: 秉心说 , 专注 Java 、 Android 原创知识分享,LeetCode 题解。

更多最新原创文章,扫码关注我吧!

原文链接:http://www.cnblogs.com/bingxinshuo/p/11749847.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号