System Server content
System Server是android 基本服务的提供者,是android系统运行的最基本需求,所有server运行在一个叫system_process的进程中,system_process进程是android java虚拟机跑的第一个进程,从Zygote 创建而来,是andorid系统最重要的java虚拟机。可以说,整个android系统的业务都是围绕system server而展开,所以,当system_process死掉了,手机必须重启。
System server主要包含以下服务:
以上所列系统服务不代表最新Android系统的所有系统服务。
这些服务那么重要,它们什么时候启动?都做了些什么事情?等等这些问题是本文以及大纲下面的文章将会一一道来。
了解这些系统服务之前,先来了解一个重量级的超级类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();
}
构造方法里面只做了从属性系统中读取了工厂测试模式,这个不在本文以及本大纲的文章中赘述的内容,这里就不在叙述了。
下面直接进入main()方法:
public static void main(String[] args) {
new SystemServer().run();
}
直接调用了类内的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);
}
.....
}
上述代码中,首先创建一个system context,这个对象在整个system server中使用非常频繁。接着创建一个SystemServiceManager.java的实例,顾名思义就是SystemService的管理者,管理所有的SystemService。代码中把接着创建一个SystemServiceManager的实例通过LocalServices.addService(SystemServiceManager.class, mSystemServiceManager)语句设置到LocalService中,LocalServices的功能类似SystemServiceManager,不同点在于LocalServices专门用来管理system_process进程中的SystemService,也就没有真正的跨进程通信,也就没有Binder对象。
接着就是启动各种系统服务,在这里分三种类型的SystemService,依次启动,分别对应三个方法:
startBootstrapServices();
startCoreServices();
startOtherServices();
这三个方法的顺序不能混乱,一定要按照上述顺序依次执行,先看startBootstrapServices()中启动了那些系统服务
private void startBootstrapServices() {
Installer installer = mSystemServiceManager.startService(Installer.class);
// Activity manager runs the show.
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "InitPowerManagement");
mActivityManagerService.initPowerManagement();
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
// Manages LEDs and display backlight so we need it to bring up the display.
mSystemServiceManager.startService(LightsService.class);
// Display manager is needed to provide display metrics before package manager
// starts up.
mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
// We need the default display before we can initialize the package manager.
mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
......
// Start the package manager.
.....
traceBeginAndSlog("StartUserManagerService");
mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
......
}
上述代码可以看到,这里启动了
启动这些SystemService都是通过SystemServiceManager的startService()的方式启动,启动完成后会回调SystemService的onStart()方法。
继续看第二个方法startCoreServices()启动了那些系统服务
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));
// Tracks whether the updatable WebView is in a ready state and watches for update installs.
mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
}
startCoreServices()中启动了
上文中提到,startBootstrapServices()必须在startCoreServices()前面执行,这里就能找到一个原因,startCoreServices()中用到mActivityManagerService对象,而该对象在startBootstrapServices()中被实例化,如果先调用startCoreServices(),mActivityManagerService对象便会发生NullPointerException的RuntimeException异常。
接着就是startOtherServices()中启动的service了,先看代码
private void startOtherServices() {
try {
ServiceManager.addService("scheduling_policy", new SchedulingPolicyService());
mSystemServiceManager.startService(TelecomLoaderService.class);
traceBeginAndSlog("StartTelephonyRegistry");
telephonyRegistry = new TelephonyRegistry(context);
ServiceManager.addService("telephony.registry", telephonyRegistry);
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
mEntropyMixer = new EntropyMixer(context);
mContentResolver = context.getContentResolver();
mSystemServiceManager.startService(CameraService.class);
mSystemServiceManager.startService(ACCOUNT_SERVICE_CLASS);
mSystemServiceManager.startService(CONTENT_SERVICE_CLASS);
mActivityManagerService.installSystemProviders();
vibrator = new VibratorService(context);
ServiceManager.addService("vibrator", vibrator);
consumerIr = new ConsumerIrService(context);
ServiceManager.addService(Context.CONSUMER_IR_SERVICE, consumerIr);
mSystemServiceManager.startService(AlarmManagerService.class);
final Watchdog watchdog = Watchdog.getInstance();
watchdog.init(context, mActivityManagerService);
traceBeginAndSlog("StartInputManagerService");
inputManager = new InputManagerService(context);
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
wm = WindowManagerService.main(context, inputManager,
mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,
!mFirstBoot, mOnlyCore);
ServiceManager.addService(Context.WINDOW_SERVICE, wm);
ServiceManager.addService(Context.INPUT_SERVICE, inputManager);
mSystemServiceManager.startService(VrManagerService.class);
mActivityManagerService.setWindowManager(wm);
inputManager.setWindowManagerCallbacks(wm.getInputMonitor());
inputManager.start();
// TODO: Use service dependencies instead.
mDisplayManagerService.windowManagerAndInputReady();
.....
mSystemServiceManager.startService(BluetoothService.class);
.....
mSystemServiceManager.startService(MetricsLoggerService.class);
mSystemServiceManager.startService(PinnerService.class);
} catch (RuntimeException e) {
}
// Bring up services needed for UI.
if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
mSystemServiceManager.startService(InputMethodManagerService.Lifecycle.class);
traceBeginAndSlog("StartAccessibilityManagerService");
try {
ServiceManager.addService(Context.ACCESSIBILITY_SERVICE,
new AccessibilityManagerService(context));
} catch (Throwable e) {
}
}
if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
if (!disableStorage &&
!"0".equals(SystemProperties.get("system_init.startmountservice"))) {
try {
mSystemServiceManager.startService(MOUNT_SERVICE_CLASS);
mountService = IMountService.Stub.asInterface(
ServiceManager.getService("mount"));
} catch (Throwable e) {
reportWtf("starting Mount Service", e);
}
}
}
mSystemServiceManager.startService(UiModeManagerService.class);
.....
if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
if (!disableNonCoreServices) {
try {
mSystemServiceManager.startService(LOCK_SETTINGS_SERVICE_CLASS);
lockSettings = ILockSettings.Stub.asInterface(
ServiceManager.getService("lock_settings"));
} catch (Throwable e) {
}
if (!SystemProperties.get(PERSISTENT_DATA_BLOCK_PROP).equals("")) {
mSystemServiceManager.startService(PersistentDataBlockService.class);
}
mSystemServiceManager.startService(DeviceIdleController.class);
mSystemServiceManager.startService(DevicePolicyManagerService.Lifecycle.class);
}
if (!disableSystemUI) {
try {
statusBar = new StatusBarManagerService(context, wm);
ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);
} catch (Throwable e) {
}
}
if (!disableNonCoreServices) {
try {
ServiceManager.addService(Context.CLIPBOARD_SERVICE,
new ClipboardService(context));
} catch (Throwable e) {
}
}
if (!disableNetwork) {
try {
networkManagement = NetworkManagementService.create(context);
ServiceManager.addService(Context.NETWORKMANAGEMENT_SERVICE, networkManagement);
} catch (Throwable e) {
}
}
if (!disableNonCoreServices && !disableTextServices) {
mSystemServiceManager.startService(TextServicesManagerService.Lifecycle.class);
}
if (!disableNetwork) {
traceBeginAndSlog("StartNetworkScoreService");
try {
networkScore = new NetworkScoreService(context);
ServiceManager.addService(Context.NETWORK_SCORE_SERVICE, networkScore);
} catch (Throwable e) {
}
try {
networkStats = NetworkStatsService.create(context, networkManagement);
ServiceManager.addService(Context.NETWORK_STATS_SERVICE, networkStats);
} catch (Throwable e) {
}
try {
networkPolicy = new NetworkPolicyManagerService(
context, mActivityManagerService,
(IPowerManager)ServiceManager.getService(Context.POWER_SERVICE),
networkStats, networkManagement);
ServiceManager.addService(Context.NETWORK_POLICY_SERVICE, networkPolicy);
} catch (Throwable e) {
}
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI_NAN)) {
mSystemServiceManager.startService(WIFI_NAN_SERVICE_CLASS);
} else {
Slog.i(TAG, "No Wi-Fi NAN Service (NAN support Not Present)");
}
mSystemServiceManager.startService(WIFI_P2P_SERVICE_CLASS);
mSystemServiceManager.startService(WIFI_SERVICE_CLASS);
mSystemServiceManager.startService(
"com.android.server.wifi.scanner.WifiScanningService");
if (!disableRtt) {
mSystemServiceManager.startService("com.android.server.wifi.RttService");
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_ETHERNET) ||
mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)) {
mSystemServiceManager.startService(ETHERNET_SERVICE_CLASS);
}
traceBeginAndSlog("StartConnectivityService");
try {
connectivity = new ConnectivityService(
context, networkManagement, networkStats, networkPolicy);
ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity);
networkStats.bindConnectivityManager(connectivity);
networkPolicy.bindConnectivityManager(connectivity);
} catch (Throwable e) {
}
try {
serviceDiscovery = NsdService.create(context);
ServiceManager.addService(
Context.NSD_SERVICE, serviceDiscovery);
} catch (Throwable e) {
reportWtf("starting Service Discovery Service", e);
}
if (!disableNonCoreServices) {
try {
ServiceManager.addService(Context.UPDATE_LOCK_SERVICE,
new UpdateLockService(context));
} catch (Throwable e) {
}
}
if (!disableNonCoreServices) {
mSystemServiceManager.startService(RecoverySystemService.class);
}
......
mSystemServiceManager.startService(NotificationManagerService.class);
notification = INotificationManager.Stub.asInterface(
ServiceManager.getService(Context.NOTIFICATION_SERVICE));
networkPolicy.bindNotificationManager(notification);
mSystemServiceManager.startService(DeviceStorageMonitorService.class);
if (!disableLocation) {
try {
location = new LocationManagerService(context);
ServiceManager.addService(Context.LOCATION_SERVICE, location);
} catch (Throwable e) {
}
try {
countryDetector = new CountryDetectorService(context);
ServiceManager.addService(Context.COUNTRY_DETECTOR, countryDetector);
} catch (Throwable e) {
}
}
if (!disableNonCoreServices && !disableSearchManager) {
traceBeginAndSlog("StartSearchManagerService");
try {
mSystemServiceManager.startService(SEARCH_MANAGER_SERVICE_CLASS);
} catch (Throwable e) {
}
}
mSystemServiceManager.startService(DropBoxManagerService.class);
if (!disableNonCoreServices && context.getResources().getBoolean(
R.bool.config_enableWallpaperService)) {
mSystemServiceManager.startService(WALLPAPER_SERVICE_CLASS);
}
mSystemServiceManager.startService(AudioService.Lifecycle.class);
if (!disableNonCoreServices) {
mSystemServiceManager.startService(DockObserver.class);
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH)) {
mSystemServiceManager.startService(THERMAL_OBSERVER_CLASS);
}
}
try {
// Listen for wired headset changes
inputManager.setWiredAccessoryCallbacks(
new WiredAccessoryManager(context, inputManager));
} catch (Throwable e) {
}
if (!disableNonCoreServices) {
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_MIDI)) {
// Start MIDI Manager service
mSystemServiceManager.startService(MIDI_SERVICE_CLASS);
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)
|| mPackageManager.hasSystemFeature(
PackageManager.FEATURE_USB_ACCESSORY)) {
mSystemServiceManager.startService(USB_SERVICE_CLASS);
}
if (!disableSerial) {
try {
// Serial port support
serial = new SerialService(context);
ServiceManager.addService(Context.SERIAL_SERVICE, serial);
} catch (Throwable e) {
}
}
"StartHardwarePropertiesManagerService");
try {
hardwarePropertiesService = new HardwarePropertiesManagerService(context);
ServiceManager.addService(Context.HARDWARE_PROPERTIES_SERVICE,
hardwarePropertiesService);
} catch (Throwable e) {
Slog.e(TAG, "Failure starting HardwarePropertiesManagerService", e);
}
}
mSystemServiceManager.startService(TwilightService.class);
mSystemServiceManager.startService(JobSchedulerService.class);
mSystemServiceManager.startService(SoundTriggerService.class);
if (!disableNonCoreServices) {
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_BACKUP)) {
mSystemServiceManager.startService(BACKUP_MANAGER_SERVICE_CLASS);
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_APP_WIDGETS)
|| context.getResources().getBoolean(R.bool.config_enableAppWidgetService)) {
mSystemServiceManager.startService(APPWIDGET_SERVICE_CLASS);
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_VOICE_RECOGNIZERS)) {
mSystemServiceManager.startService(VOICE_RECOGNITION_MANAGER_SERVICE_CLASS);
}
if (GestureLauncherService.isGestureLauncherEnabled(context.getResources())) {
Slog.i(TAG, "Gesture Launcher Service");
mSystemServiceManager.startService(GestureLauncherService.class);
}
mSystemServiceManager.startService(SensorNotificationService.class);
mSystemServiceManager.startService(ContextHubSystemService.class);
}
try {
ServiceManager.addService("diskstats", new DiskStatsService(context));
} catch (Throwable e) {
}
if (!disableSamplingProfiler) {
traceBeginAndSlog("StartSamplingProfilerService");
try {
ServiceManager.addService("samplingprofiler",
new SamplingProfilerService(context));
} catch (Throwable e) {
}
}
if (!disableNetwork && !disableNetworkTime) {
traceBeginAndSlog("StartNetworkTimeUpdateService");
try {
networkTimeUpdater = new NetworkTimeUpdateService(context);
ServiceManager.addService("network_time_update_service", networkTimeUpdater);
} catch (Throwable e) {
}
}
traceBeginAndSlog("StartCommonTimeManagementService");
try {
commonTimeMgmtService = new CommonTimeManagementService(context);
ServiceManager.addService("commontime_management", commonTimeMgmtService);
} catch (Throwable e) {
}
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
if (!disableNetwork) {
try {
CertBlacklister blacklister = new CertBlacklister(context);
} catch (Throwable e) {
}
}
if (!disableNonCoreServices) {
mSystemServiceManager.startService(DreamManagerService.class);
}
if (!disableNonCoreServices && ZygoteInit.PRELOAD_RESOURCES) {
traceBeginAndSlog("StartAssetAtlasService");
try {
atlas = new AssetAtlasService(context);
ServiceManager.addService(AssetAtlasService.ASSET_ATLAS_SERVICE, atlas);
} catch (Throwable e) {
}
}
if (!disableNonCoreServices) {
ServiceManager.addService(GraphicsStatsService.GRAPHICS_STATS_SERVICE,
new GraphicsStatsService(context));
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PRINTING)) {
mSystemServiceManager.startService(PRINT_MANAGER_SERVICE_CLASS);
}
mSystemServiceManager.startService(RestrictionsManagerService.class);
mSystemServiceManager.startService(MediaSessionService.class);
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_HDMI_CEC)) {
mSystemServiceManager.startService(HdmiControlService.class);
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LIVE_TV)) {
mSystemServiceManager.startService(TvInputManagerService.class);
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) {
mSystemServiceManager.startService(MediaResourceMonitorService.class);
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {
mSystemServiceManager.startService(TvRemoteService.class);
}
if (!disableNonCoreServices) {
traceBeginAndSlog("StartMediaRouterService");
try {
mediaRouter = new MediaRouterService(context);
ServiceManager.addService(Context.MEDIA_ROUTER_SERVICE, mediaRouter);
} catch (Throwable e) {
}
if (!disableTrustManager) {
mSystemServiceManager.startService(TrustManagerService.class);
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
mSystemServiceManager.startService(FingerprintService.class);
}
}
// LauncherAppsService uses ShortcutService.
mSystemServiceManager.startService(ShortcutService.Lifecycle.class);
mSystemServiceManager.startService(LauncherAppsService.class);
}
if (!disableNonCoreServices && !disableMediaProjection) {
mSystemServiceManager.startService(MediaProjectionManagerService.class);
}
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH)) {
mSystemServiceManager.startService(WEAR_BLUETOOTH_SERVICE_CLASS);
}
mmsService = mSystemServiceManager.startService(MmsServiceBroker.class);
// It is now time to start up the app processes...
try {
vibrator.systemReady();
} catch (Throwable e) {
}
if (lockSettings != null) {
try {
lockSettings.systemReady();
} catch (Throwable e) {
}
}
// Needed by DevicePolicyManager for initialization
mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);
mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);
Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeWindowManagerServiceReady");
try {
wm.systemReady();
} catch (Throwable e) {
}
try {
// TODO: use boot phase
mPowerManagerService.systemReady(mActivityManagerService.getAppOpsService());
} catch (Throwable e) {
}
try {
mPackageManagerService.systemReady();
} catch (Throwable e) {
}
try {
// TODO: use boot phase and communicate these flags some other way
mDisplayManagerService.systemReady(safeMode, mOnlyCore);
} catch (Throwable e) {
}
mActivityManagerService.systemReady(new Runnable() {
@Override
public void run() {
try {
startSystemUi(context);
} catch (Throwable e) {
}
"MakeNetworkManagementServiceReady");
try {
if (networkManagementF != null) networkManagementF.systemReady();
} catch (Throwable e) {
reportWtf("making Network Managment Service ready", e);
}
"MakeNetworkStatsServiceReady");
try {
if (networkStatsF != null) networkStatsF.systemReady();
} catch (Throwable e) {
}
try {
if (networkPolicyF != null) networkPolicyF.systemReady();
} catch (Throwable e) {
reportWtf("making Network Policy Service ready", e);
}
"MakeConnectivityServiceReady");
try {
if (connectivityF != null) connectivityF.systemReady();
} catch (Throwable e) {
}
Watchdog.getInstance().start();
try {
if (locationF != null) locationF.systemRunning();
} catch (Throwable e) {
}
try {
if (countryDetectorF != null) countryDetectorF.systemRunning();
} catch (Throwable e) {
}
try {
if (networkTimeUpdaterF != null) networkTimeUpdaterF.systemRunning();
} catch (Throwable e) {
}
try {
if (commonTimeMgmtServiceF != null) {
commonTimeMgmtServiceF.systemRunning();
}
} catch (Throwable e) {
}
try {
if (atlasF != null) atlasF.systemRunning();
} catch (Throwable e) {
}
try {
// TODO(BT) Pass parameter to input manager
if (inputManagerF != null) inputManagerF.systemRunning();
} catch (Throwable e) {
}
try {
if (telephonyRegistryF != null) telephonyRegistryF.systemRunning();
} catch (Throwable e) {
reportWtf("Notifying TelephonyRegistry running", e);
}
try {
if (mediaRouterF != null) mediaRouterF.systemRunning();
} catch (Throwable e) {
}
try {
if (mmsServiceF != null) mmsServiceF.systemRunning();
} catch (Throwable e) {
}
try {
if (networkScoreF != null) networkScoreF.systemRunning();
} catch (Throwable e) {
}
}
});
}
这个方法中启动的service非常多,代码量非常巨大,所以可见,这个方法对于Android系统而言,不言也可知其重要性。由于代码量巨大,将startOtherServices()分成三部分解说:
1.startOtherServices()中启动了那些服务
所列的这些服务,不一定全部都启动,系统会依照一些配置,选择性启动某些服务。如,因为Android系统会用于众多设备,手机,电视等等,当Android安装到电视设备是,TvInputManagerService、TvRemoteService这些service才会被启动,相反,手机设备时,这两个服务就不会被启动了。
2.不同的启动服务的方式
不知读者是否注意到,在startOtherServices()中存在和startBootstrapServices()、startCoreServices()中不同的启动service的方法,在startBootstrapServices()、startCoreServices()中见到SystemServiceManager.startService()和LocalServices.addService()的方式,而startOtherServices()中又多了ServiceManager.addService(),这三种方式有什么不同呢?
类型不同
SystemServiceManager.startService()和LocalServices.addService()启动的系统服务是SystemService的子类,启动这些服务后会回调SystemService的onStart()方法。ServiceManager.addService()启动的系统服务是实现了Android IPC 的Binder的子类,这些服务启动后会调用systemReady()或systemRunning()方法。
SystemServiceManager.startService()和ServiceManager.addService()中启动的服务需要Binder对象,而LocalServices.addService()却没有Binder对象。
SystemServiceManager.startService()中启动的是需要关心lifecycle events的服务,而ServiceManager.addService()和LocalServices.addService()不关心lifecycle events。
ServiceManager.addService()启动的服务本身是实现Binder通信的子类,而一般SystemServiceManager.startService()启动的服务是某个服务的内部类且这个内部类是SystemService的子类,如BackupManagerService$Lifecycle,在启动这个Lifecycle的内部类服务时,当回调onStart()方法时通过SystemService的publishBinderService()方法应用某个服务的Binder对象,且这个Binder的实现类也是某个服务的内部类。也就是说需要启动服务,而这个服务需要关心lifecycle events,所以不能通过ServiceManager.addService()的方式启动,然后在这个服务中声明一个实现了SystemService的子类Lifecycle,来接受lifecycle events,通过SystemServiceManager.startService()的方式启动这个服务,在SystemService的回调方法onStart()中应用这个服务的Binder对象。所以通过SystemServiceManager.startService()启动的服务,实际是启动了一个即需要关心lifecycle events,也需要像ServiceManager.addService()那样需要Binder对象的服务。
所以,其实在startBootstrapServices()中就已经通过ServiceManager.addService()的方式启动了一些特别特别重要的服务,如:
private void startBootstrapServices() {
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
}
public static PackageManagerService main(Context context, Installer installer,
boolean factoryTest, boolean onlyCore) {
......
ServiceManager.addService("package", m);
return m;
}
3.通过ServiceManager.addService()启动的服务,会调用服务的systemReady()或systemRunning()方法,初始化一些需要在系统服务启动后的其它代码。如启动SystemUI。
全部启动所需要的服务以后,SystemServer便要进入了接受Message的循环中,等待Message的事件。
在本大纲中,认识了Android系统启动时需要启动的服务,以及
三种不同的启动系统服务的方式,通过这三种启动的服务各有什么不同。另外,Android系统除了在启动的时候可以初始化服务,在运行中,也可能有新的服务被加进来,如某些APP启动时,会增加一些服务,如Phone APP(Telephony)
public void onCreate() {
phoneMgr = PhoneInterfaceManager.init(this, PhoneFactory.getDefaultPhone());
}
static PhoneInterfaceManager init(PhoneGlobals app, Phone phone) {
synchronized (PhoneInterfaceManager.class) {
if (sInstance == null) {
sInstance = new PhoneInterfaceManager(app, phone);
......
return sInstance;
}
}
private PhoneInterfaceManager(PhoneGlobals app, Phone phone) {
publish();
}
private void publish() {
ServiceManager.addService("phone", this);
}
到此,System Server的大纲介绍到这里,在本大纲的牵引下,一一以分文章(文档)的形式对各个系统服务进入全面的了解。