您的位置:首页 > 房产 > 建筑 > 网页开发模板_网页生成快捷方式带图标_seo与sem的关系_站长之家关键词挖掘

网页开发模板_网页生成快捷方式带图标_seo与sem的关系_站长之家关键词挖掘

2025/1/23 1:51:23 来源:https://blog.csdn.net/lansus/article/details/144964056  浏览:    关键词:网页开发模板_网页生成快捷方式带图标_seo与sem的关系_站长之家关键词挖掘
网页开发模板_网页生成快捷方式带图标_seo与sem的关系_站长之家关键词挖掘

在这里插入图片描述

init加载

init进程启动流程

1 FirstStageMain 第一阶段,创建挂载系统启动需要的目录
2 FirstStageMain 第一阶段 加载内核模块
3 FirstStageMain 第一阶段 授予文件权限
4 FirstStageMain 第一阶段 执行init文件,进入selinux_setup
5 SetupSelinux 预编译文件编译 读取selinux policy 加载策 略文件
6 SetupSelinux 设置selinux的启动状态
7 SetupSelinux 执行init文件 进入second_stage
8 SecondStageMain 第二阶段 加载系统属性和对应的selinux安全上下文
9 SecondStageMain 第二阶段 注册sigchild信号处理函数
10 SecondStageMain 第二阶段 StartPropertyService打开属性服务
11 SecondStageMain 第二阶段 LoadBootScripts 加载init.rc脚本文件
12 SecondStageMain
第二阶段 添加Action到行为队列中
13 SecondStageMain 第二阶段 进入无线循环 按序处理Action 每次处理后

检查是否需要重启进程,监听sigCHLD信号回收僵尸进程,监听系统属性变化 处理一种被称为"chorded keyboard"的键盘输入事件
当无事件时epoll_wait会堵塞当前线程
整体解析流程
1 解析配置文件
判断ro.boot.init_rc属性的值(文件路径)是否存在
存在解析ro.boot.init_rc属性的值
不存在解析
遍历一下目录解析配置文件
/system/etc/init
/vendor/etc/init
/odm/etc/init
/product/etc/init

其中,init的进程在kernel内核加载完成后启动,init在启动时候会加载init.rc进行解析, 文件在
在 Android 8.0 版本后, 对 init.rc 文件进行了拆分,每个服务对应一个 rc 文件。
• init.XXX.rc 文件:这里的 XXX 代指不同的服务,是多个非常重要的配置文件。该文件是由 Android 初始化语言 Android Init Language 编写的脚本。例如 Zygote 启动脚本在 init.zygoteXX.rc 中定义,XX 是处理器位数,例如 64 位处理器是 init.zygote64.rc 。
从 Android5.0 开始, Android 开始支持 64 位程序, Zygote 有了 32 和 64 位的区别, ro.zygote 的取值有以下四种:
• init.zygote32.rc :表示支持纯 32 位程序。
• init.zygote64.rc : 表示支持纯 64 位程序。
• init.zygote32_64.rc :表示即支持 32 位程序也支持 64 位程序;脚本中有两个 Service ,会启动两个 Zygote 进程:
○ 一个名为 zygote,执行程序为 app_process32 ,作为主模式;
○ 另一个名为 zygotę_secondary ,执行程序为 app_process64 ,作为辅模式。
• init.zygote64_32.rc:主模式与辅模式正好与 32_64 相反
Init.rc的代码,下面定义的是服务启动的时机:
init.rc - Android社区 - https://www.androidos.net.cn/
on zygote-start && property:ro.crypto.state=unencrypted
# A/B update verifier that marks a successful boot.
exec_start update_verifier_nonencrypted
start netd
start zygote
start zygote_secondary

on zygote-start && property:ro.crypto.state=unsupported
# A/B update verifier that marks a successful boot.
exec_start update_verifier_nonencrypted
start netd
start zygote
start zygote_secondary

on zygote-start && property:ro.crypto.state=encrypted && property:ro.crypto.type=file
# A/B update verifier that marks a successful boot.
exec_start update_verifier_nonencrypted
start netd
start zygote
start zygote_secondary
代码中的 on 表示事件,它的事件名称是 early-init,表示系统在执行 early-init 这个事件的时候触发,触发之后,会执行下面的所有操作,直到遇见下一个事件

启动init服务, 会加载init.rc文件,这里面要注意的是:
init.rc有两个,确切的说是两套,分别位于:
./system/core/rootdir/init.rc
./bootable/recovery/etc/init.rc
从目录上大致可以猜测,这两个init.rc使用场景不一样,一个是刷机用到的,也就是进入recorvery模式,一个是正常启动用到的;我们这里重点分析的是上面那个,也是init.c关联的那个。

/system/core/init/init.cpp(这一点从android 7开始,分成多个不同的rc文件)
static void LoadBootScripts(ActionManager& action_manager, ServiceList& service_list) {Parser parser = CreateParser(action_manager, service_list);std::string bootscript = GetProperty("ro.boot.init_rc", "");if (bootscript.empty()) {parser.ParseConfig("/init.rc");if (!parser.ParseConfig("/system/etc/init")) {late_import_paths.emplace_back("/system/etc/init");}if (!parser.ParseConfig("/product/etc/init")) {late_import_paths.emplace_back("/product/etc/init");}if (!parser.ParseConfig("/product_services/etc/init")) {late_import_paths.emplace_back("/product_services/etc/init");}if (!parser.ParseConfig("/odm/etc/init")) {late_import_paths.emplace_back("/odm/etc/init");}if (!parser.ParseConfig("/vendor/etc/init")) {late_import_paths.emplace_back("/vendor/etc/init");}} else {parser.ParseConfig(bootscript);}
}

这是init加载配置文件的代码,根据ro.boot.init_rc的配置,进行选择init.
• /system/etc/init/ 用于核心系统项,例如 SurfaceFlinger, MediaService和logd。
• /vendor/etc/init/ 是针对SoC供应商的项目,如SoC核心功能所需的actions或守护进程。
• /odm/etc/init/ 用于设备制造商的项目,如actions或运动传感器或其他外围功能所需的守护进程
同时,也会解析其他位置的服务定义, 比如Zygote服务:
zygote的服务定义在这个文件夹下面,:
/system/core/rootdir/init.zygote32.rc

service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-serverclass mainpriority -20user rootgroup root readproc reserved_disksocket zygote stream 660 root systemsocket usap_pool_primary stream 660 root systemonrestart write /sys/android_power/request_state wakeonrestart write /sys/power/state ononrestart restart audioserveronrestart restart cameraserveronrestart restart mediaonrestart restart netdonrestart restart wificondwritepid /dev/cpuset/foreground/tasks

它会被定义成一个class name是main的一个服务。 会被init启动,启动代码是:

从init.rc中启动到,定义了 Zygote的服务,会执行到 app/process里,在文件:

frameworks/base/cmds/app_process/app_main.cpp 的main方法。
int main(int argc, char* const argv[])
{// 创建并初始化AppRuntime对象runtimeAppRuntime runtime(argv[0], computeArgBlockSize(argc, argv));// 初始化参数zygote,startSystemServer,application,niceName,className// 代码见源码,此处略// 解析命令行参数// 代码见源码,此处略// 构建传递给 Java 初始化类的参数列表// 代码见源码,此处略if (zygote) {// 调用AppRuntime的start方法,开始加载ZygoteInit类runtime.start("com.android.internal.os.ZygoteInit", args, zygote);} else if (!className.isEmpty()) {runtime.start("com.android.internal.os.RuntimeInit", args, zygote);} else {fprintf(stderr, "Error: no class name or --zygote supplied.\n");app_usage();LOG_ALWAYS_FATAL("app_process: no class name or --zygote supplied.");}
}这里面会启动RunTime运行时的服务,
void AndroidRuntime::start(const char* className, const Vector<String8>& options, bool zygote)
{// 初始化Java Native Interface (JNI)。JNI是Java和C/C++之间的接口,它允许Java代码和C/C++代码相互调用JniInvocation jni_invocation;jni_invocation.Init(NULL);JNIEnv* env;  // JNIEnv环境指针// 初始化虚拟机if (startVm(&mJavaVM, &env, zygote, primary_zygote) != 0) {return;}// 注册JNI方法if (startReg(env) < 0) {return;}/** 以下代码执行后,当前线程(即运行 AndroidRuntime::start 方法的线程)将成为Java虚拟机(JVM)的主线程,并且在调用env->CallStaticVoidMethod启动指定的Java类的 main 方法后,这个方法不会返回,直到 JVM 退出为止。(官方文档说明)*/// 将"com.android.internal.os.ZygoteInit"转换为"com/android/internal/os/ZygoteInit"char* slashClassName = toSlashClassName(className != NULL ? className : "");jclass startClass = env->FindClass(slashClassName);if (startClass == NULL) {// 没有找到ZygoteInit.main()方法} else {// 通过JNI调用ZygoteInit.main()方法jmethodID startMeth = env->GetStaticMethodID(startClass, "main","([Ljava/lang/String;)V");}
}

• 创建虚拟机
• 注册JNI方法
• 通过JNI调用ZygoteInit.main() 这是java调用的第一个类, 在/frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
• main的方法为:

public static void main(String argv[]) {// 创建ZygoteServer对象ZygoteServer zygoteServer = new ZygoteServer();/* ... */try {/* ... */String socketName = "zygote";/* ... */// 创建一个Server端的Socket,并传入socketNamezygoteServer.registerServerSocket(socketName);if (!enableLazyPreload) {bootTimingsTraceLog.traceBegin("ZygotePreload");EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START, SystemClock.uptimeMillis());// 预加载类和资源preload(bootTimingsTraceLog);EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END, SystemClock.uptimeMillis());bootTimingsTraceLog.traceEnd();} else {Zygote.resetNicePriority();}/* ... */if (startSystemServer) {// 启动SystemServer进程,并捕获Zygote.MethodAndArgsCaller异常startSystemServer(abiList, socketName, zygoteServer);}Log.i(TAG, "Accepting command socket connections");// 等待AMS创建新应用程序进程的请求zygoteServer.runSelectLoop(abiList);zygoteServer.closeServerSocket();} catch (Zygote.MethodAndArgsCaller caller) {// SystemServer进程完成初始化,调用run方法caller.run();} catch (Throwable ex) {Log.e(TAG, "System zygote died with exception", ex);zygoteServer.closeServerSocket();throw ex;}
}private static boolean startSystemServer(String abiList, String socketName, ZygoteServer zygoteServer)throws Zygote.MethodAndArgsCaller, RuntimeException {/* ... */// 创建args数组,保存启动SystemServer的启动参数String args[] = {"--setuid=1000", 	// 用户id"--setgid=1000",	// 用户组id// 进程拥有的权限"--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1023,1032,3001,3002,3003,3006,3007,3009,3010","--capabilities=" + capabilities + "," + capabilities,"--nice-name=system_server",	// 进程名"--runtime-args",// 启动的类名"com.android.server.SystemServer",};ZygoteConnection.Arguments parsedArgs = null;int pid;try {// 将args数组封装成Arguments对象parsedArgs = new ZygoteConnection.Arguments(args);ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);// 创建一个子进程,即SystemServer进程pid = Zygote.forkSystemServer(parsedArgs.uid, parsedArgs.gid,parsedArgs.gids,parsedArgs.debugFlags,null,parsedArgs.permittedCapabilities,parsedArgs.effectiveCapabilities);} catch (IllegalArgumentException ex) {throw new RuntimeException(ex);}// 当前代码逻辑运行在子进程中if (pid == 0) {if (hasSecondZygote(abiList)) {waitForSecondaryZygote(socketName);}// 关闭Zygote进程创建的SocketzygoteServer.closeServerSocket();// 处理SystemServer进程handleSystemServerProcess(parsedArgs);}return true;
}

Zygote 进程都是通过fock 自身来创建子进程的,这样Zygote 进程以及它的子进程都可以进入app_main.cpp的main函数,因此main函数中为了区分当前运行在哪个进程,会在注释1处判断参数arg中是否包含了“–zygote”​,如果包含了则说明main函数是运行在Zygote进程中的并在注释2处将zygote设置为ture。同理在注释3处判断参数arg中是否包含了“–start-system-server”​,如果包含了则说明main函数是运行在SystemServer进程中的并在注释4处将startSystemServer 设置为true。
上面的loop就是一个死循环, 根据收到 的socket消息进行子进程Folk创建。systemserver是zygote folk的第一个进程。zygote进程也叫app_process进程
zygote进程会读取这个文件配置:
1)创建一个Server端的Socket。
(2)预加载类和资源。
(3)启动SystemServer进程。
(4)等待AMS请求创建新的应用程序进程。
在这里插入图片描述

System server概要
System server主要包含以下服务:

1、 EntropyService, 熵服务,用于产生随机数;
2、 PowerManagerService, 电源管理服务;
3、 ActivityMangerService Activity,管理服务;
4、 TelephonyRegistry, 电话服务,电话底层通知服务;
5、 PackageManagerService, 程序包管理服务;
6、 AccountManagerService, 联系人账户管理服务;
7、 ContentService, 内容提供器服务,提供跨进程数据交换;
8、 LightService, 光感应传感器服务;
9、 BatteryService,电池服务;
10、 VibrateService,震动器服务;
11、 AlarmManagerService,闹钟服务;
12、 WindowManagerService,窗口管理服务;
13、 BluetoothService,蓝牙服务;
14、 InputMethodManagerService,输入法服务;
15、 AccessibilityManagerService, 辅助器管理程序服务;
16、 DevicePolicyManagerService,提供系统级别的设置及属性;
17、 StatusBarManagerService,状态栏管理服务;
18、 ClipboardService,粘贴板服务;
19、 NetworkManagerService,网络管理服务;
20、 TextServicesManagerService,用户管理服务;
21、 NetworkStatsService,手机网络状态服务;
22、 NetworkPolicyManagerService,low-level网络策略服务;
23、 WifiP2pService,Wifi点对点服务;
24、 WifiService,Wifi服务;
25、 ConnectivityService,网络连接状态服务;
26、 MountService,磁盘加载服务;
27、 NotificationManagerService,通知管理服务;
28、 DeviceStorageMonitorService,存储设备容量监听服务;
29、 LocationManagerService,位置管理服务;
30、 CountryDetectorService,检查用户当前所在国家服务;
31、 SearchManagerService,搜索管理服务;
32、 DropBoxManagerService,系统日志文件管理服务;
33、 WallpaperManagerService,壁纸管理服务;
34、 AudioService,AudioFlinger上层封装音频管理服务;
35、 UsbService,USB Host 和 device管理服务;
36、 UiModeManagerService,UI模式管理服务;
37、 BackupManagerService,备份服务;
38、 AppWidgetService,应用桌面部件服务;
39、 RecognitionManagerService,身份识别服务;
40、 DiskStatsService,磁盘统计服务;
41、 SamplingProfilerService,性能统计服务;
42、 NetworkTimeUpdateService,网络时间更新服务;
43、 InputManagerService,输入管理服务;
44、 FingerprintService,指纹服务;
45、 DreamManagerService, dreams服务;
46、 HdmiControlService, HDMI控制服务;
47、 SsvService,SIM卡状态和转换服务;

了解这些系统服务之前,先来了解一个重量级的超级类SystemServer.java, 这个类在AOSP中的路径是:frameworks/base/services/java/com/android/server/SystemServer.java,在上文中提到,从Zygote创建system_process进程时,便实例化了该类。熟悉java的开发者都知道,启动某个java程序时,最先调用的就是声明了main()方法的类。所以SystemServer.java被实例化后,便调用了main()方法。首先看看SystemServer.java的构造方法。

public SystemServer() {// Check for factory test mode.mFactoryTestMode = FactoryTest.getMode();
}
public static void main(String[] args) {new SystemServer().run();
}     
private void run() {try {// AndroidRuntime using the same set of system properties, but only the system_server// Initialize the system context.createSystemContext();// Create the system service manager.mSystemServiceManager = new SystemServiceManager(mSystemContext);LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);} finally {Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}// Start services.try {Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartServices");startBootstrapServices();startCoreServices();startOtherServices();} catch (Throwable ex) {Slog.e("System", "******************************************");Slog.e("System", "************ Failure starting system services", ex);throw ex;} finally {Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}.....
}

这里主要是看按照顺序启动的三个服务的方法:
startBootstrapServices()根据注释看出,时启动一些互相依赖的基础服务。首先启动的是看门狗。然后依次是:
• Installer。 是在启动其他服务之前,需要初始化一些必要目录,比如data/user等
• DeviceIdentifiersPolicyService。在某些情况下,在启动应用程序后我们需要访问设备标识v
• 符,因此在活动管理器之前注册设备标识符策略。
• UriGrantsManagerService.Lifecycle
• ActivityTaskManagerService.Lifecycle
• ActivityManagerService
• PowerManagerService
• LightsService
• DisplayManagerService
• PackageManagerService
• UserManagerService
• OverlayManagerService
• SensorPrivacyService
源码如下:

/*** Starts the small tangle of critical services that are needed to get the system off the* ground.  These services have complex mutual dependencies which is why we initialize them all* in one place here.  Unless your service is also entwined in these dependencies, it should be* initialized in one of the other functions.*/private void startBootstrapServices() {// Start the watchdog as early as possible so we can crash the system server// if we deadlock during early boottraceBeginAndSlog("StartWatchdog");final Watchdog watchdog = Watchdog.getInstance();watchdog.start();traceEnd();Slog.i(TAG, "Reading configuration...");final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig";traceBeginAndSlog(TAG_SYSTEM_CONFIG);SystemServerInitThreadPool.get().submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);traceEnd();// Wait for installd to finish starting up so that it has a chance to// create critical directories such as /data/user with the appropriate// permissions.  We need this to complete before we initialize other services.traceBeginAndSlog("StartInstaller");Installer installer = mSystemServiceManager.startService(Installer.class);traceEnd();// In some cases after launching an app we need to access device identifiers,// therefore register the device identifier policy before the activity manager.traceBeginAndSlog("DeviceIdentifiersPolicyService");mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);traceEnd();// Uri Grants Manager.traceBeginAndSlog("UriGrantsManagerService");mSystemServiceManager.startService(UriGrantsManagerService.Lifecycle.class);traceEnd();// Activity manager runs the show.traceBeginAndSlog("StartActivityManager");// TODO: Might need to move after migration to WM.ActivityTaskManagerService atm = mSystemServiceManager.startService(ActivityTaskManagerService.Lifecycle.class).getService();mActivityManagerService = ActivityManagerService.Lifecycle.startService(mSystemServiceManager, atm);mActivityManagerService.setSystemServiceManager(mSystemServiceManager);mActivityManagerService.setInstaller(installer);mWindowManagerGlobalLock = atm.getGlobalLock();traceEnd();// Power manager needs to be started early because other services need it.// Native daemons may be watching for it to be registered so it must be ready// to handle incoming binder calls immediately (including being able to verify// the permissions for those calls).traceBeginAndSlog("StartPowerManager");mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);traceEnd();traceBeginAndSlog("StartThermalManager");mSystemServiceManager.startService(ThermalManagerService.class);traceEnd();// Now that the power manager has been started, let the activity manager// initialize power management features.traceBeginAndSlog("InitPowerManagement");mActivityManagerService.initPowerManagement();traceEnd();// Bring up recovery system in case a rescue party needs a reboottraceBeginAndSlog("StartRecoverySystemService");mSystemServiceManager.startService(RecoverySystemService.class);traceEnd();// Now that we have the bare essentials of the OS up and running, take// note that we just booted, which might send out a rescue party if// we're stuck in a runtime restart loop.RescueParty.noteBoot(mSystemContext);// Manages LEDs and display backlight so we need it to bring up the display.traceBeginAndSlog("StartLightsService");mSystemServiceManager.startService(LightsService.class);traceEnd();traceBeginAndSlog("StartSidekickService");// Package manager isn't started yet; need to use SysProp not hardware featureif (SystemProperties.getBoolean("config.enable_sidekick_graphics", false)) {mSystemServiceManager.startService(WEAR_SIDEKICK_SERVICE_CLASS);}traceEnd();// Display manager is needed to provide display metrics before package manager// starts up.traceBeginAndSlog("StartDisplayManager");mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);traceEnd();// We need the default display before we can initialize the package manager.traceBeginAndSlog("WaitForDisplay");mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);traceEnd();// Only run "core" apps if we're encrypting the device.String cryptState = VoldProperties.decrypt().orElse("");if (ENCRYPTING_STATE.equals(cryptState)) {Slog.w(TAG, "Detected encryption in progress - only parsing core apps");mOnlyCore = true;} else if (ENCRYPTED_STATE.equals(cryptState)) {Slog.w(TAG, "Device encrypted - only parsing core apps");mOnlyCore = true;}// Start the package manager.if (!mRuntimeRestart) {MetricsLogger.histogram(null, "boot_package_manager_init_start",(int) SystemClock.elapsedRealtime());}traceBeginAndSlog("StartPackageManagerService");try {Watchdog.getInstance().pauseWatchingCurrentThread("packagemanagermain");mPackageManagerService = PackageManagerService.main(mSystemContext, installer,mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);} finally {Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain");}mFirstBoot = mPackageManagerService.isFirstBoot();mPackageManager = mSystemContext.getPackageManager();traceEnd();if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {MetricsLogger.histogram(null, "boot_package_manager_init_ready",(int) SystemClock.elapsedRealtime());}// Manages A/B OTA dexopting. This is a bootstrap service as we need it to rename// A/B artifacts after boot, before anything else might touch/need them.// Note: this isn't needed during decryption (we don't have /data anyways).if (!mOnlyCore) {boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt",false);if (!disableOtaDexopt) {traceBeginAndSlog("StartOtaDexOptService");try {Watchdog.getInstance().pauseWatchingCurrentThread("moveab");OtaDexoptService.main(mSystemContext, mPackageManagerService);} catch (Throwable e) {reportWtf("starting OtaDexOptService", e);} finally {Watchdog.getInstance().resumeWatchingCurrentThread("moveab");traceEnd();}}}traceBeginAndSlog("StartUserManagerService");mSystemServiceManager.startService(UserManagerService.LifeCycle.class);traceEnd();// Initialize attribute cache used to cache resources from packages.traceBeginAndSlog("InitAttributerCache");AttributeCache.init(mSystemContext);traceEnd();// Set up the Application instance for the system process and get started.traceBeginAndSlog("SetSystemProcess");mActivityManagerService.setSystemProcess();traceEnd();// Complete the watchdog setup with an ActivityManager instance and listen for reboots// Do this only after the ActivityManagerService is properly started as a system processtraceBeginAndSlog("InitWatchdog");watchdog.init(mSystemContext, mActivityManagerService);traceEnd();// DisplayManagerService needs to setup android.display scheduling related policies// since setSystemProcess() would have overridden policies due to setProcessGroupmDisplayManagerService.setupSchedulerPolicies();// Manages Overlay packagestraceBeginAndSlog("StartOverlayManagerService");mSystemServiceManager.startService(new OverlayManagerService(mSystemContext, installer));traceEnd();traceBeginAndSlog("StartSensorPrivacyService");mSystemServiceManager.startService(new SensorPrivacyService(mSystemContext));traceEnd();if (SystemProperties.getInt("persist.sys.displayinset.top", 0) > 0) {// DisplayManager needs the overlay immediately.mActivityManagerService.updateSystemUiContext();LocalServices.getService(DisplayManagerInternal.class).onOverlayChanged();}// The sensor service needs access to package manager service, app ops// service, and permissions service, therefore we start it after them.// Start sensor service in a separate thread. Completion should be checked// before using it.mSensorServiceStart = SystemServerInitThreadPool.get().submit(() -> {TimingsTraceLog traceLog = new TimingsTraceLog(SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);traceLog.traceBegin(START_SENSOR_SERVICE);startSensorService();traceLog.traceEnd();}, START_SENSOR_SERVICE);}

startCoreServices启动一些核心的服务:
• BatteryService 电池服务
• UsageStatsService 主要通过AMS等,来监测并记录各个应用的使用数据。
• WebViewUpdateService
• CachedDeviceStateService 跟踪 缓存和设备的状态
• BinderCallsStatsService 跟踪Binder在CPU所花费的时间
• LooperStatsService 统计程序 looper处理消息所还花费的时间
• RollbackManagerService 管理apk回滚的服务
• BugreportManagerService bug报告管理服务
• GpuService 管理GPU和GPU驱动

源码如下:
/*** Starts some essential services that are not tangled up in the bootstrap process.*/private void startCoreServices() {traceBeginAndSlog("StartBatteryService");// Tracks the battery level.  Requires LightService.mSystemServiceManager.startService(BatteryService.class);traceEnd();// Tracks application usage stats.traceBeginAndSlog("StartUsageService");mSystemServiceManager.startService(UsageStatsService.class);mActivityManagerService.setUsageStatsManager(LocalServices.getService(UsageStatsManagerInternal.class));traceEnd();// Tracks whether the updatable WebView is in a ready state and watches for update installs.if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {traceBeginAndSlog("StartWebViewUpdateService");mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);traceEnd();}// Tracks and caches the device state.traceBeginAndSlog("StartCachedDeviceStateService");mSystemServiceManager.startService(CachedDeviceStateService.class);traceEnd();// Tracks cpu time spent in binder callstraceBeginAndSlog("StartBinderCallsStatsService");mSystemServiceManager.startService(BinderCallsStatsService.LifeCycle.class);traceEnd();// Tracks time spent in handling messages in handlers.traceBeginAndSlog("StartLooperStatsService");mSystemServiceManager.startService(LooperStatsService.Lifecycle.class);traceEnd();// Manages apk rollbacks.traceBeginAndSlog("StartRollbackManagerService");mSystemServiceManager.startService(RollbackManagerService.class);traceEnd();// Service to capture bugreports.traceBeginAndSlog("StartBugreportManagerService");mSystemServiceManager.startService(BugreportManagerService.class);traceEnd();// Serivce for GPU and GPU drivertraceBeginAndSlog("GpuService");mSystemServiceManager.startService(GpuService.class);traceEnd();}
再来看最后的一个startOtherServices方法,这个里面有个不一样地方是,会读取系统预置信息,根据配置去启动对应的服务,而不是所有的:HardwarePropertiesManagerService hardwarePropertiesService = null;boolean disableSystemTextClassifier = SystemProperties.getBoolean("config.disable_systemtextclassifier", false);boolean disableNetworkTime = SystemProperties.getBoolean("config.disable_networktime",false);boolean disableCameraService = SystemProperties.getBoolean("config.disable_cameraservice",false);boolean disableSlices = SystemProperties.getBoolean("config.disable_slices", false);boolean enableLeftyService = SystemProperties.getBoolean("config.enable_lefty", false);boolean isEmulator = SystemProperties.get("ro.kernel.qemu").equals("1");

开启的服务有:
• KeyAttestationApplicationIdProviderService 负责提供与密钥认证相关的应用标识信息
。该服务的主要功能是为密钥认证过程提供应用的详细信息,包括应用的包名、版本号和签名信息等
• SchedulingPolicyService 负责管理进程和线程的调度策略
• TelecomLoaderService 会加载手机call模块中的TelecomService,把Telecom服务添加到系统服务中,并对默认短信通过模块等默认app进行相应的授权。
• AccountManagerService ContentService 一个系统级别的消息中心,可以说搭建了一个系统级的观察者模型,APP可以向消息中心注册观察者,选择订阅自己关心的消息,也可以通过消息中心发送信息,通知其他进程
• DropBoxManagerService DBMS服务,生成和管理系统日志服务
• VibratorService 负责管理和控制设备的振动器硬件。它允许应用程序通过系统服务来启动、停止和配置设备的震动效果
• DynamicSystemService 主要负责管理动态系统的安装和更新。它允许系统在运行时动态加载和卸载不同的系统映像,从而实现更灵活的系统更新和管理
• ConsumerIrService 负责管理设备的红外发射功能。它允许应用程序通过红外信号来控制其他设备,例如电视、空调等。开发者可以通过 ConsumerIrManager 类来访问和使用这个服务
• AlarmManagerService 负责管理和调度定时任务。它允许应用程序在未来某个时间点触发特定的操作,例如启动一个服务、发送一个广播等
• InputManagerService
• WindowManagerService
• VrManagerService Android 系统中的一个服务,负责管理虚拟现实(VR)模式的启用和相关功能。它允许系统在进入或退出 VR 模式时进行相应的配置和优化,在7.0的时候引入的
• BluetoothService 蓝牙服务
• IpConnectivityMetrics 主要负责收集和分析设备的 IP 连接性能数据
• NetworkWatchlistService
• Wifi 相关的接服务
….等等,源码太长我就不放了。这些服务都是通过startService方式启动,并注册到SystemServiceManager当中的。此外,我们要理解这些服务都是共同一个SystemServer进程,属于里面的一部分, 算是其中的一个子线程。

启动Application
当这些服务都启动了以后,其中的ActivityManagerService最终会调用systemReady()方法。

// We now tell the activity manager it is okay to run third party
// code.  It will call back into us once it has gotten to the state
// where third party code can really run (but before it has actually
// started launching the initial applications), for us to complete our
// initialization.
mActivityManagerService.systemReady(() -> {Slog.i(TAG, "Making services ready");t.traceBegin("StartActivityManagerReadyPhase");mSystemServiceManager.startBootPhase(t, SystemService.PHASE_ACTIVITY_MANAGER_READY);t.traceEnd();t.traceBegin("StartObservingNativeCrashes");try {mActivityManagerService.startObservingNativeCrashes();} catch (Throwable e) {reportWtf("observing native crashes", e);}t.traceEnd();

下面图是从网上找来的, Launcher的启动流程, 这个我会在后面单独一个专题去说

在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com