SystemServer 进程
1.1 SystemServer进程是由Zygote进程fork 出来的。上篇介绍了fork过程1.2 SystemServer进程 是用来启动各种系统服务的进程,例如ActivityManagerService,WindowManagerService,PowerManagerService,PackageManagerService等等,当应用需要系统服务也是通过SystemServer进程通讯获取服务对象进行交互。
SystemServer 调用
初始化
/**
* The main entry point from zygote.
*/
public static void main(String[] args) {
new SystemServer().run();
}
private void run() {
if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
Slog.w(TAG,
"System clock is before 1970; setting to 1970.");
SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
}
if (!SystemProperties.get(
"persist.sys.language").isEmpty()) {
final String languageTag = Locale.getDefault().toLanguageTag();
SystemProperties.set(
"persist.sys.locale", languageTag);
SystemProperties.set(
"persist.sys.language",
"");
SystemProperties.set(
"persist.sys.country",
"");
SystemProperties.set(
"persist.sys.localevar",
"");
}
Slog.i(TAG,
"Entered the Android system server!");
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, SystemClock.uptimeMillis());
SystemProperties.set(
"persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
if (SamplingProfilerIntegration.isEnabled()) {
SamplingProfilerIntegration.start();
mProfilerSnapshotTimer =
new Timer();
mProfilerSnapshotTimer.schedule(
new TimerTask() {
@Override
public void run() {
SamplingProfilerIntegration.writeSnapshot(
"system_server",
null);
}
}, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
}
VMRuntime.getRuntime().clearGrowthLimit();
VMRuntime.getRuntime().setTargetHeapUtilization(
0.8f);
Build.ensureFingerprintProperty();
Environment.setUserRequired(
true);
BinderInternal.disableBackgroundScheduling(
true);
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_FOREGROUND);
android.os.Process.setCanSelfBackground(
false);
Looper.prepareMainLooper();
System.loadLibrary(
"android_servers");
performPendingShutdown();
createSystemContext();
mSystemServiceManager =
new SystemServiceManager(mSystemContext);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
try {
startBootstrapServices();
startCoreServices();
startOtherServices();
}
catch (Throwable ex) {
Slog.e(
"System",
"******************************************");
Slog.e(
"System",
"************ Failure starting system services", ex);
throw ex;
}
if (StrictMode.conditionallyEnableDebugLogging()) {
Slog.i(TAG,
"Enabled StrictMode for system server main thread.");
}
Looper.loop();
throw new RuntimeException(
"Main thread loop unexpectedly exited");
}
1.1 初始化系统时间
if (System
.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
Slog
.w(TAG,
"System clock is before 1970; setting to 1970.")
SystemClock
.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME)
}
1.2 设置语言,位置,国家,地区(只有系统app和系统服务可修改)
if (!SystemProperties
.get(
"persist.sys.language")
.isEmpty()) {
final String languageTag = Locale
.getDefault()
.toLanguageTag()
SystemProperties
.set(
"persist.sys.locale", languageTag)
SystemProperties
.set(
"persist.sys.language",
"")
SystemProperties
.set(
"persist.sys.country",
"")
SystemProperties
.set(
"persist.sys.localevar",
"")
}
1.3 接下来无关紧要,设置虚拟机运行内存,加载运行库,初始化SystemServer进程异步消息Looper
Looper
.prepareMainLooper()
Looper
.loop()
2 创建SystemServer系统Context
private void createSystemContext() {
ActivityThread activityThread = ActivityThread
.systemMain()
mSystemContext = activityThread
.getSystemContext()
mSystemContext
.setTheme(android
.R.style.Theme_DeviceDefault_Light_DarkActionBar)
}
3 创建SystemServiceManager,SystemServiceManager是用来初始化各种系统服务的。创建之后,并存储起来。
mSystemServiceManager =
new SystemServiceManager(mSystemContext);
LocalServices.addService(SystemServiceManager.
class, mSystemServiceManager);
4 启动服务 startBootstrapServices 启动系统Boot级服务 startCoreServices 启动系统核心服务 startOtherServices 启动系统其他服务
try {
startBootstrapServices();
startCoreServices();
startOtherServices();
}
catch (Throwable ex) {
Slog.e(
"System",
"******************************************");
Slog.e(
"System",
"************ Failure starting system services", ex);
throw ex;
}
4.1 startBootstrapServices 先上源码
private void startBootstrapServices() {
Installer installer
= mSystemServiceManager
.startService(Installer
.class);
mActivityManagerService
= mSystemServiceManager
.startService(
ActivityManagerService
.Lifecycle
.class)
.getService();
mActivityManagerService
.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService
.setInstaller(installer);
mPowerManagerService
= mSystemServiceManager
.startService(PowerManagerService
.class);
mActivityManagerService
.initPowerManagement();
mSystemServiceManager
.startService(LightsService
.class);
mDisplayManagerService
= mSystemServiceManager
.startService(DisplayManagerService
.class);
mSystemServiceManager
.startBootPhase(SystemService
.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
String cryptState
= SystemProperties
.get(
"vold.decrypt");
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;
}
Slog
.i(
TAG,
"Package Manager");
mPackageManagerService
= PackageManagerService
.main(mSystemContext, installer,
mFactoryTestMode
!= FactoryTest
.FACTORY_TEST_OFF, mOnlyCore);
mFirstBoot
= mPackageManagerService
.isFirstBoot();
mPackageManager
= mSystemContext
.getPackageManager();
Slog
.i(
TAG,
"User Service");
ServiceManager
.addService(Context
.USER_SERVICE, UserManagerService
.getInstance());
AttributeCache
.init(mSystemContext);
mActivityManagerService
.setSystemProcess();
startSensorService();
}
4.1.1 首先startService
Installer installer = mSystemServiceManager
.startService(Installer
.class)
查看SystemServiceManager
public <T
extends SystemService> T startService(Class<T> serviceClass) {
final String name = serviceClass.getName();
Slog.i(TAG,
"Starting " + name);
if (!SystemService.
class.isAssignableFrom(serviceClass)) {
throw new RuntimeException(
"Failed to create " + name
+
": service must extend " + SystemService.
class.getName());
}
final T service;
try {
Constructor<T> constructor = serviceClass.getConstructor(Context.
class);
service = constructor.newInstance(mContext);
}
catch (InstantiationException ex) {
throw new RuntimeException(
"Failed to create service " + name
+
": service could not be instantiated", ex);
}
catch (IllegalAccessException ex) {
throw new RuntimeException(
"Failed to create service " + name
+
": service must have a public constructor with a Context argument", ex);
}
catch (NoSuchMethodException ex) {
throw new RuntimeException(
"Failed to create service " + name
+
": service must have a public constructor with a Context argument", ex);
}
catch (InvocationTargetException ex) {
throw new RuntimeException(
"Failed to create service " + name
+
": service constructor threw an exception", ex);
}
mServices.add(service);
try {
service.onStart();
}
catch (RuntimeException ex) {
throw new RuntimeException(
"Failed to start service " + name
+
": onStart threw an exception", ex);
}
return service;
}
4.1.2 这里我们看到Register & Start,service是传进来的Installer类 4.1.3 Installer类是系统安装apk的服务类,需要启动Installer服务之后才可以启动其他系统服务。 所以作为第一个启动的服务。 看一下onStart() 如何调用?
@Override
public void onStart() {
Slog.i(TAG,
"Waiting for installd to be ready.");
mInstaller.waitForConnection();
}
public void waitForConnection() {
for (;;) {
if (execute(
"ping") >=
0) {
return;
}
Slog.w(TAG,
"installd not ready");
SystemClock.sleep(
1000);
}
}
4.1.4 在 waitForConnection中 创建轮询,不断通过ping命令连接 Zygote进程,因为Android中只有SystemServer和Zygote进程通过socket方式通讯,其他进程通过Binder方式通讯。 只有在 SystemServer和Zygote 成功连接后,才会启动其他的服务。
4.1.5 启动其他服务
ActivityManagerService (SystemServiceManager.startService)PowerManagerService (SystemServiceManager.startService)LightsService(SystemServiceManager.startService)DisplayManagerService(SystemServiceManager.startService)PackageManagerService(PackageManagerService.main)通过ServiceManager.addService方法启动,再通过Binder机制与JNI交互UserManagerService(ServiceManager.addService)
public static PackageManagerService
main(Context context, Installer installer,
boolean factoryTest,
boolean onlyCore) {
PackageManagerService m =
new PackageManagerService(context, installer,
factoryTest, onlyCore);
ServiceManager.addService(
"package", m);
return m;
}
4.1.6 最后 startSensorService() 完成,以上这些服务有复杂的相互依赖关系,所以放在一起进行初始化
4.2 startCoreServices() 启动无相互依赖的核心服务
BatteryServiceUsageStatsManagerInternalWebViewUpdateService
private void startCoreServices() {
// Tracks the battery level. Requires LightService.
mSystemServiceManager
.startService(BatteryService
.class)
// Tracks application usage stats.
mSystemServiceManager
.startService(UsageStatsService
.class)
mActivityManagerService
.setUsageStatsManager(
LocalServices
.getService(UsageStatsManagerInternal
.class))
// Update after UsageStatsService is available, needed before performBootDexOpt.
mPackageManagerService
.getUsageStatsIfNoPackageUsageInfo()
// Tracks whether the updatable WebView is
in a ready state
and watches for update installs.
mSystemServiceManager
.startService(WebViewUpdateService
.class)
}
4.3 启动其他服务 startOtherServices(),代码太长就不贴了0.0(800行)
5.梳理一下