> 文章列表 > android framework-SystemServer进程

android framework-SystemServer进程

android framework-SystemServer进程

android framework-SystemServer进程

SystemServer进程信息

android framework-SystemServer进程

android framework-SystemServer进程

一、SystemServer整体时序图

android framework-SystemServer进程

涉及源码路径
android-10.0.0_r41\\frameworks\\base\\core\\java\\com\\android\\internal\\os\\ZygoteInit.java
android-10.0.0_r41\\frameworks\\base\\core\\java\\com\\android\\internal\\os\\Zygote.java
android-10.0.0_r41\\frameworks\\base\\core\\java\\com\\android\\internal\\os\\RuntimeInit.java
android-10.0.0_r41\\frameworks\\base\\services\\java\\com\\android\\server\\SystemServer.java

二、SystemServer概述

android framework-SystemServer进程
android framework-SystemServer进程

  • SystemServer和系统服务有着重要关系。Android系统中几乎所有的核心服务都在这个进程中,如ActivityManagerService、PowerManagerService和WindowManagerService等。SystemServer的核心就是启动各种系统服务。
  • 上面截图是Pixel3a手机的进程信息,可以看到无论是system_server,还是bluetooth,都是zygote的子进程

三、SystemServer核心方法

路径:android-10.0.0_r41\\frameworks\\base\\services\\java\\com\\android\\server\\SystemServer.java

3.1、createSystemContext

  private void createSystemContext() {ActivityThread activityThread = ActivityThread.systemMain();mSystemContext = activityThread.getSystemContext();mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);final Context systemUiContext = activityThread.getSystemUiContext();systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);}

通过ActivityThread创建获取系统的上下文环境

3.2、startBootstrapServices

 private void startBootstrapServices() {// Start the watchdog as early as possible so we can crash the system server// if we deadlock during early boottraceBeginAndSlog("StartWatchdog");final Watchdog watchdog = Watchdog.getInstance();watchdog.start();traceEnd();Slog.i(TAG, "Reading configuration...");final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig";traceBeginAndSlog(TAG_SYSTEM_CONFIG);SystemServerInitThreadPool.get().submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);traceEnd();// Wait for installd to finish starting up so that it has a chance to// create critical directories such as /data/user with the appropriate// permissions.  We need this to complete before we initialize other services.traceBeginAndSlog("StartInstaller");Installer installer = mSystemServiceManager.startService(Installer.class);traceEnd();// In some cases after launching an app we need to access device identifiers,// therefore register the device identifier policy before the activity manager.traceBeginAndSlog("DeviceIdentifiersPolicyService");mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);traceEnd();// Uri Grants Manager.traceBeginAndSlog("UriGrantsManagerService");mSystemServiceManager.startService(UriGrantsManagerService.Lifecycle.class);traceEnd();// Activity manager runs the show.traceBeginAndSlog("StartActivityManager");// TODO: Might need to move after migration to WM.ActivityTaskManagerService atm = mSystemServiceManager.startService(ActivityTaskManagerService.Lifecycle.class).getService();mActivityManagerService = ActivityManagerService.Lifecycle.startService(mSystemServiceManager, atm);mActivityManagerService.setSystemServiceManager(mSystemServiceManager);mActivityManagerService.setInstaller(installer);mWindowManagerGlobalLock = atm.getGlobalLock();traceEnd();// Power manager needs to be started early because other services need it.// Native daemons may be watching for it to be registered so it must be ready// to handle incoming binder calls immediately (including being able to verify// the permissions for those calls).traceBeginAndSlog("StartPowerManager");mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);traceEnd();traceBeginAndSlog("StartThermalManager");mSystemServiceManager.startService(ThermalManagerService.class);traceEnd();// Now that the power manager has been started, let the activity manager// initialize power management features.traceBeginAndSlog("InitPowerManagement");mActivityManagerService.initPowerManagement();traceEnd();// Bring up recovery system in case a rescue party needs a reboottraceBeginAndSlog("StartRecoverySystemService");mSystemServiceManager.startService(RecoverySystemService.class);traceEnd();// Now that we have the bare essentials of the OS up and running, take// note that we just booted, which might send out a rescue party if// we're stuck in a runtime restart loop.RescueParty.noteBoot(mSystemContext);// Manages LEDs and display backlight so we need it to bring up the display.traceBeginAndSlog("StartLightsService");mSystemServiceManager.startService(LightsService.class);traceEnd();traceBeginAndSlog("StartSidekickService");// Package manager isn't started yet; need to use SysProp not hardware featureif (SystemProperties.getBoolean("config.enable_sidekick_graphics", false)) {mSystemServiceManager.startService(WEAR_SIDEKICK_SERVICE_CLASS);}traceEnd();// Display manager is needed to provide display metrics before package manager// starts up.traceBeginAndSlog("StartDisplayManager");mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);traceEnd();// We need the default display before we can initialize the package manager.traceBeginAndSlog("WaitForDisplay");mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);traceEnd();// Only run "core" apps if we're encrypting the device.String cryptState = VoldProperties.decrypt().orElse("");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;}// Start the package manager.if (!mRuntimeRestart) {MetricsLogger.histogram(null, "boot_package_manager_init_start",(int) SystemClock.elapsedRealtime());}traceBeginAndSlog("StartPackageManagerService");try {Watchdog.getInstance().pauseWatchingCurrentThread("packagemanagermain");mPackageManagerService = PackageManagerService.main(mSystemContext, installer,mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);} finally {Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain");}mFirstBoot = mPackageManagerService.isFirstBoot();mPackageManager = mSystemContext.getPackageManager();traceEnd();if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {MetricsLogger.histogram(null, "boot_package_manager_init_ready",(int) SystemClock.elapsedRealtime());}// Manages A/B OTA dexopting. This is a bootstrap service as we need it to rename// A/B artifacts after boot, before anything else might touch/need them.// Note: this isn't needed during decryption (we don't have /data anyways).if (!mOnlyCore) {boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt",false);if (!disableOtaDexopt) {traceBeginAndSlog("StartOtaDexOptService");try {Watchdog.getInstance().pauseWatchingCurrentThread("moveab");OtaDexoptService.main(mSystemContext, mPackageManagerService);} catch (Throwable e) {reportWtf("starting OtaDexOptService", e);} finally {Watchdog.getInstance().resumeWatchingCurrentThread("moveab");traceEnd();}}}traceBeginAndSlog("StartUserManagerService");mSystemServiceManager.startService(UserManagerService.LifeCycle.class);traceEnd();// Initialize attribute cache used to cache resources from packages.traceBeginAndSlog("InitAttributerCache");AttributeCache.init(mSystemContext);traceEnd();// Set up the Application instance for the system process and get started.traceBeginAndSlog("SetSystemProcess");mActivityManagerService.setSystemProcess();traceEnd();// Complete the watchdog setup with an ActivityManager instance and listen for reboots// Do this only after the ActivityManagerService is properly started as a system processtraceBeginAndSlog("InitWatchdog");watchdog.init(mSystemContext, mActivityManagerService);traceEnd();// DisplayManagerService needs to setup android.display scheduling related policies// since setSystemProcess() would have overridden policies due to setProcessGroupmDisplayManagerService.setupSchedulerPolicies();// Manages Overlay packagestraceBeginAndSlog("StartOverlayManagerService");mSystemServiceManager.startService(new OverlayManagerService(mSystemContext, installer));traceEnd();traceBeginAndSlog("StartSensorPrivacyService");mSystemServiceManager.startService(new SensorPrivacyService(mSystemContext));traceEnd();if (SystemProperties.getInt("persist.sys.displayinset.top", 0) > 0) {// DisplayManager needs the overlay immediately.mActivityManagerService.updateSystemUiContext();LocalServices.getService(DisplayManagerInternal.class).onOverlayChanged();}// The sensor service needs access to package manager service, app ops// service, and permissions service, therefore we start it after them.// Start sensor service in a separate thread. Completion should be checked// before using it.mSensorServiceStart = SystemServerInitThreadPool.get().submit(() -> {TimingsTraceLog traceLog = new TimingsTraceLog(SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);traceLog.traceBegin(START_SENSOR_SERVICE);startSensorService();traceLog.traceEnd();}, START_SENSOR_SERVICE);}
  • startService
    1、 Installer
    2、 DeviceIdentifiersPolicyService
    3、UriGrantsManagerService
    4、 ActivityTaskManagerService
    5、 PowerManagerService
    6、 ThermalManagerService
    7、 RecoverySystemService
    8、LightsService
    9、DisplayManagerService
    10、UserManagerService
    11、OverlayManagerService
    12、SensorPrivacyService

3.3、startCoreServices

private void startCoreServices() {traceBeginAndSlog("StartBatteryService");// Tracks the battery level.  Requires LightService.mSystemServiceManager.startService(BatteryService.class);traceEnd();// Tracks application usage stats.traceBeginAndSlog("StartUsageService");mSystemServiceManager.startService(UsageStatsService.class);mActivityManagerService.setUsageStatsManager(LocalServices.getService(UsageStatsManagerInternal.class));traceEnd();// Tracks whether the updatable WebView is in a ready state and watches for update installs.if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {traceBeginAndSlog("StartWebViewUpdateService");mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);traceEnd();}// Tracks and caches the device state.traceBeginAndSlog("StartCachedDeviceStateService");mSystemServiceManager.startService(CachedDeviceStateService.class);traceEnd();// Tracks cpu time spent in binder callstraceBeginAndSlog("StartBinderCallsStatsService");mSystemServiceManager.startService(BinderCallsStatsService.LifeCycle.class);traceEnd();// Tracks time spent in handling messages in handlers.traceBeginAndSlog("StartLooperStatsService");mSystemServiceManager.startService(LooperStatsService.Lifecycle.class);traceEnd();// Manages apk rollbacks.traceBeginAndSlog("StartRollbackManagerService");mSystemServiceManager.startService(RollbackManagerService.class);traceEnd();// Service to capture bugreports.traceBeginAndSlog("StartBugreportManagerService");mSystemServiceManager.startService(BugreportManagerService.class);traceEnd();// Serivce for GPU and GPU driver.traceBeginAndSlog("GpuService");mSystemServiceManager.startService(GpuService.class);traceEnd();}
  • startService
    1、 BatteryService
    2、 UsageStatsService
    3、 WebViewUpdateService
    4、 CachedDeviceStateService
    5、 BinderCallsStatsService
    6、 LooperStatsService
    7、 RollbackManagerService
    8、 BugreportManagerService
    9、 GpuService

2.4、startOtherServices

 private void startOtherServices() {final Context context = mSystemContext;VibratorService vibrator = null;DynamicSystemService dynamicSystem = null;IStorageManager storageManager = null;NetworkManagementService networkManagement = null;IpSecService ipSecService = null;NetworkStatsService networkStats = null;NetworkPolicyManagerService networkPolicy = null;ConnectivityService connectivity = null;NsdService serviceDiscovery = null;WindowManagerService wm = null;SerialService serial = null;NetworkTimeUpdateService networkTimeUpdater = null;InputManagerService inputManager = null;TelephonyRegistry telephonyRegistry = null;ConsumerIrService consumerIr = null;MmsServiceBroker mmsService = null;HardwarePropertiesManagerService hardwarePropertiesService = null;boolean disableSystemTextClassifier = SystemProperties.getBoolean("config.disable_systemtextclassifier", false);boolean disableNetworkTime = SystemProperties.getBoolean("config.disable_networktime",false);boolean disableCameraService = SystemProperties.getBoolean("config.disable_cameraservice",false);boolean disableSlices = SystemProperties.getBoolean("config.disable_slices", false);boolean enableLeftyService = SystemProperties.getBoolean("config.enable_lefty", false);boolean isEmulator = SystemProperties.get("ro.kernel.qemu").equals("1");boolean isWatch = context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH);boolean isArc = context.getPackageManager().hasSystemFeature("org.chromium.arc");boolean enableVrService = context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE);// For debugging RescuePartyif (Build.IS_DEBUGGABLE && SystemProperties.getBoolean("debug.crash_system", false)) {throw new RuntimeException();}try {final String SECONDARY_ZYGOTE_PRELOAD = "SecondaryZygotePreload";// We start the preload ~1s before the webview factory preparation, to// ensure that it completes before the 32 bit relro process is forked// from the zygote. In the event that it takes too long, the webview// RELRO process will block, but it will do so without holding any locks.mZygotePreload = SystemServerInitThreadPool.get().submit(() -> {try {Slog.i(TAG, SECONDARY_ZYGOTE_PRELOAD);TimingsTraceLog traceLog = new TimingsTraceLog(SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);traceLog.traceBegin(SECONDARY_ZYGOTE_PRELOAD);if (!Process.ZYGOTE_PROCESS.preloadDefault(Build.SUPPORTED_32_BIT_ABIS[0])) {Slog.e(TAG, "Unable to preload default resources");}traceLog.traceEnd();} catch (Exception ex) {Slog.e(TAG, "Exception preloading default resources", ex);}}, SECONDARY_ZYGOTE_PRELOAD);traceBeginAndSlog("StartKeyAttestationApplicationIdProviderService");ServiceManager.addService("sec_key_att_app_id_provider",new KeyAttestationApplicationIdProviderService(context));traceEnd();traceBeginAndSlog("StartKeyChainSystemService");mSystemServiceManager.startService(KeyChainSystemService.class);traceEnd();traceBeginAndSlog("StartSchedulingPolicyService");ServiceManager.addService("scheduling_policy", new SchedulingPolicyService());traceEnd();traceBeginAndSlog("StartTelecomLoaderService");mSystemServiceManager.startService(TelecomLoaderService.class);traceEnd();traceBeginAndSlog("StartTelephonyRegistry");telephonyRegistry = new TelephonyRegistry(context);ServiceManager.addService("telephony.registry", telephonyRegistry);traceEnd();traceBeginAndSlog("StartEntropyMixer");mEntropyMixer = new EntropyMixer(context);traceEnd();mContentResolver = context.getContentResolver();// The AccountManager must come before the ContentServicetraceBeginAndSlog("StartAccountManagerService");mSystemServiceManager.startService(ACCOUNT_SERVICE_CLASS);traceEnd();traceBeginAndSlog("StartContentService");mSystemServiceManager.startService(CONTENT_SERVICE_CLASS);traceEnd();traceBeginAndSlog("InstallSystemProviders");mActivityManagerService.installSystemProviders();// Now that SettingsProvider is ready, reactivate SQLiteCompatibilityWalFlagsSQLiteCompatibilityWalFlags.reset();traceEnd();// Records errors and logs, for example wtf()// Currently this service indirectly depends on SettingsProvider so do this after// InstallSystemProviders.traceBeginAndSlog("StartDropBoxManager");mSystemServiceManager.startService(DropBoxManagerService.class);traceEnd();traceBeginAndSlog("StartVibratorService");vibrator = new VibratorService(context);ServiceManager.addService("vibrator", vibrator);traceEnd();traceBeginAndSlog("StartDynamicSystemService");dynamicSystem = new DynamicSystemService(context);ServiceManager.addService("dynamic_system", dynamicSystem);traceEnd();if (!isWatch) {traceBeginAndSlog("StartConsumerIrService");consumerIr = new ConsumerIrService(context);ServiceManager.addService(Context.CONSUMER_IR_SERVICE, consumerIr);traceEnd();}traceBeginAndSlog("StartAlarmManagerService");mSystemServiceManager.startService(new AlarmManagerService(context));traceEnd();traceBeginAndSlog("StartInputManagerService");inputManager = new InputManagerService(context);traceEnd();traceBeginAndSlog("StartWindowManagerService");// WMS needs sensor service readyConcurrentUtils.waitForFutureNoInterrupt(mSensorServiceStart, START_SENSOR_SERVICE);mSensorServiceStart = null;wm = WindowManagerService.main(context, inputManager, !mFirstBoot, mOnlyCore,new PhoneWindowManager(), mActivityManagerService.mActivityTaskManager);ServiceManager.addService(Context.WINDOW_SERVICE, wm, /* allowIsolated= */ false,DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO);ServiceManager.addService(Context.INPUT_SERVICE, inputManager,/* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);traceEnd();traceBeginAndSlog("SetWindowManagerService");mActivityManagerService.setWindowManager(wm);traceEnd();traceBeginAndSlog("WindowManagerServiceOnInitReady");wm.onInitReady();traceEnd();// Start receiving calls from HIDL services. Start in in a separate thread// because it need to connect to SensorManager. This have to start// after START_SENSOR_SERVICE is done.SystemServerInitThreadPool.get().submit(() -> {TimingsTraceLog traceLog = new TimingsTraceLog(SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);traceLog.traceBegin(START_HIDL_SERVICES);startHidlServices();traceLog.traceEnd();}, START_HIDL_SERVICES);if (!isWatch && enableVrService) {traceBeginAndSlog("StartVrManagerService");mSystemServiceManager.startService(VrManagerService.class);traceEnd();}traceBeginAndSlog("StartInputManager");inputManager.setWindowManagerCallbacks(wm.getInputManagerCallback());inputManager.start();traceEnd();// TODO: Use service dependencies instead.traceBeginAndSlog("DisplayManagerWindowManagerAndInputReady");mDisplayManagerService.windowManagerAndInputReady();traceEnd();if (mFactoryTestMode == FactoryTest.FACTORY_TEST_LOW_LEVEL) {Slog.i(TAG, "No Bluetooth Service (factory test)");} else if (!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)) {Slog.i(TAG, "No Bluetooth Service (Bluetooth Hardware Not Present)");} else {traceBeginAndSlog("StartBluetoothService");mSystemServiceManager.startService(BluetoothService.class);traceEnd();}traceBeginAndSlog("IpConnectivityMetrics");mSystemServiceManager.startService(IpConnectivityMetrics.class);traceEnd();traceBeginAndSlog("NetworkWatchlistService");mSystemServiceManager.startService(NetworkWatchlistService.Lifecycle.class);traceEnd();traceBeginAndSlog("PinnerService");mSystemServiceManager.startService(PinnerService.class);traceEnd();traceBeginAndSlog("SignedConfigService");SignedConfigService.registerUpdateReceiver(mSystemContext);traceEnd();} catch (RuntimeException e) {Slog.e("System", "");Slog.e("System", " Failure starting core service", e);}// Before things start rolling, be sure we have decided whether// we are in safe mode.final boolean safeMode = wm.detectSafeMode();if (safeMode) {// If yes, immediately turn on the global setting for airplane mode.// Note that this does not send broadcasts at this stage because// subsystems are not yet up. We will send broadcasts later to ensure// all listeners have the chance to react with special handling.Settings.Global.putInt(context.getContentResolver(),Settings.Global.AIRPLANE_MODE_ON, 1);}StatusBarManagerService statusBar = null;INotificationManager notification = null;LocationManagerService location = null;CountryDetectorService countryDetector = null;ILockSettings lockSettings = null;MediaRouterService mediaRouter = null;// Bring up services needed for UI.if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {traceBeginAndSlog("StartInputMethodManagerLifecycle");if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) {mSystemServiceManager.startService(MultiClientInputMethodManagerService.Lifecycle.class);} else {mSystemServiceManager.startService(InputMethodManagerService.Lifecycle.class);}traceEnd();traceBeginAndSlog("StartAccessibilityManagerService");try {mSystemServiceManager.startService(ACCESSIBILITY_MANAGER_SERVICE_CLASS);} catch (Throwable e) {reportWtf("starting Accessibility Manager", e);}traceEnd();}traceBeginAndSlog("MakeDisplayReady");try {wm.displayReady();} catch (Throwable e) {reportWtf("making display ready", e);}traceEnd();if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {if (!"0".equals(SystemProperties.get("system_init.startmountservice"))) {traceBeginAndSlog("StartStorageManagerService");try {/ NotificationManagerService is dependant on StorageManagerService,* (for media / usb notifications) so we must start StorageManagerService first.*/mSystemServiceManager.startService(STORAGE_MANAGER_SERVICE_CLASS);storageManager = IStorageManager.Stub.asInterface(ServiceManager.getService("mount"));} catch (Throwable e) {reportWtf("starting StorageManagerService", e);}traceEnd();traceBeginAndSlog("StartStorageStatsService");try {mSystemServiceManager.startService(STORAGE_STATS_SERVICE_CLASS);} catch (Throwable e) {reportWtf("starting StorageStatsService", e);}traceEnd();}}// We start this here so that we update our configuration to set watch or television// as appropriate.traceBeginAndSlog("StartUiModeManager");mSystemServiceManager.startService(UiModeManagerService.class);traceEnd();if (!mOnlyCore) {traceBeginAndSlog("UpdatePackagesIfNeeded");try {Watchdog.getInstance().pauseWatchingCurrentThread("dexopt");mPackageManagerService.updatePackagesIfNeeded();} catch (Throwable e) {reportWtf("update packages", e);} finally {Watchdog.getInstance().resumeWatchingCurrentThread("dexopt");}traceEnd();}traceBeginAndSlog("PerformFstrimIfNeeded");try {mPackageManagerService.performFstrimIfNeeded();} catch (Throwable e) {reportWtf("performing fstrim", e);}traceEnd();if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {traceBeginAndSlog("StartLockSettingsService");try {mSystemServiceManager.startService(LOCK_SETTINGS_SERVICE_CLASS);lockSettings = ILockSettings.Stub.asInterface(ServiceManager.getService("lock_settings"));} catch (Throwable e) {reportWtf("starting LockSettingsService service", e);}traceEnd();final boolean hasPdb = !SystemProperties.get(PERSISTENT_DATA_BLOCK_PROP).equals("");final boolean hasGsi = SystemProperties.getInt(GSI_RUNNING_PROP, 0) > 0;if (hasPdb && !hasGsi) {traceBeginAndSlog("StartPersistentDataBlock");mSystemServiceManager.startService(PersistentDataBlockService.class);traceEnd();}traceBeginAndSlog("StartTestHarnessMode");mSystemServiceManager.startService(TestHarnessModeService.class);traceEnd();if (hasPdb || OemLockService.isHalPresent()) {// Implementation depends on pdb or the OemLock HALtraceBeginAndSlog("StartOemLockService");mSystemServiceManager.startService(OemLockService.class);traceEnd();}traceBeginAndSlog("StartDeviceIdleController");mSystemServiceManager.startService(DeviceIdleController.class);traceEnd();// Always start the Device Policy Manager, so that the API is compatible with// API8.traceBeginAndSlog("StartDevicePolicyManager");mSystemServiceManager.startService(DevicePolicyManagerService.Lifecycle.class);traceEnd();if (!isWatch) {traceBeginAndSlog("StartStatusBarManagerService");try {statusBar = new StatusBarManagerService(context, wm);ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);} catch (Throwable e) {reportWtf("starting StatusBarManagerService", e);}traceEnd();}startContentCaptureService(context);startAttentionService(context);startSystemCaptionsManagerService(context);// App prediction manager serviceif (deviceHasConfigString(context, R.string.config_defaultAppPredictionService)) {traceBeginAndSlog("StartAppPredictionService");mSystemServiceManager.startService(APP_PREDICTION_MANAGER_SERVICE_CLASS);traceEnd();} else {Slog.d(TAG, "AppPredictionService not defined by OEM");}// Content suggestions manager serviceif (deviceHasConfigString(context, R.string.config_defaultContentSuggestionsService)) {traceBeginAndSlog("StartContentSuggestionsService");mSystemServiceManager.startService(CONTENT_SUGGESTIONS_SERVICE_CLASS);traceEnd();} else {Slog.d(TAG, "ContentSuggestionsService not defined by OEM");}traceBeginAndSlog("InitNetworkStackClient");try {NetworkStackClient.getInstance().init();} catch (Throwable e) {reportWtf("initializing NetworkStackClient", e);}traceEnd();traceBeginAndSlog("StartNetworkManagementService");try {networkManagement = NetworkManagementService.create(context);ServiceManager.addService(Context.NETWORKMANAGEMENT_SERVICE, networkManagement);} catch (Throwable e) {reportWtf("starting NetworkManagement Service", e);}traceEnd();traceBeginAndSlog("StartIpSecService");try {ipSecService = IpSecService.create(context);ServiceManager.addService(Context.IPSEC_SERVICE, ipSecService);} catch (Throwable e) {reportWtf("starting IpSec Service", e);}traceEnd();traceBeginAndSlog("StartTextServicesManager");mSystemServiceManager.startService(TextServicesManagerService.Lifecycle.class);traceEnd();if (!disableSystemTextClassifier) {traceBeginAndSlog("StartTextClassificationManagerService");mSystemServiceManager.startService(TextClassificationManagerService.Lifecycle.class);traceEnd();}traceBeginAndSlog("StartNetworkScoreService");mSystemServiceManager.startService(NetworkScoreService.Lifecycle.class);traceEnd();traceBeginAndSlog("StartNetworkStatsService");try {networkStats = NetworkStatsService.create(context, networkManagement);ServiceManager.addService(Context.NETWORK_STATS_SERVICE, networkStats);} catch (Throwable e) {reportWtf("starting NetworkStats Service", e);}traceEnd();traceBeginAndSlog("StartNetworkPolicyManagerService");try {networkPolicy = new NetworkPolicyManagerService(context, mActivityManagerService,networkManagement);ServiceManager.addService(Context.NETWORK_POLICY_SERVICE, networkPolicy);} catch (Throwable e) {reportWtf("starting NetworkPolicy Service", e);}traceEnd();if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI)) {// Wifi Service must be started first for wifi-related services.traceBeginAndSlog("StartWifi");mSystemServiceManager.startService(WIFI_SERVICE_CLASS);traceEnd();traceBeginAndSlog("StartWifiScanning");mSystemServiceManager.startService("com.android.server.wifi.scanner.WifiScanningService");traceEnd();}if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI_RTT)) {traceBeginAndSlog("StartRttService");mSystemServiceManager.startService("com.android.server.wifi.rtt.RttService");traceEnd();}if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI_AWARE)) {traceBeginAndSlog("StartWifiAware");mSystemServiceManager.startService(WIFI_AWARE_SERVICE_CLASS);traceEnd();}if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI_DIRECT)) {traceBeginAndSlog("StartWifiP2P");mSystemServiceManager.startService(WIFI_P2P_SERVICE_CLASS);traceEnd();}if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LOWPAN)) {traceBeginAndSlog("StartLowpan");mSystemServiceManager.startService(LOWPAN_SERVICE_CLASS);traceEnd();}if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_ETHERNET) ||mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)) {traceBeginAndSlog("StartEthernet");mSystemServiceManager.startService(ETHERNET_SERVICE_CLASS);traceEnd();}traceBeginAndSlog("StartConnectivityService");try {connectivity = new ConnectivityService(context, networkManagement, networkStats, networkPolicy);ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity,/* allowIsolated= */ false,DUMP_FLAG_PRIORITY_HIGH | DUMP_FLAG_PRIORITY_NORMAL);networkPolicy.bindConnectivityManager(connectivity);} catch (Throwable e) {reportWtf("starting Connectivity Service", e);}traceEnd();traceBeginAndSlog("StartNsdService");try {serviceDiscovery = NsdService.create(context);ServiceManager.addService(Context.NSD_SERVICE, serviceDiscovery);} catch (Throwable e) {reportWtf("starting Service Discovery Service", e);}traceEnd();traceBeginAndSlog("StartSystemUpdateManagerService");try {ServiceManager.addService(Context.SYSTEM_UPDATE_SERVICE,new SystemUpdateManagerService(context));} catch (Throwable e) {reportWtf("starting SystemUpdateManagerService", e);}traceEnd();traceBeginAndSlog("StartUpdateLockService");try {ServiceManager.addService(Context.UPDATE_LOCK_SERVICE,new UpdateLockService(context));} catch (Throwable e) {reportWtf("starting UpdateLockService", e);}traceEnd();traceBeginAndSlog("StartNotificationManager");mSystemServiceManager.startService(NotificationManagerService.class);SystemNotificationChannels.removeDeprecated(context);SystemNotificationChannels.createAll(context);notification = INotificationManager.Stub.asInterface(ServiceManager.getService(Context.NOTIFICATION_SERVICE));traceEnd();traceBeginAndSlog("StartDeviceMonitor");mSystemServiceManager.startService(DeviceStorageMonitorService.class);traceEnd();traceBeginAndSlog("StartLocationManagerService");try {location = new LocationManagerService(context);ServiceManager.addService(Context.LOCATION_SERVICE, location);} catch (Throwable e) {reportWtf("starting Location Manager", e);}traceEnd();traceBeginAndSlog("StartCountryDetectorService");try {countryDetector = new CountryDetectorService(context);ServiceManager.addService(Context.COUNTRY_DETECTOR, countryDetector);} catch (Throwable e) {reportWtf("starting Country Detector", e);}traceEnd();final boolean useNewTimeServices = true;if (useNewTimeServices) {traceBeginAndSlog("StartTimeDetectorService");try {mSystemServiceManager.startService(TIME_DETECTOR_SERVICE_CLASS);} catch (Throwable e) {reportWtf("starting StartTimeDetectorService service", e);}traceEnd();}if (!isWatch) {traceBeginAndSlog("StartSearchManagerService");try {mSystemServiceManager.startService(SEARCH_MANAGER_SERVICE_CLASS);} catch (Throwable e) {reportWtf("starting Search Service", e);}traceEnd();}if (context.getResources().getBoolean(R.bool.config_enableWallpaperService)) {traceBeginAndSlog("StartWallpaperManagerService");mSystemServiceManager.startService(WALLPAPER_SERVICE_CLASS);traceEnd();} else {Slog.i(TAG, "Wallpaper service disabled by config");}traceBeginAndSlog("StartAudioService");if (!isArc) {mSystemServiceManager.startService(AudioService.Lifecycle.class);} else {String className = context.getResources().getString(R.string.config_deviceSpecificAudioService);try {mSystemServiceManager.startService(className + "$Lifecycle");} catch (Throwable e) {reportWtf("starting " + className, e);}}traceEnd();if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_BROADCAST_RADIO)) {traceBeginAndSlog("StartBroadcastRadioService");mSystemServiceManager.startService(BroadcastRadioService.class);traceEnd();}traceBeginAndSlog("StartDockObserver");mSystemServiceManager.startService(DockObserver.class);traceEnd();if (isWatch) {traceBeginAndSlog("StartThermalObserver");mSystemServiceManager.startService(THERMAL_OBSERVER_CLASS);traceEnd();}traceBeginAndSlog("StartWiredAccessoryManager");try {// Listen for wired headset changesinputManager.setWiredAccessoryCallbacks(new WiredAccessoryManager(context, inputManager));} catch (Throwable e) {reportWtf("starting WiredAccessoryManager", e);}traceEnd();if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_MIDI)) {// Start MIDI Manager servicetraceBeginAndSlog("StartMidiManager");mSystemServiceManager.startService(MIDI_SERVICE_CLASS);traceEnd();}// Start ADB Debugging ServicetraceBeginAndSlog("StartAdbService");try {mSystemServiceManager.startService(ADB_SERVICE_CLASS);} catch (Throwable e) {Slog.e(TAG, "Failure starting AdbService");}traceEnd();if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)|| mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_ACCESSORY)|| isEmulator) {// Manage USB host and device supporttraceBeginAndSlog("StartUsbService");mSystemServiceManager.startService(USB_SERVICE_CLASS);traceEnd();}if (!isWatch) {traceBeginAndSlog("StartSerialService");try {// Serial port supportserial = new SerialService(context);ServiceManager.addService(Context.SERIAL_SERVICE, serial);} catch (Throwable e) {Slog.e(TAG, "Failure starting SerialService", e);}traceEnd();}traceBeginAndSlog("StartHardwarePropertiesManagerService");try {hardwarePropertiesService = new HardwarePropertiesManagerService(context);ServiceManager.addService(Context.HARDWARE_PROPERTIES_SERVICE,hardwarePropertiesService);} catch (Throwable e) {Slog.e(TAG, "Failure starting HardwarePropertiesManagerService", e);}traceEnd();traceBeginAndSlog("StartTwilightService");mSystemServiceManager.startService(TwilightService.class);traceEnd();traceBeginAndSlog("StartColorDisplay");mSystemServiceManager.startService(ColorDisplayService.class);traceEnd();traceBeginAndSlog("StartJobScheduler");mSystemServiceManager.startService(JobSchedulerService.class);traceEnd();traceBeginAndSlog("StartSoundTrigger");mSystemServiceManager.startService(SoundTriggerService.class);traceEnd();traceBeginAndSlog("StartTrustManager");mSystemServiceManager.startService(TrustManagerService.class);traceEnd();if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_BACKUP)) {traceBeginAndSlog("StartBackupManager");mSystemServiceManager.startService(BACKUP_MANAGER_SERVICE_CLASS);traceEnd();}if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_APP_WIDGETS)|| context.getResources().getBoolean(R.bool.config_enableAppWidgetService)) {traceBeginAndSlog("StartAppWidgetService");mSystemServiceManager.startService(APPWIDGET_SERVICE_CLASS);traceEnd();}// Grants default permissions and defines rolestraceBeginAndSlog("StartRoleManagerService");mSystemServiceManager.startService(new RoleManagerService(mSystemContext, new LegacyRoleResolutionPolicy(mSystemContext)));traceEnd();// We need to always start this service, regardless of whether the// FEATURE_VOICE_RECOGNIZERS feature is set, because it needs to take care// of initializing various settings.  It will internally modify its behavior// based on that feature.traceBeginAndSlog("StartVoiceRecognitionManager");mSystemServiceManager.startService(VOICE_RECOGNITION_MANAGER_SERVICE_CLASS);traceEnd();if (GestureLauncherService.isGestureLauncherEnabled(context.getResources())) {traceBeginAndSlog("StartGestureLauncher");mSystemServiceManager.startService(GestureLauncherService.class);traceEnd();}traceBeginAndSlog("StartSensorNotification");mSystemServiceManager.startService(SensorNotificationService.class);traceEnd();traceBeginAndSlog("StartContextHubSystemService");mSystemServiceManager.startService(ContextHubSystemService.class);traceEnd();traceBeginAndSlog("StartDiskStatsService");try {ServiceManager.addService("diskstats", new DiskStatsService(context));} catch (Throwable e) {reportWtf("starting DiskStats Service", e);}traceEnd();traceBeginAndSlog("RuntimeService");try {ServiceManager.addService("runtime", new RuntimeService(context));} catch (Throwable e) {reportWtf("starting RuntimeService", e);}traceEnd();// timezone.RulesManagerService will prevent a device starting up if the chain of trust// required for safe time zone updates might be broken. RuleManagerService cannot do// this check when mOnlyCore == true, so we don't enable the service in this case.// This service requires that JobSchedulerService is already started when it starts.final boolean startRulesManagerService =!mOnlyCore && context.getResources().getBoolean(R.bool.config_enableUpdateableTimeZoneRules);if (startRulesManagerService) {traceBeginAndSlog("StartTimeZoneRulesManagerService");mSystemServiceManager.startService(TIME_ZONE_RULES_MANAGER_SERVICE_CLASS);traceEnd();}if (!isWatch && !disableNetworkTime) {traceBeginAndSlog("StartNetworkTimeUpdateService");try {if (useNewTimeServices) {networkTimeUpdater = new NewNetworkTimeUpdateService(context);} else {networkTimeUpdater = new OldNetworkTimeUpdateService(context);}Slog.d(TAG, "Using networkTimeUpdater class=" + networkTimeUpdater.getClass());ServiceManager.addService("network_time_update_service", networkTimeUpdater);} catch (Throwable e) {reportWtf("starting NetworkTimeUpdate service", e);}traceEnd();}traceBeginAndSlog("CertBlacklister");try {CertBlacklister blacklister = new CertBlacklister(context);} catch (Throwable e) {reportWtf("starting CertBlacklister", e);}traceEnd();if (EmergencyAffordanceManager.ENABLED) {// EmergencyMode servicetraceBeginAndSlog("StartEmergencyAffordanceService");mSystemServiceManager.startService(EmergencyAffordanceService.class);traceEnd();}// Dreams (interactive idle-time views, a/k/a screen savers, and doze mode)traceBeginAndSlog("StartDreamManager");mSystemServiceManager.startService(DreamManagerService.class);traceEnd();traceBeginAndSlog("AddGraphicsStatsService");ServiceManager.addService(GraphicsStatsService.GRAPHICS_STATS_SERVICE,new GraphicsStatsService(context));traceEnd();if (CoverageService.ENABLED) {traceBeginAndSlog("AddCoverageService");ServiceManager.addService(CoverageService.COVERAGE_SERVICE, new CoverageService());traceEnd();}if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PRINTING)) {traceBeginAndSlog("StartPrintManager");mSystemServiceManager.startService(PRINT_MANAGER_SERVICE_CLASS);traceEnd();}if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_COMPANION_DEVICE_SETUP)) {traceBeginAndSlog("StartCompanionDeviceManager");mSystemServiceManager.startService(COMPANION_DEVICE_MANAGER_SERVICE_CLASS);traceEnd();}traceBeginAndSlog("StartRestrictionManager");mSystemServiceManager.startService(RestrictionsManagerService.class);traceEnd();traceBeginAndSlog("StartMediaSessionService");mSystemServiceManager.startService(MediaSessionService.class);traceEnd();if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_HDMI_CEC)) {traceBeginAndSlog("StartHdmiControlService");mSystemServiceManager.startService(HdmiControlService.class);traceEnd();}if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LIVE_TV)|| mPackageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {traceBeginAndSlog("StartTvInputManager");mSystemServiceManager.startService(TvInputManagerService.class);traceEnd();}if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) {traceBeginAndSlog("StartMediaResourceMonitor");mSystemServiceManager.startService(MediaResourceMonitorService.class);traceEnd();}if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {traceBeginAndSlog("StartTvRemoteService");mSystemServiceManager.startService(TvRemoteService.class);traceEnd();}traceBeginAndSlog("StartMediaRouterService");try {mediaRouter = new MediaRouterService(context);ServiceManager.addService(Context.MEDIA_ROUTER_SERVICE, mediaRouter);} catch (Throwable e) {reportWtf("starting MediaRouterService", e);}traceEnd();final boolean hasFeatureFace= mPackageManager.hasSystemFeature(PackageManager.FEATURE_FACE);final boolean hasFeatureIris= mPackageManager.hasSystemFeature(PackageManager.FEATURE_IRIS);final boolean hasFeatureFingerprint= mPackageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT);if (hasFeatureFace) {traceBeginAndSlog("StartFaceSensor");mSystemServiceManager.startService(FaceService.class);traceEnd();}if (hasFeatureIris) {traceBeginAndSlog("StartIrisSensor");mSystemServiceManager.startService(IrisService.class);traceEnd();}if (hasFeatureFingerprint) {traceBeginAndSlog("StartFingerprintSensor");mSystemServiceManager.startService(FingerprintService.class);traceEnd();}if (hasFeatureFace || hasFeatureIris || hasFeatureFingerprint) {// Start this service after all biometric services.traceBeginAndSlog("StartBiometricService");mSystemServiceManager.startService(BiometricService.class);traceEnd();}traceBeginAndSlog("StartBackgroundDexOptService");try {BackgroundDexOptService.schedule(context);} catch (Throwable e) {reportWtf("starting StartBackgroundDexOptService", e);}traceEnd();if (!isWatch) {// We don't run this on watches as there are no plans to use the data logged// on watch devices.traceBeginAndSlog("StartDynamicCodeLoggingService");try {DynamicCodeLoggingService.schedule(context);} catch (Throwable e) {reportWtf("starting DynamicCodeLoggingService", e);}traceEnd();}if (!isWatch) {traceBeginAndSlog("StartPruneInstantAppsJobService");try {PruneInstantAppsJobService.schedule(context);} catch (Throwable e) {reportWtf("StartPruneInstantAppsJobService", e);}traceEnd();}// LauncherAppsService uses ShortcutService.traceBeginAndSlog("StartShortcutServiceLifecycle");mSystemServiceManager.startService(ShortcutService.Lifecycle.class);traceEnd();traceBeginAndSlog("StartLauncherAppsService");mSystemServiceManager.startService(LauncherAppsService.class);traceEnd();traceBeginAndSlog("StartCrossProfileAppsService");mSystemServiceManager.startService(CrossProfileAppsService.class);traceEnd();}if (!isWatch) {traceBeginAndSlog("StartMediaProjectionManager");mSystemServiceManager.startService(MediaProjectionManagerService.class);traceEnd();}if (isWatch) {// Must be started before services that depend it, e.g. WearConnectivityServicetraceBeginAndSlog("StartWearPowerService");mSystemServiceManager.startService(WEAR_POWER_SERVICE_CLASS);traceEnd();traceBeginAndSlog("StartWearConnectivityService");mSystemServiceManager.startService(WEAR_CONNECTIVITY_SERVICE_CLASS);traceEnd();traceBeginAndSlog("StartWearDisplayService");mSystemServiceManager.startService(WEAR_DISPLAY_SERVICE_CLASS);traceEnd();traceBeginAndSlog("StartWearTimeService");mSystemServiceManager.startService(WEAR_TIME_SERVICE_CLASS);traceEnd();if (enableLeftyService) {traceBeginAndSlog("StartWearLeftyService");mSystemServiceManager.startService(WEAR_LEFTY_SERVICE_CLASS);traceEnd();}traceBeginAndSlog("StartWearGlobalActionsService");mSystemServiceManager.startService(WEAR_GLOBAL_ACTIONS_SERVICE_CLASS);traceEnd();}if (!disableSlices) {traceBeginAndSlog("StartSliceManagerService");mSystemServiceManager.startService(SLICE_MANAGER_SERVICE_CLASS);traceEnd();}if (!disableCameraService) {traceBeginAndSlog("StartCameraServiceProxy");mSystemServiceManager.startService(CameraServiceProxy.class);traceEnd();}if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_EMBEDDED)) {traceBeginAndSlog("StartIoTSystemService");mSystemServiceManager.startService(IOT_SERVICE_CLASS);traceEnd();}// Statsd helpertraceBeginAndSlog("StartStatsCompanionService");mSystemServiceManager.startService(StatsCompanionService.Lifecycle.class);traceEnd();// Incidentd and dumpstated helpertraceBeginAndSlog("StartIncidentCompanionService");mSystemServiceManager.startService(IncidentCompanionService.class);traceEnd();if (safeMode) {mActivityManagerService.enterSafeMode();}// MMS service brokertraceBeginAndSlog("StartMmsService");mmsService = mSystemServiceManager.startService(MmsServiceBroker.class);traceEnd();if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOFILL)) {traceBeginAndSlog("StartAutoFillService");mSystemServiceManager.startService(AUTO_FILL_MANAGER_SERVICE_CLASS);traceEnd();}// NOTE: ClipboardService depends on ContentCapture and AutofilltraceBeginAndSlog("StartClipboardService");mSystemServiceManager.startService(ClipboardService.class);traceEnd();traceBeginAndSlog("AppServiceManager");mSystemServiceManager.startService(AppBindingService.Lifecycle.class);traceEnd();// It is now time to start up the app processes...traceBeginAndSlog("MakeVibratorServiceReady");try {vibrator.systemReady();} catch (Throwable e) {reportWtf("making Vibrator Service ready", e);}traceEnd();traceBeginAndSlog("MakeLockSettingsServiceReady");if (lockSettings != null) {try {lockSettings.systemReady();} catch (Throwable e) {reportWtf("making Lock Settings Service ready", e);}}traceEnd();// Needed by DevicePolicyManager for initializationtraceBeginAndSlog("StartBootPhaseLockSettingsReady");mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);traceEnd();traceBeginAndSlog("StartBootPhaseSystemServicesReady");mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);traceEnd();traceBeginAndSlog("MakeWindowManagerServiceReady");try {wm.systemReady();} catch (Throwable e) {reportWtf("making Window Manager Service ready", e);}traceEnd();if (safeMode) {mActivityManagerService.showSafeModeOverlay();}// Update the configuration for this context by hand, because we're going// to start using it before the config change done in wm.systemReady() will// propagate to it.final Configuration config = wm.computeNewConfiguration(DEFAULT_DISPLAY);DisplayMetrics metrics = new DisplayMetrics();WindowManager w = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);w.getDefaultDisplay().getMetrics(metrics);context.getResources().updateConfiguration(config, metrics);// The system context's theme may be configuration-dependent.final Theme systemTheme = context.getTheme();if (systemTheme.getChangingConfigurations() != 0) {systemTheme.rebase();}traceBeginAndSlog("MakePowerManagerServiceReady");try {// TODO: use boot phasemPowerManagerService.systemReady(mActivityManagerService.getAppOpsService());} catch (Throwable e) {reportWtf("making Power Manager Service ready", e);}traceEnd();// Permission policy servicetraceBeginAndSlog("StartPermissionPolicyService");mSystemServiceManager.startService(PermissionPolicyService.class);traceEnd();traceBeginAndSlog("MakePackageManagerServiceReady");mPackageManagerService.systemReady();traceEnd();traceBeginAndSlog("MakeDisplayManagerServiceReady");try {// TODO: use boot phase and communicate these flags some other waymDisplayManagerService.systemReady(safeMode, mOnlyCore);} catch (Throwable e) {reportWtf("making Display Manager Service ready", e);}traceEnd();mSystemServiceManager.setSafeMode(safeMode);// Start device specific servicestraceBeginAndSlog("StartDeviceSpecificServices");final String[] classes = mSystemContext.getResources().getStringArray(R.array.config_deviceSpecificSystemServices);for (final String className : classes) {traceBeginAndSlog("StartDeviceSpecificServices " + className);try {mSystemServiceManager.startService(className);} catch (Throwable e) {reportWtf("starting " + className, e);}traceEnd();}traceEnd();traceBeginAndSlog("StartBootPhaseDeviceSpecificServicesReady");mSystemServiceManager.startBootPhase(SystemService.PHASE_DEVICE_SPECIFIC_SERVICES_READY);traceEnd();// These are needed to propagate to the runnable below.final NetworkManagementService networkManagementF = networkManagement;final NetworkStatsService networkStatsF = networkStats;final NetworkPolicyManagerService networkPolicyF = networkPolicy;final ConnectivityService connectivityF = connectivity;final LocationManagerService locationF = location;final CountryDetectorService countryDetectorF = countryDetector;final NetworkTimeUpdateService networkTimeUpdaterF = networkTimeUpdater;final InputManagerService inputManagerF = inputManager;final TelephonyRegistry telephonyRegistryF = telephonyRegistry;final MediaRouterService mediaRouterF = mediaRouter;final MmsServiceBroker mmsServiceF = mmsService;final IpSecService ipSecServiceF = ipSecService;final WindowManagerService windowManagerF = wm;// We now tell the activity manager it is okay to run third party// code.  It will call back into us once it has gotten to the state// where third party code can really run (but before it has actually// started launching the initial applications), for us to complete our// initialization.mActivityManagerService.systemReady(() -> {Slog.i(TAG, "Making services ready");traceBeginAndSlog("StartActivityManagerReadyPhase");mSystemServiceManager.startBootPhase(SystemService.PHASE_ACTIVITY_MANAGER_READY);traceEnd();traceBeginAndSlog("StartObservingNativeCrashes");try {mActivityManagerService.startObservingNativeCrashes();} catch (Throwable e) {reportWtf("observing native crashes", e);}traceEnd();// No dependency on Webview preparation in system server. But this should// be completed before allowing 3rd partyfinal String WEBVIEW_PREPARATION = "WebViewFactoryPreparation";Future<?> webviewPrep = null;if (!mOnlyCore && mWebViewUpdateService != null) {webviewPrep = SystemServerInitThreadPool.get().submit(() -> {Slog.i(TAG, WEBVIEW_PREPARATION);TimingsTraceLog traceLog = new TimingsTraceLog(SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);traceLog.traceBegin(WEBVIEW_PREPARATION);ConcurrentUtils.waitForFutureNoInterrupt(mZygotePreload, "Zygote preload");mZygotePreload = null;mWebViewUpdateService.prepareWebViewInSystemServer();traceLog.traceEnd();}, WEBVIEW_PREPARATION);}if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {traceBeginAndSlog("StartCarServiceHelperService");mSystemServiceManager.startService(CAR_SERVICE_HELPER_SERVICE_CLASS);traceEnd();}traceBeginAndSlog("StartSystemUI");try {startSystemUi(context, windowManagerF);} catch (Throwable e) {reportWtf("starting System UI", e);}traceEnd();// Enable airplane mode in safe mode. setAirplaneMode() cannot be called// earlier as it sends broadcasts to other services.// TODO: This may actually be too late if radio firmware already started leaking// RF before the respective services start. However, fixing this requires changes// to radio firmware and interfaces.if (safeMode) {traceBeginAndSlog("EnableAirplaneModeInSafeMode");try {connectivityF.setAirplaneMode(true);} catch (Throwable e) {reportWtf("enabling Airplane Mode during Safe Mode bootup", e);}traceEnd();}traceBeginAndSlog("MakeNetworkManagementServiceReady");try {if (networkManagementF != null) {networkManagementF.systemReady();}} catch (Throwable e) {reportWtf("making Network Managment Service ready", e);}CountDownLatch networkPolicyInitReadySignal = null;if (networkPolicyF != null) {networkPolicyInitReadySignal = networkPolicyF.networkScoreAndNetworkManagementServiceReady();}traceEnd();traceBeginAndSlog("MakeIpSecServiceReady");try {if (ipSecServiceF != null) {ipSecServiceF.systemReady();}} catch (Throwable e) {reportWtf("making IpSec Service ready", e);}traceEnd();traceBeginAndSlog("MakeNetworkStatsServiceReady");try {if (networkStatsF != null) {networkStatsF.systemReady();}} catch (Throwable e) {reportWtf("making Network Stats Service ready", e);}traceEnd();traceBeginAndSlog("MakeConnectivityServiceReady");try {if (connectivityF != null) {connectivityF.systemReady();}} catch (Throwable e) {reportWtf("making Connectivity Service ready", e);}traceEnd();traceBeginAndSlog("MakeNetworkPolicyServiceReady");try {if (networkPolicyF != null) {networkPolicyF.systemReady(networkPolicyInitReadySignal);}} catch (Throwable e) {reportWtf("making Network Policy Service ready", e);}traceEnd();// Wait for all packages to be preparedmPackageManagerService.waitForAppDataPrepared();// It is now okay to let the various system services start their// third party code...traceBeginAndSlog("PhaseThirdPartyAppsCanStart");// confirm webview completion before starting 3rd partyif (webviewPrep != null) {ConcurrentUtils.waitForFutureNoInterrupt(webviewPrep, WEBVIEW_PREPARATION);}mSystemServiceManager.startBootPhase(SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);traceEnd();traceBeginAndSlog("StartNetworkStack");try {// Note : the network stack is creating on-demand objects that need to send// broadcasts, which means it currently depends on being started after// ActivityManagerService.mSystemReady and ActivityManagerService.mProcessesReady// are set to true. Be careful if moving this to a different place in the// startup sequence.NetworkStackClient.getInstance().start(context);} catch (Throwable e) {reportWtf("starting Network Stack", e);}traceEnd();traceBeginAndSlog("MakeLocationServiceReady");try {if (locationF != null) {locationF.systemRunning();}} catch (Throwable e) {reportWtf("Notifying Location Service running", e);}traceEnd();traceBeginAndSlog("MakeCountryDetectionServiceReady");try {if (countryDetectorF != null) {countryDetectorF.systemRunning();}} catch (Throwable e) {reportWtf("Notifying CountryDetectorService running", e);}traceEnd();traceBeginAndSlog("MakeNetworkTimeUpdateReady");try {if (networkTimeUpdaterF != null) {networkTimeUpdaterF.systemRunning();}} catch (Throwable e) {reportWtf("Notifying NetworkTimeService running", e);}traceEnd();traceBeginAndSlog("MakeInputManagerServiceReady");try {// TODO(BT) Pass parameter to input managerif (inputManagerF != null) {inputManagerF.systemRunning();}} catch (Throwable e) {reportWtf("Notifying InputManagerService running", e);}traceEnd();traceBeginAndSlog("MakeTelephonyRegistryReady");try {if (telephonyRegistryF != null) {telephonyRegistryF.systemRunning();}} catch (Throwable e) {reportWtf("Notifying TelephonyRegistry running", e);}traceEnd();traceBeginAndSlog("MakeMediaRouterServiceReady");try {if (mediaRouterF != null) {mediaRouterF.systemRunning();}} catch (Throwable e) {reportWtf("Notifying MediaRouterService running", e);}traceEnd();traceBeginAndSlog("MakeMmsServiceReady");try {if (mmsServiceF != null) {mmsServiceF.systemRunning();}} catch (Throwable e) {reportWtf("Notifying MmsService running", e);}traceEnd();traceBeginAndSlog("IncidentDaemonReady");try {// TODO: Switch from checkService to getService once it's always// in the build and should reliably be there.final IIncidentManager incident = IIncidentManager.Stub.asInterface(ServiceManager.getService(Context.INCIDENT_SERVICE));if (incident != null) {incident.systemRunning();}} catch (Throwable e) {reportWtf("Notifying incident daemon running", e);}traceEnd();}, BOOT_TIMINGS_TRACE_LOG);}
  • startService
    1、KeyChainSystemService
    2、TelecomLoaderService
    3、AccountManagerService
    4、ContentService
    5、DropBoxManagerService
    6、AlarmManagerService
    7、VrManagerService
    8、BluetoothService
    9、IpConnectivityMetrics
    10、NetworkWatchlistService
    11、PinnerService
    12、InputMethodManagerService
    13、AccessibilityManagerService
    14、StorageManagerService
    15、StorageStatsService
    16、UiModeManagerService
    17、LockSettingsService
    18、PersistentDataBlockService
    19、TestHarnessModeService
    20、OemLockService
    21、DeviceIdleController
    22、DevicePolicyManagerService
    23、AppPredictionManagerService
    24、ContentSuggestionsManagerService
    25、TextServicesManagerService
    26、TextClassificationManagerService
    27、NetworkScoreService
    28、WifiService
    29、WifiScanningService
    30、RttService
    31、WifiAwareService
    32、WifiP2pService
    33、LowpanService
    34、EthernetService
    35、NotificationManagerService
    36、DeviceStorageMonitorService
    37、TimeDetectorService
    38、SearchManagerService
    39、WallpaperManagerService
    40、AudioService
    41、BroadcastRadioService
    42、DockObserver
    43、ThermalObserver
    44、MidiService
    45、AdbService
    46、UsbService
    47、TwilightService
    48、ColorDisplayService
    49、JobSchedulerService
    50、SoundTriggerService
    51、TrustManagerService
    52、BackupManagerService
    53、AppWidgetService
    54、RoleManagerService
    55、VoiceInteractionManagerService
    56、GestureLauncherService
    57、SensorNotificationService
    58、ContextHubSystemService
    59、EmergencyAffordanceService
    60、DreamManagerService
    61、PrintManagerService
    62、CompanionDeviceManagerService
    63、RestrictionsManagerService
    64、MediaSessionService
    65、HdmiControlService
    66、TvInputManagerService
    67、MediaResourceMonitorService
    68、TvRemoteService
    69、FaceService
    70、IrisService
    71、FingerprintService
    72、BiometricService
    73、ShortcutService
    74、LauncherAppsService
    75、CrossProfileAppsService
    76、MediaProjectionManagerService
    77、WearPowerService
    78、WearConnectivityService
    79、WearDisplayService
    80、WearTimeService
    81、WearLeftyService
    82、GlobalActionsService
    83、SliceManagerService
    84、CameraServiceProxy
    85、IoTSystemService
    86、StatsCompanionService
    87、IncidentCompanionService
    88、MmsServiceBroker
    89、AutofillManagerService
    90、ClipboardService
    91、 AppBindingService
    92、PermissionPolicyService
    93、CarServiceHelperService

  • addService
    1、KeyAttestationApplicationIdProviderService
    2、SchedulingPolicyService
    3、TelephonyRegistry
    4、VibratorService
    5、DynamicSystemService
    6、ConsumerIrService
    7、StatusBarManagerService
    8、NetworkManagementService
    9、IpSecService
    10、NetworkStatsService
    11、NetworkPolicyManagerService
    12、ConnectivityService
    13、NsdService
    14、SystemUpdateManagerService
    15、UpdateLockService
    16、LocationManagerService
    17、CountryDetectorService
    18、SerialService
    19、HardwarePropertiesManagerService
    20、DiskStatsService
    21、RuntimeService
    22、RulesManagerService
    23、NewNetworkTimeUpdateService
    24、GraphicsStatsService
    25、CoverageService
    26、MediaRouterService

四、系统服务启动

在SystemServer源码里面我们发现启动服务的时候,调用了SystemServiceManager的startService方法,也有直接调用ServiceManager的addService方法,其实SystemServiceManager的startService方法最终还是调用ServiceManager的addService方法,添加系统服务的。我们以ActivityTaskManagerService为例,来看一下整个添加系统服务的大致流程。

4.1、SystemServiceManager

android framework-SystemServer进程
SystemServiceManager 类用于创建、启动各种系统服务,并且这些系统服务必须是 com.android.server.SystemService 的子类
android framework-SystemServer进程
在SystemServiceManager的startService方法里面,首先通过反射,创建系统服务的对象,最后调用系统服务的onStart()方法。

4.1.1、ActivityTaskManagerService(ATMS)

android framework-SystemServer进程

路径:
android-10.0.0_r41\\frameworks\\base\\services\\core\\java\\com\\android\\server\\SystemServiceManager.java
android-10.0.0_r41\\frameworks\\base\\services\\core\\java\\com\\android\\server\\wm\\ActivityTaskManagerService.java
android-10.0.0_r41\\frameworks\\base\\services\\core\\java\\com\\android\\server\\SystemService.java
android-10.0.0_r41\\frameworks\\base\\core\\java\\android\\os\\ServiceManager.java

  • SystemServer#startBootstrapServices
 ActivityTaskManagerService atm = mSystemServiceManager.startService(ActivityTaskManagerService.Lifecycle.class).getService();
  • ActivityTaskManagerService.Lifecycle#onStart
@Overridepublic void onStart() {publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);mService.start();}
  • SystemService#publishBinderService
 * Publish the service so it is accessible to other services and apps.** @param name the name of the new service* @param service the service object*/protected final void publishBinderService(String name, IBinder service) {publishBinderService(name, service, false);}/* Publish the service so it is accessible to other services and apps. @param name the name of the new service* @param service the service object* @param allowIsolated set to true to allow isolated sandboxed processes* to access this service*/protected final void publishBinderService(String name, IBinder service,boolean allowIsolated) {publishBinderService(name, service, allowIsolated, DUMP_FLAG_PRIORITY_DEFAULT);}/* Publish the service so it is accessible to other services and apps. @param name the name of the new service* @param service the service object* @param allowIsolated set to true to allow isolated sandboxed processes* to access this service* @param dumpPriority supported dump priority levels as a bitmask*/protected final void publishBinderService(String name, IBinder service,boolean allowIsolated, int dumpPriority) {ServiceManager.addService(name, service, allowIsolated, dumpPriority);}

最终还是调用的ServiceManager的addService方法来添加系统服务。

五、系统服务客户端调用

android framework-SystemServer进程

涉及源码路径:
android-10.0.0_r41\\frameworks\\base\\core\\java\\android\\content\\Context.java
android-10.0.0_r41\\frameworks\\base\\core\\java\\android\\app\\ContextImpl.java
android-10.0.0_r41\\frameworks\\base\\core\\java\\android\\app\\SystemServiceRegistry.java

5.1、添加系统服务

static {//CHECKSTYLE:OFF IndentationCheckregisterService(Context.ACCESSIBILITY_SERVICE, AccessibilityManager.class,new CachedServiceFetcher<AccessibilityManager>() {@Overridepublic AccessibilityManager createService(ContextImpl ctx) {return AccessibilityManager.getInstance(ctx);}});registerService(Context.CAPTIONING_SERVICE, CaptioningManager.class,new CachedServiceFetcher<CaptioningManager>() {@Overridepublic CaptioningManager createService(ContextImpl ctx) {return new CaptioningManager(ctx);}});registerService(Context.ACCOUNT_SERVICE, AccountManager.class,new CachedServiceFetcher<AccountManager>() {@Overridepublic AccountManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.ACCOUNT_SERVICE);IAccountManager service = IAccountManager.Stub.asInterface(b);return new AccountManager(ctx, service);}});registerService(Context.ACTIVITY_SERVICE, ActivityManager.class,new CachedServiceFetcher<ActivityManager>() {@Overridepublic ActivityManager createService(ContextImpl ctx) {return new ActivityManager(ctx.getOuterContext(), ctx.mMainThread.getHandler());}});registerService(Context.ACTIVITY_TASK_SERVICE, ActivityTaskManager.class,new CachedServiceFetcher<ActivityTaskManager>() {@Overridepublic ActivityTaskManager createService(ContextImpl ctx) {return new ActivityTaskManager(ctx.getOuterContext(), ctx.mMainThread.getHandler());}});registerService(Context.URI_GRANTS_SERVICE, UriGrantsManager.class,new CachedServiceFetcher<UriGrantsManager>() {@Overridepublic UriGrantsManager createService(ContextImpl ctx) {return new UriGrantsManager(ctx.getOuterContext(), ctx.mMainThread.getHandler());}});registerService(Context.ALARM_SERVICE, AlarmManager.class,new CachedServiceFetcher<AlarmManager>() {@Overridepublic AlarmManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.ALARM_SERVICE);IAlarmManager service = IAlarmManager.Stub.asInterface(b);return new AlarmManager(service, ctx);}});registerService(Context.AUDIO_SERVICE, AudioManager.class,new CachedServiceFetcher<AudioManager>() {@Overridepublic AudioManager createService(ContextImpl ctx) {return new AudioManager(ctx);}});registerService(Context.MEDIA_ROUTER_SERVICE, MediaRouter.class,new CachedServiceFetcher<MediaRouter>() {@Overridepublic MediaRouter createService(ContextImpl ctx) {return new MediaRouter(ctx);}});registerService(Context.BLUETOOTH_SERVICE, BluetoothManager.class,new CachedServiceFetcher<BluetoothManager>() {@Overridepublic BluetoothManager createService(ContextImpl ctx) {return new BluetoothManager(ctx);}});registerService(Context.HDMI_CONTROL_SERVICE, HdmiControlManager.class,new StaticServiceFetcher<HdmiControlManager>() {@Overridepublic HdmiControlManager createService() throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.HDMI_CONTROL_SERVICE);return new HdmiControlManager(IHdmiControlService.Stub.asInterface(b));}});registerService(Context.TEXT_CLASSIFICATION_SERVICE, TextClassificationManager.class,new CachedServiceFetcher<TextClassificationManager>() {@Overridepublic TextClassificationManager createService(ContextImpl ctx) {return new TextClassificationManager(ctx);}});registerService(Context.CLIPBOARD_SERVICE, ClipboardManager.class,new CachedServiceFetcher<ClipboardManager>() {@Overridepublic ClipboardManager createService(ContextImpl ctx) throws ServiceNotFoundException {return new ClipboardManager(ctx.getOuterContext(),ctx.mMainThread.getHandler());}});// The clipboard service moved to a new package.  If someone asks for the old// interface by class then we want to redirect over to the new interface instead// (which extends it).SYSTEM_SERVICE_NAMES.put(android.text.ClipboardManager.class, Context.CLIPBOARD_SERVICE);registerService(Context.CONNECTIVITY_SERVICE, ConnectivityManager.class,new StaticApplicationContextServiceFetcher<ConnectivityManager>() {@Overridepublic ConnectivityManager createService(Context context) throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.CONNECTIVITY_SERVICE);IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);return new ConnectivityManager(context, service);}});registerService(Context.NETD_SERVICE, IBinder.class, new StaticServiceFetcher<IBinder>() {@Overridepublic IBinder createService() throws ServiceNotFoundException {return ServiceManager.getServiceOrThrow(Context.NETD_SERVICE);}});registerService(Context.IPSEC_SERVICE, IpSecManager.class,new CachedServiceFetcher<IpSecManager>() {@Overridepublic IpSecManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder b = ServiceManager.getService(Context.IPSEC_SERVICE);IIpSecService service = IIpSecService.Stub.asInterface(b);return new IpSecManager(ctx, service);}});registerService(Context.TEST_NETWORK_SERVICE,TestNetworkManager.class,new StaticApplicationContextServiceFetcher<TestNetworkManager>() {@Overridepublic TestNetworkManager createService(Context context)throws ServiceNotFoundException {IBinder csBinder =ServiceManager.getServiceOrThrow(Context.CONNECTIVITY_SERVICE);IConnectivityManager csMgr =IConnectivityManager.Stub.asInterface(csBinder);final IBinder tnBinder;try {tnBinder = csMgr.startOrGetTestNetworkService();} catch (RemoteException e) {throw new ServiceNotFoundException(Context.TEST_NETWORK_SERVICE);}ITestNetworkManager tnMgr = ITestNetworkManager.Stub.asInterface(tnBinder);return new TestNetworkManager(tnMgr);}});registerService(Context.COUNTRY_DETECTOR, CountryDetector.class,new StaticServiceFetcher<CountryDetector>() {@Overridepublic CountryDetector createService() throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.COUNTRY_DETECTOR);return new CountryDetector(ICountryDetector.Stub.asInterface(b));}});registerService(Context.DEVICE_POLICY_SERVICE, DevicePolicyManager.class,new CachedServiceFetcher<DevicePolicyManager>() {@Overridepublic DevicePolicyManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.DEVICE_POLICY_SERVICE);return new DevicePolicyManager(ctx, IDevicePolicyManager.Stub.asInterface(b));}});registerService(Context.DOWNLOAD_SERVICE, DownloadManager.class,new CachedServiceFetcher<DownloadManager>() {@Overridepublic DownloadManager createService(ContextImpl ctx) {return new DownloadManager(ctx);}});registerService(Context.BATTERY_SERVICE, BatteryManager.class,new CachedServiceFetcher<BatteryManager>() {@Overridepublic BatteryManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBatteryStats stats = IBatteryStats.Stub.asInterface(ServiceManager.getServiceOrThrow(BatteryStats.SERVICE_NAME));IBatteryPropertiesRegistrar registrar = IBatteryPropertiesRegistrar.Stub.asInterface(ServiceManager.getServiceOrThrow("batteryproperties"));return new BatteryManager(ctx, stats, registrar);}});registerService(Context.NFC_SERVICE, NfcManager.class,new CachedServiceFetcher<NfcManager>() {@Overridepublic NfcManager createService(ContextImpl ctx) {return new NfcManager(ctx);}});registerService(Context.DROPBOX_SERVICE, DropBoxManager.class,new CachedServiceFetcher<DropBoxManager>() {@Overridepublic DropBoxManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.DROPBOX_SERVICE);IDropBoxManagerService service = IDropBoxManagerService.Stub.asInterface(b);return new DropBoxManager(ctx, service);}});registerService(Context.INPUT_SERVICE, InputManager.class,new StaticServiceFetcher<InputManager>() {@Overridepublic InputManager createService() {return InputManager.getInstance();}});registerService(Context.DISPLAY_SERVICE, DisplayManager.class,new CachedServiceFetcher<DisplayManager>() {@Overridepublic DisplayManager createService(ContextImpl ctx) {return new DisplayManager(ctx.getOuterContext());}});registerService(Context.COLOR_DISPLAY_SERVICE, ColorDisplayManager.class,new CachedServiceFetcher<ColorDisplayManager>() {@Overridepublic ColorDisplayManager createService(ContextImpl ctx) {return new ColorDisplayManager();}});// InputMethodManager has its own cache strategy based on display id to support apps that// still assume InputMethodManager is a per-process singleton and it's safe to directly// access internal fields via reflection.  Hence directly use ServiceFetcher instead of// StaticServiceFetcher/CachedServiceFetcher.registerService(Context.INPUT_METHOD_SERVICE, InputMethodManager.class,new ServiceFetcher<InputMethodManager>() {@Overridepublic InputMethodManager getService(ContextImpl ctx) {return InputMethodManager.forContext(ctx.getOuterContext());}});registerService(Context.TEXT_SERVICES_MANAGER_SERVICE, TextServicesManager.class,new CachedServiceFetcher<TextServicesManager>() {@Overridepublic TextServicesManager createService(ContextImpl ctx)throws ServiceNotFoundException {return TextServicesManager.createInstance(ctx);}});registerService(Context.KEYGUARD_SERVICE, KeyguardManager.class,new CachedServiceFetcher<KeyguardManager>() {@Overridepublic KeyguardManager createService(ContextImpl ctx) throws ServiceNotFoundException {return new KeyguardManager(ctx);}});registerService(Context.LAYOUT_INFLATER_SERVICE, LayoutInflater.class,new CachedServiceFetcher<LayoutInflater>() {@Overridepublic LayoutInflater createService(ContextImpl ctx) {return new PhoneLayoutInflater(ctx.getOuterContext());}});registerService(Context.LOCATION_SERVICE, LocationManager.class,new CachedServiceFetcher<LocationManager>() {@Overridepublic LocationManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.LOCATION_SERVICE);return new LocationManager(ctx, ILocationManager.Stub.asInterface(b));}});registerService(Context.NETWORK_POLICY_SERVICE, NetworkPolicyManager.class,new CachedServiceFetcher<NetworkPolicyManager>() {@Overridepublic NetworkPolicyManager createService(ContextImpl ctx) throws ServiceNotFoundException {return new NetworkPolicyManager(ctx, INetworkPolicyManager.Stub.asInterface(ServiceManager.getServiceOrThrow(Context.NETWORK_POLICY_SERVICE)));}});registerService(Context.NOTIFICATION_SERVICE, NotificationManager.class,new CachedServiceFetcher<NotificationManager>() {@Overridepublic NotificationManager createService(ContextImpl ctx) {final Context outerContext = ctx.getOuterContext();return new NotificationManager(new ContextThemeWrapper(outerContext,Resources.selectSystemTheme(0,outerContext.getApplicationInfo().targetSdkVersion,com.android.internal.R.style.Theme_Dialog,com.android.internal.R.style.Theme_Holo_Dialog,com.android.internal.R.style.Theme_DeviceDefault_Dialog,com.android.internal.R.style.Theme_DeviceDefault_Light_Dialog)),ctx.mMainThread.getHandler());}});registerService(Context.NSD_SERVICE, NsdManager.class,new CachedServiceFetcher<NsdManager>() {@Overridepublic NsdManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.NSD_SERVICE);INsdManager service = INsdManager.Stub.asInterface(b);return new NsdManager(ctx.getOuterContext(), service);}});registerService(Context.POWER_SERVICE, PowerManager.class,new CachedServiceFetcher<PowerManager>() {@Overridepublic PowerManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.POWER_SERVICE);IPowerManager service = IPowerManager.Stub.asInterface(b);return new PowerManager(ctx.getOuterContext(),service, ctx.mMainThread.getHandler());}});registerService(Context.RECOVERY_SERVICE, RecoverySystem.class,new CachedServiceFetcher<RecoverySystem>() {@Overridepublic RecoverySystem createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.RECOVERY_SERVICE);IRecoverySystem service = IRecoverySystem.Stub.asInterface(b);return new RecoverySystem(service);}});registerService(Context.SEARCH_SERVICE, SearchManager.class,new CachedServiceFetcher<SearchManager>() {@Overridepublic SearchManager createService(ContextImpl ctx) throws ServiceNotFoundException {return new SearchManager(ctx.getOuterContext(),ctx.mMainThread.getHandler());}});registerService(Context.SENSOR_SERVICE, SensorManager.class,new CachedServiceFetcher<SensorManager>() {@Overridepublic SensorManager createService(ContextImpl ctx) {return new SystemSensorManager(ctx.getOuterContext(),ctx.mMainThread.getHandler().getLooper());}});registerService(Context.SENSOR_PRIVACY_SERVICE, SensorPrivacyManager.class,new CachedServiceFetcher<SensorPrivacyManager>() {@Overridepublic SensorPrivacyManager createService(ContextImpl ctx) {return SensorPrivacyManager.getInstance(ctx);}});registerService(Context.STATS_MANAGER, StatsManager.class,new CachedServiceFetcher<StatsManager>() {@Overridepublic StatsManager createService(ContextImpl ctx) {return new StatsManager(ctx.getOuterContext());}});registerService(Context.STATUS_BAR_SERVICE, StatusBarManager.class,new CachedServiceFetcher<StatusBarManager>() {@Overridepublic StatusBarManager createService(ContextImpl ctx) {return new StatusBarManager(ctx.getOuterContext());}});registerService(Context.STORAGE_SERVICE, StorageManager.class,new CachedServiceFetcher<StorageManager>() {@Overridepublic StorageManager createService(ContextImpl ctx) throws ServiceNotFoundException {return new StorageManager(ctx, ctx.mMainThread.getHandler().getLooper());}});registerService(Context.STORAGE_STATS_SERVICE, StorageStatsManager.class,new CachedServiceFetcher<StorageStatsManager>() {@Overridepublic StorageStatsManager createService(ContextImpl ctx) throws ServiceNotFoundException {IStorageStatsManager service = IStorageStatsManager.Stub.asInterface(ServiceManager.getServiceOrThrow(Context.STORAGE_STATS_SERVICE));return new StorageStatsManager(ctx, service);}});registerService(Context.SYSTEM_UPDATE_SERVICE, SystemUpdateManager.class,new CachedServiceFetcher<SystemUpdateManager>() {@Overridepublic SystemUpdateManager createService(ContextImpl ctx)throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.SYSTEM_UPDATE_SERVICE);ISystemUpdateManager service = ISystemUpdateManager.Stub.asInterface(b);return new SystemUpdateManager(service);}});registerService(Context.TELEPHONY_SERVICE, TelephonyManager.class,new CachedServiceFetcher<TelephonyManager>() {@Overridepublic TelephonyManager createService(ContextImpl ctx) {return new TelephonyManager(ctx.getOuterContext());}});registerService(Context.TELEPHONY_SUBSCRIPTION_SERVICE, SubscriptionManager.class,new CachedServiceFetcher<SubscriptionManager>() {@Overridepublic SubscriptionManager createService(ContextImpl ctx) throws ServiceNotFoundException {return new SubscriptionManager(ctx.getOuterContext());}});registerService(Context.TELEPHONY_RCS_SERVICE, RcsManager.class,new CachedServiceFetcher<RcsManager>() {@Overridepublic RcsManager createService(ContextImpl ctx) {return new RcsManager(ctx.getOuterContext());}});registerService(Context.CARRIER_CONFIG_SERVICE, CarrierConfigManager.class,new CachedServiceFetcher<CarrierConfigManager>() {@Overridepublic CarrierConfigManager createService(ContextImpl ctx) {return new CarrierConfigManager(ctx.getOuterContext());}});registerService(Context.TELECOM_SERVICE, TelecomManager.class,new CachedServiceFetcher<TelecomManager>() {@Overridepublic TelecomManager createService(ContextImpl ctx) {return new TelecomManager(ctx.getOuterContext());}});registerService(Context.EUICC_SERVICE, EuiccManager.class,new CachedServiceFetcher<EuiccManager>() {@Overridepublic EuiccManager createService(ContextImpl ctx) {return new EuiccManager(ctx.getOuterContext());}});registerService(Context.EUICC_CARD_SERVICE, EuiccCardManager.class,new CachedServiceFetcher<EuiccCardManager>() {@Overridepublic EuiccCardManager createService(ContextImpl ctx) {return new EuiccCardManager(ctx.getOuterContext());}});registerService(Context.UI_MODE_SERVICE, UiModeManager.class,new CachedServiceFetcher<UiModeManager>() {@Overridepublic UiModeManager createService(ContextImpl ctx) throws ServiceNotFoundException {return new UiModeManager();}});registerService(Context.USB_SERVICE, UsbManager.class,new CachedServiceFetcher<UsbManager>() {@Overridepublic UsbManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.USB_SERVICE);return new UsbManager(ctx, IUsbManager.Stub.asInterface(b));}});registerService(Context.ADB_SERVICE, AdbManager.class,new CachedServiceFetcher<AdbManager>() {@Overridepublic AdbManager createService(ContextImpl ctx)throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.ADB_SERVICE);return new AdbManager(ctx, IAdbManager.Stub.asInterface(b));}});registerService(Context.SERIAL_SERVICE, SerialManager.class,new CachedServiceFetcher<SerialManager>() {@Overridepublic SerialManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.SERIAL_SERVICE);return new SerialManager(ctx, ISerialManager.Stub.asInterface(b));}});registerService(Context.VIBRATOR_SERVICE, Vibrator.class,new CachedServiceFetcher<Vibrator>() {@Overridepublic Vibrator createService(ContextImpl ctx) {return new SystemVibrator(ctx);}});registerService(Context.WALLPAPER_SERVICE, WallpaperManager.class,new CachedServiceFetcher<WallpaperManager>() {@Overridepublic WallpaperManager createService(ContextImpl ctx)throws ServiceNotFoundException {final IBinder b = ServiceManager.getService(Context.WALLPAPER_SERVICE);if (b == null) {// There are 2 reason service can be null:// 1.Device doesn't support it - that's fine// 2.App is running on instant mode - should failfinal boolean enabled = Resources.getSystem().getBoolean(com.android.internal.R.bool.config_enableWallpaperService);if (!enabled) {// Life moves on...return DisabledWallpaperManager.getInstance();}if (ctx.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.P) {// Instant appthrow new ServiceNotFoundException(Context.WALLPAPER_SERVICE);}// Bad state - WallpaperManager methods will throw exception}IWallpaperManager service = IWallpaperManager.Stub.asInterface(b);return new WallpaperManager(service, ctx.getOuterContext(),ctx.mMainThread.getHandler());}});registerService(Context.LOWPAN_SERVICE, LowpanManager.class,new CachedServiceFetcher<LowpanManager>() {@Overridepublic LowpanManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.LOWPAN_SERVICE);ILowpanManager service = ILowpanManager.Stub.asInterface(b);return new LowpanManager(ctx.getOuterContext(), service,ConnectivityThread.getInstanceLooper());}});registerService(Context.WIFI_SERVICE, WifiManager.class,new CachedServiceFetcher<WifiManager>() {@Overridepublic WifiManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.WIFI_SERVICE);IWifiManager service = IWifiManager.Stub.asInterface(b);return new WifiManager(ctx.getOuterContext(), service,ConnectivityThread.getInstanceLooper());}});registerService(Context.WIFI_P2P_SERVICE, WifiP2pManager.class,new StaticServiceFetcher<WifiP2pManager>() {@Overridepublic WifiP2pManager createService() throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.WIFI_P2P_SERVICE);IWifiP2pManager service = IWifiP2pManager.Stub.asInterface(b);return new WifiP2pManager(service);}});registerService(Context.WIFI_AWARE_SERVICE, WifiAwareManager.class,new CachedServiceFetcher<WifiAwareManager>() {@Overridepublic WifiAwareManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.WIFI_AWARE_SERVICE);IWifiAwareManager service = IWifiAwareManager.Stub.asInterface(b);if (service == null) {return null;}return new WifiAwareManager(ctx.getOuterContext(), service);}});registerService(Context.WIFI_SCANNING_SERVICE, WifiScanner.class,new CachedServiceFetcher<WifiScanner>() {@Overridepublic WifiScanner createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.WIFI_SCANNING_SERVICE);IWifiScanner service = IWifiScanner.Stub.asInterface(b);return new WifiScanner(ctx.getOuterContext(), service,ConnectivityThread.getInstanceLooper());}});registerService(Context.WIFI_RTT_SERVICE, RttManager.class,new CachedServiceFetcher<RttManager>() {@Overridepublic RttManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.WIFI_RTT_RANGING_SERVICE);IWifiRttManager service = IWifiRttManager.Stub.asInterface(b);return new RttManager(ctx.getOuterContext(),new WifiRttManager(ctx.getOuterContext(), service));}});registerService(Context.WIFI_RTT_RANGING_SERVICE, WifiRttManager.class,new CachedServiceFetcher<WifiRttManager>() {@Overridepublic WifiRttManager createService(ContextImpl ctx)throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.WIFI_RTT_RANGING_SERVICE);IWifiRttManager service = IWifiRttManager.Stub.asInterface(b);return new WifiRttManager(ctx.getOuterContext(), service);}});registerService(Context.ETHERNET_SERVICE, EthernetManager.class,new CachedServiceFetcher<EthernetManager>() {@Overridepublic EthernetManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.ETHERNET_SERVICE);IEthernetManager service = IEthernetManager.Stub.asInterface(b);return new EthernetManager(ctx.getOuterContext(), service);}});registerService(Context.WINDOW_SERVICE, WindowManager.class,new CachedServiceFetcher<WindowManager>() {@Overridepublic WindowManager createService(ContextImpl ctx) {return new WindowManagerImpl(ctx);}});registerService(Context.USER_SERVICE, UserManager.class,new CachedServiceFetcher<UserManager>() {@Overridepublic UserManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.USER_SERVICE);IUserManager service = IUserManager.Stub.asInterface(b);return new UserManager(ctx, service);}});registerService(Context.APP_OPS_SERVICE, AppOpsManager.class,new CachedServiceFetcher<AppOpsManager>() {@Overridepublic AppOpsManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.APP_OPS_SERVICE);IAppOpsService service = IAppOpsService.Stub.asInterface(b);return new AppOpsManager(ctx, service);}});registerService(Context.CAMERA_SERVICE, CameraManager.class,new CachedServiceFetcher<CameraManager>() {@Overridepublic CameraManager createService(ContextImpl ctx) {return new CameraManager(ctx);}});registerService(Context.LAUNCHER_APPS_SERVICE, LauncherApps.class,new CachedServiceFetcher<LauncherApps>() {@Overridepublic LauncherApps createService(ContextImpl ctx) {return new LauncherApps(ctx);}});registerService(Context.RESTRICTIONS_SERVICE, RestrictionsManager.class,new CachedServiceFetcher<RestrictionsManager>() {@Overridepublic RestrictionsManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.RESTRICTIONS_SERVICE);IRestrictionsManager service = IRestrictionsManager.Stub.asInterface(b);return new RestrictionsManager(ctx, service);}});registerService(Context.PRINT_SERVICE, PrintManager.class,new CachedServiceFetcher<PrintManager>() {@Overridepublic PrintManager createService(ContextImpl ctx) throws ServiceNotFoundException {IPrintManager service = null;// If the feature not present, don't try to look up every timeif (ctx.getPackageManager().hasSystemFeature(PackageManager.FEATURE_PRINTING)) {service = IPrintManager.Stub.asInterface(ServiceManager.getServiceOrThrow(Context.PRINT_SERVICE));}final int userId = ctx.getUserId();final int appId = UserHandle.getAppId(ctx.getApplicationInfo().uid);return new PrintManager(ctx.getOuterContext(), service, userId, appId);}});registerService(Context.COMPANION_DEVICE_SERVICE, CompanionDeviceManager.class,new CachedServiceFetcher<CompanionDeviceManager>() {@Overridepublic CompanionDeviceManager createService(ContextImpl ctx)throws ServiceNotFoundException {ICompanionDeviceManager service = null;// If the feature not present, don't try to look up every timeif (ctx.getPackageManager().hasSystemFeature(PackageManager.FEATURE_COMPANION_DEVICE_SETUP)) {service = ICompanionDeviceManager.Stub.asInterface(ServiceManager.getServiceOrThrow(Context.COMPANION_DEVICE_SERVICE));}return new CompanionDeviceManager(service, ctx.getOuterContext());}});registerService(Context.CONSUMER_IR_SERVICE, ConsumerIrManager.class,new CachedServiceFetcher<ConsumerIrManager>() {@Overridepublic ConsumerIrManager createService(ContextImpl ctx) throws ServiceNotFoundException {return new ConsumerIrManager(ctx);}});registerService(Context.MEDIA_SESSION_SERVICE, MediaSessionManager.class,new CachedServiceFetcher<MediaSessionManager>() {@Overridepublic MediaSessionManager createService(ContextImpl ctx) {return new MediaSessionManager(ctx);}});registerService(Context.TRUST_SERVICE, TrustManager.class,new StaticServiceFetcher<TrustManager>() {@Overridepublic TrustManager createService() throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.TRUST_SERVICE);return new TrustManager(b);}});registerService(Context.FINGERPRINT_SERVICE, FingerprintManager.class,new CachedServiceFetcher<FingerprintManager>() {@Overridepublic FingerprintManager createService(ContextImpl ctx) throws ServiceNotFoundException {final IBinder binder;if (ctx.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.O) {binder = ServiceManager.getServiceOrThrow(Context.FINGERPRINT_SERVICE);} else {binder = ServiceManager.getService(Context.FINGERPRINT_SERVICE);}IFingerprintService service = IFingerprintService.Stub.asInterface(binder);return new FingerprintManager(ctx.getOuterContext(), service);}});registerService(Context.FACE_SERVICE, FaceManager.class,new CachedServiceFetcher<FaceManager>() {@Overridepublic FaceManager createService(ContextImpl ctx)throws ServiceNotFoundException {final IBinder binder;if (ctx.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.O) {binder = ServiceManager.getServiceOrThrow(Context.FACE_SERVICE);} else {binder = ServiceManager.getService(Context.FACE_SERVICE);}IFaceService service = IFaceService.Stub.asInterface(binder);return new FaceManager(ctx.getOuterContext(), service);}});registerService(Context.IRIS_SERVICE, IrisManager.class,new CachedServiceFetcher<IrisManager>() {@Overridepublic IrisManager createService(ContextImpl ctx)throws ServiceNotFoundException {final IBinder binder =ServiceManager.getServiceOrThrow(Context.IRIS_SERVICE);IIrisService service = IIrisService.Stub.asInterface(binder);return new IrisManager(ctx.getOuterContext(), service);}});registerService(Context.BIOMETRIC_SERVICE, BiometricManager.class,new CachedServiceFetcher<BiometricManager>() {@Overridepublic BiometricManager createService(ContextImpl ctx)throws ServiceNotFoundException {if (BiometricManager.hasBiometrics(ctx)) {final IBinder binder =ServiceManager.getServiceOrThrow(Context.BIOMETRIC_SERVICE);final IBiometricService service =IBiometricService.Stub.asInterface(binder);return new BiometricManager(ctx.getOuterContext(), service);} else {// Allow access to the manager when service is null. This saves memory// on devices without biometric hardware.return new BiometricManager(ctx.getOuterContext(), null);}}});registerService(Context.TV_INPUT_SERVICE, TvInputManager.class,new CachedServiceFetcher<TvInputManager>() {@Overridepublic TvInputManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder iBinder = ServiceManager.getServiceOrThrow(Context.TV_INPUT_SERVICE);ITvInputManager service = ITvInputManager.Stub.asInterface(iBinder);return new TvInputManager(service, ctx.getUserId());}});registerService(Context.NETWORK_SCORE_SERVICE, NetworkScoreManager.class,new CachedServiceFetcher<NetworkScoreManager>() {@Overridepublic NetworkScoreManager createService(ContextImpl ctx) throws ServiceNotFoundException {return new NetworkScoreManager(ctx);}});registerService(Context.USAGE_STATS_SERVICE, UsageStatsManager.class,new CachedServiceFetcher<UsageStatsManager>() {@Overridepublic UsageStatsManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder iBinder = ServiceManager.getServiceOrThrow(Context.USAGE_STATS_SERVICE);IUsageStatsManager service = IUsageStatsManager.Stub.asInterface(iBinder);return new UsageStatsManager(ctx.getOuterContext(), service);}});registerService(Context.NETWORK_STATS_SERVICE, NetworkStatsManager.class,new CachedServiceFetcher<NetworkStatsManager>() {@Overridepublic NetworkStatsManager createService(ContextImpl ctx) throws ServiceNotFoundException {return new NetworkStatsManager(ctx.getOuterContext());}});registerService(Context.JOB_SCHEDULER_SERVICE, JobScheduler.class,new StaticServiceFetcher<JobScheduler>() {@Overridepublic JobScheduler createService() throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.JOB_SCHEDULER_SERVICE);return new JobSchedulerImpl(IJobScheduler.Stub.asInterface(b));}});registerService(Context.PERSISTENT_DATA_BLOCK_SERVICE, PersistentDataBlockManager.class,new StaticServiceFetcher<PersistentDataBlockManager>() {@Overridepublic PersistentDataBlockManager createService() throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.PERSISTENT_DATA_BLOCK_SERVICE);IPersistentDataBlockService persistentDataBlockService =IPersistentDataBlockService.Stub.asInterface(b);if (persistentDataBlockService != null) {return new PersistentDataBlockManager(persistentDataBlockService);} else {// not supportedreturn null;}}});registerService(Context.OEM_LOCK_SERVICE, OemLockManager.class,new StaticServiceFetcher<OemLockManager>() {@Overridepublic OemLockManager createService() throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.OEM_LOCK_SERVICE);IOemLockService oemLockService = IOemLockService.Stub.asInterface(b);if (oemLockService != null) {return new OemLockManager(oemLockService);} else {// not supportedreturn null;}}});registerService(Context.MEDIA_PROJECTION_SERVICE, MediaProjectionManager.class,new CachedServiceFetcher<MediaProjectionManager>() {@Overridepublic MediaProjectionManager createService(ContextImpl ctx) {return new MediaProjectionManager(ctx);}});registerService(Context.APPWIDGET_SERVICE, AppWidgetManager.class,new CachedServiceFetcher<AppWidgetManager>() {@Overridepublic AppWidgetManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.APPWIDGET_SERVICE);return new AppWidgetManager(ctx, IAppWidgetService.Stub.asInterface(b));}});registerService(Context.MIDI_SERVICE, MidiManager.class,new CachedServiceFetcher<MidiManager>() {@Overridepublic MidiManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.MIDI_SERVICE);return new MidiManager(IMidiManager.Stub.asInterface(b));}});registerService(Context.RADIO_SERVICE, RadioManager.class,new CachedServiceFetcher<RadioManager>() {@Overridepublic RadioManager createService(ContextImpl ctx) throws ServiceNotFoundException {return new RadioManager(ctx);}});registerService(Context.HARDWARE_PROPERTIES_SERVICE, HardwarePropertiesManager.class,new CachedServiceFetcher<HardwarePropertiesManager>() {@Overridepublic HardwarePropertiesManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.HARDWARE_PROPERTIES_SERVICE);IHardwarePropertiesManager service =IHardwarePropertiesManager.Stub.asInterface(b);return new HardwarePropertiesManager(ctx, service);}});registerService(Context.SOUND_TRIGGER_SERVICE, SoundTriggerManager.class,new CachedServiceFetcher<SoundTriggerManager>() {@Overridepublic SoundTriggerManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.SOUND_TRIGGER_SERVICE);return new SoundTriggerManager(ctx, ISoundTriggerService.Stub.asInterface(b));}});registerService(Context.SHORTCUT_SERVICE, ShortcutManager.class,new CachedServiceFetcher<ShortcutManager>() {@Overridepublic ShortcutManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.SHORTCUT_SERVICE);return new ShortcutManager(ctx, IShortcutService.Stub.asInterface(b));}});registerService(Context.OVERLAY_SERVICE, OverlayManager.class,new CachedServiceFetcher<OverlayManager>() {@Overridepublic OverlayManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.OVERLAY_SERVICE);return new OverlayManager(ctx, IOverlayManager.Stub.asInterface(b));}});registerService(Context.NETWORK_WATCHLIST_SERVICE, NetworkWatchlistManager.class,new CachedServiceFetcher<NetworkWatchlistManager>() {@Overridepublic NetworkWatchlistManager createService(ContextImpl ctx)throws ServiceNotFoundException {IBinder b =ServiceManager.getServiceOrThrow(Context.NETWORK_WATCHLIST_SERVICE);return new NetworkWatchlistManager(ctx,INetworkWatchlistManager.Stub.asInterface(b));}});registerService(Context.SYSTEM_HEALTH_SERVICE, SystemHealthManager.class,new CachedServiceFetcher<SystemHealthManager>() {@Overridepublic SystemHealthManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(BatteryStats.SERVICE_NAME);return new SystemHealthManager(IBatteryStats.Stub.asInterface(b));}});registerService(Context.CONTEXTHUB_SERVICE, ContextHubManager.class,new CachedServiceFetcher<ContextHubManager>() {@Overridepublic ContextHubManager createService(ContextImpl ctx) throws ServiceNotFoundException {return new ContextHubManager(ctx.getOuterContext(),ctx.mMainThread.getHandler().getLooper());}});registerService(Context.INCIDENT_SERVICE, IncidentManager.class,new CachedServiceFetcher<IncidentManager>() {@Overridepublic IncidentManager createService(ContextImpl ctx) throws ServiceNotFoundException {return new IncidentManager(ctx);}});registerService(Context.BUGREPORT_SERVICE, BugreportManager.class,new CachedServiceFetcher<BugreportManager>() {@Overridepublic BugreportManager createService(ContextImpl ctx)throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.BUGREPORT_SERVICE);return new BugreportManager(ctx.getOuterContext(),IDumpstate.Stub.asInterface(b));}});registerService(Context.AUTOFILL_MANAGER_SERVICE, AutofillManager.class,new CachedServiceFetcher<AutofillManager>() {@Overridepublic AutofillManager createService(ContextImpl ctx) throws ServiceNotFoundException {// Get the services without throwing as this is an optional featureIBinder b = ServiceManager.getService(Context.AUTOFILL_MANAGER_SERVICE);IAutoFillManager service = IAutoFillManager.Stub.asInterface(b);return new AutofillManager(ctx.getOuterContext(), service);}});registerService(Context.CONTENT_CAPTURE_MANAGER_SERVICE, ContentCaptureManager.class,new CachedServiceFetcher<ContentCaptureManager>() {@Overridepublic ContentCaptureManager createService(ContextImpl ctx)throws ServiceNotFoundException {// Get the services without throwing as this is an optional featureContext outerContext = ctx.getOuterContext();ContentCaptureOptions options = outerContext.getContentCaptureOptions();// Options is null when the service didn't whitelist the activity or packageif (options != null && (options.lite || options.isWhitelisted(outerContext))) {IBinder b = ServiceManager.getService(Context.CONTENT_CAPTURE_MANAGER_SERVICE);IContentCaptureManager service = IContentCaptureManager.Stub.asInterface(b);// Service is null when not provided by OEM or disabled by kill-switch.if (service != null) {return new ContentCaptureManager(outerContext, service, options);}}// When feature is disabled or app / package not whitelisted, we return a null// manager to apps so the performance impact is practically zeroreturn null;}});registerService(Context.APP_PREDICTION_SERVICE, AppPredictionManager.class,new CachedServiceFetcher<AppPredictionManager>() {@Overridepublic AppPredictionManager createService(ContextImpl ctx)throws ServiceNotFoundException {IBinder b = ServiceManager.getService(Context.APP_PREDICTION_SERVICE);return b == null ? null : new AppPredictionManager(ctx);}});registerService(Context.CONTENT_SUGGESTIONS_SERVICE,ContentSuggestionsManager.class,new CachedServiceFetcher<ContentSuggestionsManager>() {@Overridepublic ContentSuggestionsManager createService(ContextImpl ctx) {// No throw as this is an optional serviceIBinder b = ServiceManager.getService(Context.CONTENT_SUGGESTIONS_SERVICE);IContentSuggestionsManager service =IContentSuggestionsManager.Stub.asInterface(b);return new ContentSuggestionsManager(ctx.getUserId(), service);}});registerService(Context.VR_SERVICE, VrManager.class, new CachedServiceFetcher<VrManager>() {@Overridepublic VrManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.VR_SERVICE);return new VrManager(IVrManager.Stub.asInterface(b));}});registerService(Context.TIME_ZONE_RULES_MANAGER_SERVICE, RulesManager.class,new CachedServiceFetcher<RulesManager>() {@Overridepublic RulesManager createService(ContextImpl ctx) {return new RulesManager(ctx.getOuterContext());}});registerService(Context.CROSS_PROFILE_APPS_SERVICE, CrossProfileApps.class,new CachedServiceFetcher<CrossProfileApps>() {@Overridepublic CrossProfileApps createService(ContextImpl ctx)throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.CROSS_PROFILE_APPS_SERVICE);return new CrossProfileApps(ctx.getOuterContext(),ICrossProfileApps.Stub.asInterface(b));}});registerService(Context.SLICE_SERVICE, SliceManager.class,new CachedServiceFetcher<SliceManager>() {@Overridepublic SliceManager createService(ContextImpl ctx)throws ServiceNotFoundException {return new SliceManager(ctx.getOuterContext(),ctx.mMainThread.getHandler());}});registerService(Context.DEVICE_IDLE_CONTROLLER, DeviceIdleManager.class,new CachedServiceFetcher<DeviceIdleManager>() {@Overridepublic DeviceIdleManager createService(ContextImpl ctx)throws ServiceNotFoundException {IDeviceIdleController service = IDeviceIdleController.Stub.asInterface(ServiceManager.getServiceOrThrow(Context.DEVICE_IDLE_CONTROLLER));return new DeviceIdleManager(ctx.getOuterContext(), service);}});registerService(Context.TIME_DETECTOR_SERVICE, TimeDetector.class,new CachedServiceFetcher<TimeDetector>() {@Overridepublic TimeDetector createService(ContextImpl ctx)throws ServiceNotFoundException {return new TimeDetector();}});registerService(Context.PERMISSION_SERVICE, PermissionManager.class,new CachedServiceFetcher<PermissionManager>() {@Overridepublic PermissionManager createService(ContextImpl ctx) {IPackageManager packageManager = AppGlobals.getPackageManager();return new PermissionManager(ctx.getOuterContext(), packageManager);}});registerService(Context.PERMISSION_CONTROLLER_SERVICE, PermissionControllerManager.class,new CachedServiceFetcher<PermissionControllerManager>() {@Overridepublic PermissionControllerManager createService(ContextImpl ctx) {return new PermissionControllerManager(ctx.getOuterContext(),ctx.getMainThreadHandler());}});registerService(Context.ROLE_SERVICE, RoleManager.class,new CachedServiceFetcher<RoleManager>() {@Overridepublic RoleManager createService(ContextImpl ctx)throws ServiceNotFoundException {return new RoleManager(ctx.getOuterContext());}});registerService(Context.ROLE_CONTROLLER_SERVICE, RoleControllerManager.class,new CachedServiceFetcher<RoleControllerManager>() {@Overridepublic RoleControllerManager createService(ContextImpl ctx)throws ServiceNotFoundException {return new RoleControllerManager(ctx.getOuterContext());}});registerService(Context.ROLLBACK_SERVICE, RollbackManager.class,new CachedServiceFetcher<RollbackManager>() {@Overridepublic RollbackManager createService(ContextImpl ctx)throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.ROLLBACK_SERVICE);return new RollbackManager(ctx.getOuterContext(),IRollbackManager.Stub.asInterface(b));}});registerService(Context.DYNAMIC_SYSTEM_SERVICE, DynamicSystemManager.class,new CachedServiceFetcher<DynamicSystemManager>() {@Overridepublic DynamicSystemManager createService(ContextImpl ctx)throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.DYNAMIC_SYSTEM_SERVICE);return new DynamicSystemManager(IDynamicSystemService.Stub.asInterface(b));}});//CHECKSTYLE:ON IndentationCheck}

在类SystemServiceRegistry的静态代码块里面多次调用了registerService,而该方法就是往SYSTEM_SERVICE_NAMES这个map里面添加系统服务。

  private static <T> void registerService(String serviceName, Class<T> serviceClass,ServiceFetcher<T> serviceFetcher) {SYSTEM_SERVICE_NAMES.put(serviceClass, serviceName);SYSTEM_SERVICE_FETCHERS.put(serviceName, serviceFetcher);}

客户端调用getSystemService就是从SYSTEM_SERVICE_NAMES这个map里面查找系统服务。

   /* Gets a system service from a given context.*/public static Object getSystemService(ContextImpl ctx, String name) {ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);return fetcher != null ? fetcher.getService(ctx) : null;}

六、实现自定义系统服务

6.1、创建AIDL文件

创建源码路径:frameworks/base/core/java/android/app/IMyService.aidl

// IMyService.aidl
package android.app;interface IMyService {String getString(String str);
}

6.2、继承stub

创建文件路径:frameworks/base/services/core/java/com/android/server/customize/MyService.java

package com.android.server.customize;import android.app.IMyService;
import android.os.RemoteException;public class MyService extends IMyService.Stub {@Overridepublic String getString(String str) throws RemoteException {return "MyService:"+str;}
}

6.3、提供调用方法

路径:frameworks/base/core/java/android/app/MyServiceManager.java

package android.app;import android.os.RemoteException;public class MyServiceManager {private IMyService mService;public MyServiceManager(IMyService myService){mService=myService;}public String getString(String str){try {return mService.getString(str);} catch (RemoteException e) {e.printStackTrace();}return "";}
}

6.4、Context添加常量

路径:android-10.0.0_r41/frameworks/base/core/java/android/content/Context.java

   /*My customize service*/public static final String MY_CUSTOM_SERVICE="custom_service";

6.5、SystemServer里面添加自定义服务

路径:android-10.0.0_r41\\frameworks\\base\\services\\java\\com\\android\\server\\SystemServer.java

import com.android.server.customize.MyService;traceBeginAndSlog("StartMyCustomService");ServiceManager.addService(context.MY_CUSTOM_SERVICE, new MyService());traceEnd();

6.6、SELinux权限修改

6.6.1、service_contexts

路径:android-10.0.0_r41/frameworks/system/sepolicy/private/service_contexts
添加如下内容:
android framework-SystemServer进程

custom_service                            u:object_r:my_custom_service:s0

custom_service:为Context里面定义的MY_CUSTOM_SERVICE常量的值
my_custom_service:为Context里面定义的MY_CUSTOM_SERVICE常量的名

6.6.2、service.te

路径:system/sepolicy/public/service.te
添加如下内容:

type my_custom_service, system_api_service, system_server_service, service_manager_type;

android framework-SystemServer进程

6.6.3、

路径:/system/sepolicy/public/system_server.te
添加如下内容

allow system_server my_custom_service:service_manager add;

android framework-SystemServer进程

6.7、重新编译

6.7.1、source build/envsetup.sh

6.7.2、lunch,选择对应的产品

android framework-SystemServer进程
android framework-SystemServer进程

6.7.3、重新编译系统api : make update-api

修改 framework 下的源码后,需要先执行 make update-api

6.7.4、编译异常

  • The following public types were found added to the policy without an entry into the compatibility mapping file(s) found in private/compat/V.v/V.v[.ignore].cil, where V.v is the latest API level
    android framework-SystemServer进程
./prebuilts/api/27.0/public/service.te   # 需要
./prebuilts/api/28.0/public/service.te   # 需要
./prebuilts/api/29.0/public/service.te    # 需要
./prebuilts/api/26.0/public/service.te   # 需要
./public/service.te                 # 需要./reqd_mask/service_contexts
./prebuilts/api/27.0/private/service_contexts   # 需要
./prebuilts/api/28.0/private/service_contexts   # 需要
./prebuilts/api/29.0/private/service_contexts       # 需要
./prebuilts/api/26.0/private/service_contexts   # 需要
./private/service_contexts         # 需要

把以上文件修改一致即可。重新编译
android framework-SystemServer进程

6.7.5、重新烧录新的Rom

android framework-SystemServer进程

6.7.6、adb查看系统服务

adb shell service list

android framework-SystemServer进程

6.8、SystemServiceRegistry里面注册该自定义服务

路径:frameworks/base/core/java/android/app/SystemServiceRegistry.java

import android.app.IMyService;
import android.app.MyServiceManager;registerService(Context.MY_CUSTOM_SERVICE, MyServiceManager.class,new CachedServiceFetcher<MyServiceManager>() {@Overridepublic MyServiceManager createService(ContextImpl ctx) throws ServiceNotFoundException {IBinder b = ServiceManager.getServiceOrThrow(Context.MY_CUSTOM_SERVICE);IMyService service = IMyService.Stub.asInterface(b);return new MyServiceManager(service);}});

android framework-SystemServer进程

6.9、客户端调用

6.9.1、项目中导入classes.jar

路径:out\\target\\common\\obj\\JAVA_LIBRARIES\\framework_intermediates\\classes.jar
android framework-SystemServer进程
android framework-SystemServer进程

package com.ainiljing.custom;import android.app.MyServiceManager;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;import com.anniljing.customizesystemservice.R;import androidx.appcompat.app.AppCompatActivity;public class MainActivity extends AppCompatActivity {private static final String TAG=MainActivity.class.getSimpleName();private Context mContext;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);mContext=this;setContentView(R.layout.activity_main);MyServiceManager myServiceManager=(MyServiceManager)getSystemService("custom_service");if (myServiceManager!=null){String helloService=myServiceManager.getString("Hello");Log.e(TAG,helloService);}else{Log.e(TAG,""+myServiceManager);}}
}

问题1:无法获取到service对象

android studio里面的日志没有显示具体原因,我采用adb logcat -v time >D:\\log.log,将日志信息输出,查到原来是SELinux鉴权拒绝了
android framework-SystemServer进程

  • 标志性log 格式

avc: denied { 操作权限 } for pid=7201 comm=“进程名” scontext=u:r:源类型:s0 tcontext=u:r:目标类型:s0 tclass=访问类别 permissive=0

  • 权限配置格式如下:

allow 源类型 目标类型:访问类别 操作权限 ;

avc: denied { find } for service=custom_service pid=5048 uid=10106 scontext=u:r:untrusted_app:s0:c106,c256,c512,c768 tcontext=u:object_r:my_custom_service:s0 tclass=service_manager permissive=0
操作权限:find
源类型:untrusted_app
目标类型:my_custom_service
访问类别:service_manager

在untrusted.te文件配置信息如下:
路径:
1、system/sepolicy/private/untrusted_app.te
2、system/sepolicy/public/untrusted_app.te
3、system/sepolicy/prebuilts/api/26.0/private/untrusted_app.te
4、system/sepolicy/prebuilts/api/26.0/public/untrusted_app.te
5、system/sepolicy/prebuilts/api/27.0/private/untrusted_app.te
6、system/sepolicy/prebuilts/api/27.0/public/untrusted_app.te
7、system/sepolicy/prebuilts/api/28.0/private/untrusted_app.te
8、system/sepolicy/prebuilts/api/28.0/public/untrusted_app.te
9、system/sepolicy/prebuilts/api/29.0/private/untrusted_app.te
10、system/sepolicy/prebuilts/api/29.0/public/untrusted_app.te

allow untrusted_app my_custom_service:service_manager find;

android framework-SystemServer进程
再次重新编译:

source build/envsetup.sh

lunch

make update-api

make -j8

重新刷机

android framework-SystemServer进程