Android SystemServer进程解析

2024-03-16 06:12

本文主要是介绍Android SystemServer进程解析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

SystemServer进程在android系统中占了举足轻重的地位,系统的所有服务和SystemUI都是由它启动。

一、SystemServer进程主函数流程

1、主函数三部曲

//frameworks/base/services/java/com/android/server/SystemServer.java    /** * The main entry point from zygote. */public static void main(String[] args) {new SystemServer().run();}

SystemServer的入口函数同样是main,调用顺序先是构造函数,再是run,构造函数没有什么重点地方后文dump详细介绍,主要流程主要还是run方法。run里面哦流程其实还是遵循普遍的三部曲:初始化上下文->启动服务->进入loop循环

1)初始化上下文
//frameworks/base/services/java/com/android/server/SystemServer.java    private void run() {TimingsTraceAndSlog t = new TimingsTraceAndSlog();try {t.traceBegin("InitBeforeStartServices");//.....一些属性的初始化....// The system server should never make non-oneway callsBinder.setWarnOnBlocking(true);// The system server should always load safe labelsPackageItemInfo.forceSafeLabels();// Default to FULL within the system server.SQLiteGlobal.sDefaultSyncMode = SQLiteGlobal.SYNC_MODE_FULL;// Deactivate SQLiteCompatibilityWalFlags until settings provider is initializedSQLiteCompatibilityWalFlags.init(null);// Here we go! Slog.i(TAG, "Entered the Android system server!");final long uptimeMillis = SystemClock.elapsedRealtime(); //记录开始启动的时间错,调试系统启动时间的时候需要关注// Mmmmmm... more memory!VMRuntime.getRuntime().clearGrowthLimit();// Some devices rely on runtime fingerprint generation, so make sure we've defined it before booting further.Build.ensureFingerprintProperty();// Within the system server, it is an error to access Environment paths without explicitly specifying a user.Environment.setUserRequired(true);// Within the system server, any incoming Bundles should be defused to avoid throwing BadParcelableException.BaseBundle.setShouldDefuse(true);// Within the system server, when parceling exceptions, include the stack traceParcel.setStackTraceParceling(true);// Ensure binder calls into the system always run at foreground priority.BinderInternal.disableBackgroundScheduling(true);// Increase the number of binder threads in system_serverBinderInternal.setMaxThreads(sMaxBinderThreads);// Prepare the main looper thread (this thread).              android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_FOREGROUND);android.os.Process.setCanSelfBackground(false);Looper.prepareMainLooper();Looper.getMainLooper().setSlowLogThresholdMs(SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);SystemServiceRegistry.sEnableServiceNotFoundWtf = true;// Initialize native services.System.loadLibrary("android_servers");// Allow heap / perf profiling.initZygoteChildHeapProfiling();// Check whether we failed to shut down last time we tried. This call may not return.performPendingShutdown();// Initialize the system context.createSystemContext();// Call per-process mainline module initialization.ActivityThread.initializeMainlineModules();} finally {t.traceEnd();  // InitBeforeStartServices}
2)启动系统所有服务
//frameworks/base/services/java/com/android/server/SystemServer.java    // Start services.try {t.traceBegin("StartServices");startBootstrapServices(t);   //启动BOOT服务(即没有这些服务系统无法运行)startCoreServices(t);        //启动核心服务startOtherServices(t);       //启动其他服务startApexServices(t);        //启动APEX服务,此服务必现要在前面的所有服务启动之后才能启动,为了防止OTA相关问题// Only update the timeout after starting all the services so that we use// the default timeout to start system server.updateWatchdogTimeout(t);} catch (Throwable ex) {Slog.e("System", "******************************************");Slog.e("System", "************ Failure starting system services", ex);throw ex;} finally {t.traceEnd(); // StartServices}/*** Starts system services defined in apexes.* <p>Apex services must be the last category of services to start. No other service must be* starting after this point. This is to prevent unnecessary stability issues when these apexes* are updated outside of OTA; and to avoid breaking dependencies from system into apexes.*/private void startApexServices(@NonNull TimingsTraceAndSlog t) {t.traceBegin("startApexServices");// TODO(b/192880996): get the list from "android" package, once the manifest entries are migrated to system manifest.List<ApexSystemServiceInfo> services = ApexManager.getInstance().getApexSystemServices();for (ApexSystemServiceInfo info : services) {String name = info.getName();String jarPath = info.getJarPath();t.traceBegin("starting " + name);if (TextUtils.isEmpty(jarPath)) {mSystemServiceManager.startService(name);} else {mSystemServiceManager.startServiceFromJar(name, jarPath);}t.traceEnd();}// make sure no other services are started after this pointmSystemServiceManager.sealStartedServices();t.traceEnd(); // startApexServices}

如上代码大体启动了四类服务:

  • startBootstrapServices:启动一些关键引导服务,这些服务耦合到一起
  • startCoreServices:启动一些关键引导服务,这些服务没有耦合到一起
  • startOtherServices:启动其他一些杂七杂八的服务
  • startApexServices:启动apex类的服务,其实就是mainline那些东西,详情参考请点击我
3)进入loop循环
//frameworks/base/services/java/com/android/server/SystemServer.javaStrictMode.initVmDefaults(null);if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {final long uptimeMillis = SystemClock.elapsedRealtime();final long maxUptimeMillis = 60 * 1000;if (uptimeMillis > maxUptimeMillis) {Slog.wtf(SYSTEM_SERVER_TIMING_TAG, "SystemServer init took too long. uptimeMillis=" + uptimeMillis);}}// Loop forever.Looper.loop();throw new RuntimeException("Main thread loop unexpectedly exited");

和之前讲的binder一样,基本上所有的进程最后都会进入loop进行循环,轮询主线程相关的handle消息和binder消息,如下日志堆栈,表示handle消息处理过程中发生异常:

2、顺序启动服务

二、SystemServer正常启动日志

1、SystemServerTiming日志封装

2、SystemServer启动阶段OnBootPhase

3、SystemServer无法找到服务

4、Slow operation

三、SystemServer dumpsys解读

1、SystemServer的dump

2、其他服务的dump

SystemServer:Runtime restart: falseStart count: 1Runtime start-up time: +8s0msRuntime start-elapsed time: +8s0msSystemServiceManager:Current phase: 1000Current user not set!1 target users: 0(full)172 started services:com.transsion.hubcore.server.TranBootstrapServiceManagerServicecom.android.server.security.FileIntegrityServicecom.android.server.pm.Installercom.android.server.os.DeviceIdentifiersPolicyServicecom.android.server.uri.UriGrantsManagerService.Lifecyclecom.android.server.powerstats.PowerStatsServicecom.android.server.permission.access.AccessCheckingServicecom.android.server.wm.ActivityTaskManagerService.Lifecyclecom.android.server.am.ActivityManagerService.Lifecycle......com.android.server.Watchdog:WatchdogTimeoutMillis=60000SystemServerInitThreadPool:has instance: falsenumber of threads: 8service: java.util.concurrent.ThreadPoolExecutor@7bf04fb[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 351]is shutdown: trueno pending tasksAdServices:mAdServicesModuleName: com.google.android.adservicesmAdServicesModuleVersion: 341131050mHandlerThread: Thread[AdServicesManagerServiceHandler,5,main]mAdServicesPackagesRolledBackFrom: {}mAdServicesPackagesRolledBackTo: {}ShellCmd enabled: falseUserInstanceManagermAdServicesBaseDir: /data/system/adservicesmConsentManagerMapLocked: {}mAppConsentManagerMapLocked: {}mRollbackHandlingManagerMapLocked: {}mBlockedTopicsManagerMapLocked={}TopicsDbHelperCURRENT_DATABASE_VERSION: 1mDbFile: /data/system/adservices_topics.dbmDbVersion: 1

这篇关于Android SystemServer进程解析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/814554

相关文章

网页解析 lxml 库--实战

lxml库使用流程 lxml 是 Python 的第三方解析库,完全使用 Python 语言编写,它对 XPath表达式提供了良好的支 持,因此能够了高效地解析 HTML/XML 文档。本节讲解如何通过 lxml 库解析 HTML 文档。 pip install lxml lxm| 库提供了一个 etree 模块,该模块专门用来解析 HTML/XML 文档,下面来介绍一下 lxml 库

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

Android平台播放RTSP流的几种方案探究(VLC VS ExoPlayer VS SmartPlayer)

技术背景 好多开发者需要遴选Android平台RTSP直播播放器的时候,不知道如何选的好,本文针对常用的方案,做个大概的说明: 1. 使用VLC for Android VLC Media Player(VLC多媒体播放器),最初命名为VideoLAN客户端,是VideoLAN品牌产品,是VideoLAN计划的多媒体播放器。它支持众多音频与视频解码器及文件格式,并支持DVD影音光盘,VCD影

[Linux]:进程(下)

✨✨ 欢迎大家来到贝蒂大讲堂✨✨ 🎈🎈养成好习惯,先赞后看哦~🎈🎈 所属专栏:Linux学习 贝蒂的主页:Betty’s blog 1. 进程终止 1.1 进程退出的场景 进程退出只有以下三种情况: 代码运行完毕,结果正确。代码运行完毕,结果不正确。代码异常终止(进程崩溃)。 1.2 进程退出码 在编程中,我们通常认为main函数是代码的入口,但实际上它只是用户级

android-opencv-jni

//------------------start opencv--------------------@Override public void onResume(){ super.onResume(); //通过OpenCV引擎服务加载并初始化OpenCV类库,所谓OpenCV引擎服务即是 //OpenCV_2.4.3.2_Manager_2.4_*.apk程序包,存

OWASP十大安全漏洞解析

OWASP(开放式Web应用程序安全项目)发布的“十大安全漏洞”列表是Web应用程序安全领域的权威指南,它总结了Web应用程序中最常见、最危险的安全隐患。以下是对OWASP十大安全漏洞的详细解析: 1. 注入漏洞(Injection) 描述:攻击者通过在应用程序的输入数据中插入恶意代码,从而控制应用程序的行为。常见的注入类型包括SQL注入、OS命令注入、LDAP注入等。 影响:可能导致数据泄

从状态管理到性能优化:全面解析 Android Compose

文章目录 引言一、Android Compose基本概念1.1 什么是Android Compose?1.2 Compose的优势1.3 如何在项目中使用Compose 二、Compose中的状态管理2.1 状态管理的重要性2.2 Compose中的状态和数据流2.3 使用State和MutableState处理状态2.4 通过ViewModel进行状态管理 三、Compose中的列表和滚动

Spring 源码解读:自定义实现Bean定义的注册与解析

引言 在Spring框架中,Bean的注册与解析是整个依赖注入流程的核心步骤。通过Bean定义,Spring容器知道如何创建、配置和管理每个Bean实例。本篇文章将通过实现一个简化版的Bean定义注册与解析机制,帮助你理解Spring框架背后的设计逻辑。我们还将对比Spring中的BeanDefinition和BeanDefinitionRegistry,以全面掌握Bean注册和解析的核心原理。

CSP 2023 提高级第一轮 CSP-S 2023初试题 完善程序第二题解析 未完

一、题目阅读 (最大值之和)给定整数序列 a0,⋯,an−1,求该序列所有非空连续子序列的最大值之和。上述参数满足 1≤n≤105 和 1≤ai≤108。 一个序列的非空连续子序列可以用两个下标 ll 和 rr(其中0≤l≤r<n0≤l≤r<n)表示,对应的序列为 al,al+1,⋯,ar​。两个非空连续子序列不同,当且仅当下标不同。 例如,当原序列为 [1,2,1,2] 时,要计算子序列 [