当前位置:   article > 正文

Android-33源码分析: 系统启动流程

android-33
1、按下电源键进行系统启动:触发引导芯片,加载预定义代码,启动引导程序BootLoader
2、启动BootLoader引导程序:它是一个Android系统启动前运行的一个小程序,用来拉起OS并运行
3、启动linux内核:设置缓存、被保护存储器、计划列表、加载驱动、完成系统设置,设置完后会找到系统文件init.rc启动init进程
init_parse_config_file("/init.rc");
4、启动init进程:初始化并启动属性服务,启动zygote进程
Zygote进程的初始化在App_main.cpp文件中开启
  1. // 使用运行时环境启动Zygote的初始化类.
  2. runtime.start("com.android.internal.os.ZygoteInit", startSystemServer);
5、启动zygote进程孵化器:创建JVM,注册JNI,创建服务端的socket,启动systemServer进程
6、启动systemServer进程:启动binder线程池和systemServerManager,启动各种系统服务,如AMS、WMS等
现在从c或c++代码进入到java代码中, ZygoteInit.java初始化类
  1. public static void main(String[] argv) {
  2. ....
  3. // 孵化器fork出SystemServer类
  4. Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer)
  5. ....
  6. }
  1. static int forkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
  2. int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
  3. ZygoteHooks.preFork();
  4. int pid = nativeForkSystemServer(
  5. uid, gid, gids, runtimeFlags, rlimits,
  6. permittedCapabilities, effectiveCapabilities);
  7. // Set the Java Language thread priority to the default value for new apps.
  8. Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
  9. ZygoteHooks.postForkCommon();
  10. return pid;
  11. }
  1. // com.android.server.SystemServer
  2. // 执行main方法
  3. public static void main(String[] args) {
  4. new SystemServer().run();
  5. }
  6. private void run() {
  7. TimingsTraceAndSlog t = new TimingsTraceAndSlog();
  8. /**
  9. * 该进程中也会维护一个主Looper循环 并开启消息循环Looper.loop()
  10. */
  11. // Start services.
  12. try {
  13. t.traceBegin("StartServices");
  14. // 启动引导服务
  15. startBootstrapServices(t);
  16. // 启动核心服务
  17. startCoreServices(t);
  18. // 启动其他服务-会执行mActivityManagerService.systemReady()
  19. startOtherServices(t);
  20. startApexServices(t);
  21. } catch (Throwable ex) {
  22. Slog.e("System", "******************************************");
  23. Slog.e("System", "************ Failure starting system services", ex);
  24. throw ex;
  25. } finally {
  26. t.traceEnd(); // StartServices
  27. }
  28. // Loop forever.
  29. Looper.loop();
  30. throw new RuntimeException("Main thread loop unexpectedly exited");
  31. }
// 启动引导服务
DeviceIdentifiersPolicyService
UriGrantsManagerService
PowerStatsService
ActivityTaskManagerService   
ActivityManagerService
DataLoaderManagerService
PowerManagerService
ThermalManagerService
HintManagerService
RecoverySystemService
DisplayManagerService
UserManagerService
OverlayManagerService
ResourcesManagerService
....
// 启动核心服务
SystemConfigService
BatteryService
UsageStatsService
WebViewUpdateService
CachedDeviceStateService
BinderCallsStatsService
GpuService
...
// 启动其他服务
BinaryTransparencyService
DropBoxManagerService
VibratorManagerService
WindowManagerService
NetworkManagementService
NetworkWatchlistService
FontManagerService
PinnerService
LogcatManagerService
....
  1. /**
  2. * Ready. Set. Go!
  3. * ActivityTaskManagerInternal是ActivityManagerService的抽象类
  4. * 实现是ActivityTaskManagerService的LocalService,
  5. * 所以mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady")
  6. * 最终调用的是ActivityTaskManagerService的startHomeOnAllDisplays()方法
  7. */
  8. public void systemReady(final Runnable goingCallback, @NonNull TimingsTraceAndSlog t) {
  9. ...省略
  10. if (bootingSystemUser) {
  11. t.traceBegin("startHomeOnAllDisplays");
  12. mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
  13. t.traceEnd();
  14. }
  15. ...省略
  16. }
ActivityTaskManagerService 中方法调用
  1. @Override
  2. public boolean startHomeOnAllDisplays(int userId, String reason) {
  3. synchronized (mGlobalLock) {
  4. return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
  5. }
  6. }
RootWindowContainer 中方法调用

  1. boolean startHomeOnDisplay(int userId, String reason, int displayId, boolean allowInstrumenting,
  2. boolean fromHomeKey) {
  3. // Fallback to top focused display or default display if the displayId is invalid.
  4. if (displayId == INVALID_DISPLAY) {
  5. final Task rootTask = getTopDisplayFocusedRootTask();
  6. displayId = rootTask != null ? rootTask.getDisplayId() : DEFAULT_DISPLAY;
  7. }
  8. final DisplayContent display = getDisplayContent(displayId);
  9. return display.reduceOnAllTaskDisplayAreas((taskDisplayArea, result) ->
  10. result | startHomeOnTaskDisplayArea(userId, reason, taskDisplayArea,
  11. allowInstrumenting, fromHomeKey),
  12. false /* initValue */);
  13. }
  1. boolean startHomeOnTaskDisplayArea(int userId, String reason, TaskDisplayArea taskDisplayArea,
  2. boolean allowInstrumenting, boolean fromHomeKey) {
  3. // Fallback to top focused display area if the provided one is invalid.
  4. if (taskDisplayArea == null) {
  5. final Task rootTask = getTopDisplayFocusedRootTask();
  6. taskDisplayArea = rootTask != null ? rootTask.getDisplayArea()
  7. : getDefaultTaskDisplayArea();
  8. }
  9. Intent homeIntent = null;
  10. ActivityInfo aInfo = null;
  11. if (taskDisplayArea == getDefaultTaskDisplayArea()) {
  12. // 配置意图同时设置CATEGORY_HOME
  13. homeIntent = mService.getHomeIntent();
  14. aInfo = resolveHomeActivity(userId, homeIntent);
  15. } else if (shouldPlaceSecondaryHomeOnDisplayArea(taskDisplayArea)) {
  16. Pair<ActivityInfo, Intent> info = resolveSecondaryHomeActivity(userId, taskDisplayArea);
  17. aInfo = info.first;
  18. homeIntent = info.second;
  19. }
  20. if (aInfo == null || homeIntent == null) {
  21. return false;
  22. }
  23. // 检查能否正常显示
  24. if (!canStartHomeOnDisplayArea(aInfo, taskDisplayArea, allowInstrumenting)) {
  25. return false;
  26. }
  27. // Updates the home component of the intent.
  28. homeIntent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name));
  29. homeIntent.setFlags(homeIntent.getFlags() | FLAG_ACTIVITY_NEW_TASK);
  30. // Updates the extra information of the intent.
  31. if (fromHomeKey) {
  32. homeIntent.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY, true);
  33. if (mWindowManager.getRecentsAnimationController() != null) {
  34. mWindowManager.getRecentsAnimationController().cancelAnimationForHomeStart();
  35. }
  36. }
  37. homeIntent.putExtra(WindowManagerPolicy.EXTRA_START_REASON, reason);
  38. // Update the reason for ANR debugging to verify if the user activity is the one that
  39. // actually launched.
  40. final String myReason = reason + ":" + userId + ":" + UserHandle.getUserId(
  41. aInfo.applicationInfo.uid) + ":" + taskDisplayArea.getDisplayId();
  42. mService.getActivityStartController().startHomeActivity(homeIntent, aInfo, myReason,
  43. taskDisplayArea);
  44. return true;
  45. }
ActivityStartController 中方法调用
  1. void startHomeActivity(Intent intent, ActivityInfo aInfo, String reason,
  2. TaskDisplayArea taskDisplayArea) {
  3. // ...省略
  4. // 执行ActivityStarter中的execute
  5. mLastHomeActivityStartResult = obtainStarter(intent, "startHomeActivity: " + reason)
  6. .setOutActivity(tmpOutRecord)
  7. .setCallingUid(0)
  8. .setActivityInfo(aInfo)
  9. .setActivityOptions(options.toBundle())
  10. .execute();
  11. mLastHomeActivityStartRecord = tmpOutRecord[0];
  12. if (rootHomeTask.mInResumeTopActivity) {
  13. // If we are in resume section already, home activity will be initialized, but not
  14. // resumed (to avoid recursive resume) and will stay that way until something pokes it
  15. // again. We need to schedule another resume.
  16. mSupervisor.scheduleResumeTopActivities();
  17. }
  18. }
  1. ActivityStarter // 负责界面启动检查
  2. .execute()
  3. .executeRequest(mRequest)
  4. .startActivityUnchecked(final ActivityRecord r....)
  5. .startActivityInner(final ActivityRecord r....)
  6. mRootWindowContainer.resumeFocusedTasksTopActivities(mTargetRootTask....)
  7. RootWindowContainer
  8. .resumeFocusedTasksTopActivities(mTargetRootTask, mStartActivity, mOptions, mTransientLaunch)
  9. targetRootTask.resumeTopActivityUncheckedLocked(target, targetOptions, deferPause)
  10. Task
  11. .resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options, boolean deferPause)
  12. .resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options, boolean deferPause)
  13. topFragment.resumeTopActivity(prev, options, deferPause)
  14. TaskFragment
  15. .resumeTopActivity(ActivityRecord prev, ActivityOptions options, boolean deferPause)
  16. mTaskSupervisor.startSpecificActivity(next, true, true)
  17. ActivityTaskSupervisor // 负责所有Activity栈的管理
  18. .startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig)
  19. .realStartActivityLocked(r, wpc, andResume, checkConfig)
  20. clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent)....) // 解释LaunchActivityItem由来
  21. mService.getLifecycleManager().scheduleTransaction(clientTransaction)
  22. ClientLifecycleManager // 生命周期的管理调用
  23. .scheduleTransaction(ClientTransaction transaction)
  24. transaction.schedule();
  25. ClientTransaction // 客服端事务调度
  26. .schedule()
  27. IApplicationThread=mClient.scheduleTransaction(this)
  28. ActivityThread 内部类 ApplicationThread // ApplicationThread 实现IApplicationThread
  29. .scheduleTransaction(ClientTransaction transaction)
  30. ActivityThread.this.scheduleTransaction(transaction)
  31. ClientTransactionHandler // ActivityThread的父类 主要管理消息发送与执行
  32. .scheduleTransaction(ClientTransaction transaction)
  33. transaction.preExecute(this);
  34. sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
  35. ActivityThread.mH // mH是ActivityThread内部Handler
  36. TransactionExecutor=mTransactionExecutor.execute(transaction)
  37. TransactionExecutor // 主要作用是执行ClientTransaction
  38. .execute(ClientTransaction transaction)
  39. .executeLifecycleState(ClientTransaction transaction)
  40. lifecycleItem.execute(mTransactionHandler, token, mPendingActions)
  41. LaunchActivityItem // 继承自ClientTransactionItem,而ClientTransactionItem实现BaseClientRequest // ResumeActivityItem
  42. .execute(ClientTransactionHandler client, IBinder token, PendingTransactionActions pendingActions)
  43. ClientTransactionHandler=client.handleLaunchActivity(r, pendingActions, null /* customIntent */)
  44. ActivityThread ex ClientTransactionHandler // 管理应用程序进程中主线程的执行
  45. .handleLaunchActivity(ActivityClientRecord r, PendingTransactionActions pendingActions, Intent customIntent)
  46. .performLaunchActivity(r, customIntent)
  47. Instrumentation=mInstrumentation.callActivityOnCreate(activity....)
  48. Instrumentation
  49. .callActivityOnCreate(activity....)
  50. activity.performCreate(icicle)
  51. Activity
  52. .performCreate(Bundle icicle)
  53. .performCreate(Bundle icicle, PersistableBundle persistentState)
  54. .onCreate(icicle....)
  1. 应用进程的创建:
  2. ActivityTaskSupervisor
  3. mService.startProcessAsync(r, knownToBeDead...)
  4. ActivityTaskManagerService
  5. .startProcessAsync(r, knownToBeDead...)
  6. Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess...)
  7. ActivityManagerInternal抽象类实现ActivityManagerService.LocalService
  8. ActivityManagerService
  9. .startProcess(String processName, ApplicationInfo info, boolean knownToBeDead,boolean isTop, String hostingType, ComponentName hostingName)
  10. .tartProcessLocked(processName, info.....)
  11. .tartProcessLocked(processName, info.....) // 重载
  12. mProcessList.startProcessLocked(processName, info, knownToBeDead...)
  13. ProcessList
  14. .startProcessLocked(processName, info, knownToBeDead...)
  15. .startProcessLocked(processName, info, knownToBeDead...) // 重载
  16. final Process.ProcessStartResult startResult = startProcess(hostingRecord,entryPoint, app,....)
  17. startResult = appZygote.getProcess().start(entryPoint,app.processName, uid, uid, gids.....)
  18. AppZygote.getProcess返回ChildZygoteProcess继承ZygoteProcess
  19. ZygoteProcess
  20. .start(final String processClass,final String niceName,int uid, int gid, @Nullable int[] gids....)
  21. .startViaZygote(final String processClass,final String niceName,int uid, int gid, @Nullable int[] gids....)
  22. .zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), zygotePolicyFlags, argsForZygote)
  23. .attemptZygoteSendArgsAndGetResult(zygoteState, msgStr)
  24. zygoteWriter.write(msgStr); // 把应用进程参数写入zygote进程 比如 processClass ="android.app.ActivityThread"
  25. zygoteWriter.flush(); // 进入Zygote进程,处于阻塞状态
  26. // fork采用copy-on-write机制
  27. ZygoteInit
  28. .main(String[] argv)
  29. zygoteServer.runSelectLoop(abiList)->caller.run()
  30. ZygoteServer
  31. .runSelectLoop(abiList)
  32. final Runnable command = connection.processCommand(this, multipleForksOK)
  33. ZygoteConnection
  34. .processCommand(ZygoteServer zygoteServer, boolean multipleOK)
  35. handleChildProc(parsedArgs, childPipeFd,parsedArgs.mStartChildZygote)
  36. ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,parsedArgs.mDisabledCompatChanges,parsedArgs.mRemainingArgs, null /* classLoader */)
  37. ZygoteInit
  38. .zygoteInit(parsedArgs.mTargetSdkVersion,parsedArgs.mDisabledCompatChanges,parsedArgs.mRemainingArgs, null /* classLoader */)
  39. RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv,classLoader)
  40. RuntimeInit
  41. .applicationInit(int targetSdkVersion, long[] disabledCompatChanges,String[] argv, ClassLoader classLoader)
  42. .indStaticMain(String className, String[] argv,ClassLoader classLoader)
  43. new MethodAndArgsCaller(m, argv).run({mMethod.invoke(null, new Object[] { mArgs })})
  44. ActivityThread.main() 执行完成
 

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

闽ICP备14008679号