在上一文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);
//...
}
主要有上面幾個方法
1. 加載了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
世界的兩大支柱