come from : https://www.jianshu.com/p/ed798bc172f2
在上一文Android 系统的Zygote初始化过程说到,Zygote
初始化的时候会调用RuntimeInit
里面的zygoteInit()
方法,在该方法里面调用了applicationInit()
方法,然后通过反射调用了SystemServer
的main()
函数。
SystemServer
SystemServer
的main
函数如下
//frameworks/base/ android-7.1.2_r36/services /java/com/android/SystemServer.java
public static void main(String[] args) {
new SystemServer().run();
}
创建一个SystemServer
对象,同时执行run()
方法。接下来就是来到run()
方法
//frameworks/base/ android-7.1.2_r36/services /java/com/android/SystemServer.java
private void run() {
//...
System.loadLibrary("android_servers");
createSystemContext();
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
//...
}
主要有上面几个方法
- 加载了
libandroid_servers.so
,方法主要对应com_android_server_systemserver
,com_android_server_systemserver
主要有以下几个方法:
start_sensor_service
初始化手机传感器服务SensorService
,并且添加到BinderService
static int start_sensor_service(void* /*unused*/) {
SensorService::instantiate();`frameworks/native/services/sensorservice/SensorService.h`
return 0;
}
SensorService.h
继承于BinderService
,BnSensorServer
,Thread
,BinderService
相关代码如下
//`frameworks/native/include/binder/BinderService.h`
static status_t publish(bool allowIsolated = false) {
sp<IServiceManager> sm(defaultServiceManager());
return sm->addService(
String16(SERVICE::getServiceName()),
new SERVICE(), allowIsolated);
}
static void publishAndJoinThreadPool(bool allowIsolated = false) {
publish(allowIsolated);
joinThreadPool();
}
static void instantiate() { publish(); }
instantiate
调用了publish
方法,在publish
方法中主要把SensorService
服务添加到ServiceManager
,ServiceManager
是Binder
架构组成的组件之一,它是Binder
的守护进程,主要维护和管理创建的各种Service
。
android_server_SystemServer_startSensorService
static void android_server_SystemServer_startSensorService(JNIEnv* /* env */, jobject /* clazz */) {
char propBuf[PROPERTY_VALUE_MAX];
property_get("system_init.startsensorservice", propBuf, "1");
if (strcmp(propBuf, "1") == 0) {
// Start the sensor service in a new thread
createThreadEtc(start_sensor_service, nullptr,
"StartSensorThread", PRIORITY_FOREGROUND);
}
}
异步启动手机传感器服务SensorService
的JNI方法
register_android_server_SystemServer
int register_android_server_SystemServer(JNIEnv* env)
{
return jniRegisterNativeMethods(env, "com/android/server/SystemServer",
gMethods, NELEM(gMethods));
}
通过jni
注册android_server_SystemServer_startSensorService
方法,提供给给底层调用该方法启动传感器服务
createSystemContext()
方法
// frameworks/base/ android-7.1.2_r36/core/java/android/app/ActivityThread.java
private void createSystemContext() {
ActivityThread activityThread = ActivityThread.systemMain();
mSystemContext = activityThread.getSystemContext();
mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
}
这里涉及到ActivityThread
,ActivityThread
主要管理应用进程的UI
线程的执行,依次产生activities,broadcasts
,或者一些其他的操作请求,这里主要的作用是创建Context
。代码如下
//....
android.ddm.DdmHandleAppName.setAppName("system_process",
UserHandle.myUserId());
try {
mInstrumentation = new Instrumentation();
ContextImpl context = ContextImpl.createAppContext(
this, getSystemContext().mLoadedApk);
mInitialApplication = context.mLoadedApk.makeApplication(true, null);
mInitialApplication.onCreate();
} catch (Exception e) {
throw new RuntimeException(
"Unable to instantiate Application():" + e.toString(), e);
}
//....
- 设置
ddms
的应用进程号 - 通过
ContextImpl
创建Context
- 初始化
Application
,同时调用Application
的onCreate
方法
- 创建
SystemServiceManager
//...
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
//...
创建system service manager
并且添加到LocalServices
,SystemServiceManager
源码位于SystemService
同目录下面,注意SystemServer
和SystemService
的区别,SystemServer
产生Android
的各种服务,SystemService
维护Service
的生命周期的一个抽象类。它主要是通过ArrayList
保存SystemService
,在调用里面startService
方法的时候添加并且开始执行运行
@SuppressWarnings("unchecked")
public <T extends SystemService> T startService(Class<T> serviceClass) {
try {
//...
// Register it.
mServices.add(service);
// Start it.
try {
service.onStart();
} catch (RuntimeException ex) {
throw new RuntimeException("Failed to start service " + name
+ ": onStart threw an exception", ex);
}
return service;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
}
LocalServices指的是本地服务,它跟随主进程,不是一个独立的进程。主进程结束后,相应的本地服务也会相应的结束。主要定义了一个ArrayMap
来保存本地服务。
private static final ArrayMap<Class<?>, Object> sLocalServiceObjects =
new ArrayMap<Class<?>, Object>();
- 启动一些其他服务
//...
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
,代码如下
private void startBootstrapServices() {
//...
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
//...
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
//...
mSystemServiceManager.startService(LightsService.class);
//...
mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
//...
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
//...
if (!mOnlyCore) {
boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt",
false);
if (!disableOtaDexopt) {
traceBeginAndSlog("StartOtaDexOptService");
try {
OtaDexoptService.main(mSystemContext, mPackageManagerService);
} catch (Throwable e) {
reportWtf("starting OtaDexOptService", e);
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
}
}
//...
mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
//...
startSensorService();
}
通过SystemServiceManager
的startService
方法,启动了ActivityManagerService
,PowerManagerService
,LightsService
,DisplayManagerService
,PackageManagerService
,OtaDexoptService
,SensorService
等等
startCoreServices
代码如下
private void startCoreServices() {
mSystemServiceManager.startService(BatteryService.class);
mSystemServiceManager.startService(UsageStatsService.class);
mActivityManagerService.setUsageStatsManager(
LocalServices.getService(UsageStatsManagerInternal.class));
// Tracks whether the updatable WebView is in a ready state and watches for update installs.
mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
}
也是通过SystemServiceManager
的startService
方法,启动了BatteryService
,UsageStatsService
,LightsService
,DisplayManagerService
,UsageStatsManagerInternal
,WebViewUpdateService
等等
startOtherServices
代码如下
private void startOtherServices() {
final Context context = mSystemContext;
VibratorService vibrator = null;
IMountService mountService = null;
NetworkManagementService networkManagement = null;
NetworkStatsService networkStats = null;
NetworkPolicyManagerService networkPolicy = null;
ConnectivityService connectivity = null;
NetworkScoreService networkScore = null;
NsdService serviceDiscovery= null;
WindowManagerService wm = null;
SerialService serial = null;
NetworkTimeUpdateService networkTimeUpdater = null;
CommonTimeManagementService commonTimeMgmtService = null;
InputManagerService inputManager = null;
TelephonyRegistry telephonyRegistry = null;
ConsumerIrService consumerIr = null;
MmsServiceBroker mmsService = null;
HardwarePropertiesManagerService hardwarePropertiesService = null;
StatusBarManagerService statusBar = null;
INotificationManager notification = null;
LocationManagerService location = null;
CountryDetectorService countryDetector = null;
ILockSettings lockSettings = null;
AssetAtlasService atlas = null;
MediaRouterService mediaRouter = null;
//...
}
这里就是Android
的各种Service
了。
总的来说SystemServer
为Android
提供了各种Service
服务,它和Zygote
号称Android
世界的两大支柱