1. 程式人生 > >Android系統之System Server大綱

Android系統之System Server大綱

前言

System Server是android 基本服務的提供者,是android系統執行的最基本需求,所有server執行在一個叫system_process的程序中,system_process程序是android java虛擬機器跑的第一個程序,從Zygote 建立而來,是andorid系統最重要的java虛擬機器。可以說,整個android系統的業務都是圍繞system server而展開,所以,當system_process死掉了,手機必須重啟。

System server概要

System server主要包含以下服務:

  • 1、 EntropyService, 熵服務,用於產生隨機數;
  • 2、 PowerManagerService, 電源管理服務;
  • 3、 ActivityMangerService Activity,管理服務;
  • 4、 TelephonyRegistry, 電話服務,電話底層通知服務;
  • 5、 PackageManagerService, 程式包管理服務;
  • 6、 AccountManagerService, 聯絡人賬戶管理服務;
  • 7、 ContentService, 內容提供器服務,提供跨程序資料交換;
  • 8、 LightService, 光感應感測器服務;
  • 9、 BatteryService,電池服務;
  • 10、 VibrateService,震動器服務;
  • 11、 AlarmManagerService,鬧鐘服務;
  • 12、 WindowManagerService,視窗管理服務;
  • 13、 BluetoothService,藍芽服務;
  • 14、 InputMethodManagerService,輸入法服務;
  • 15、 AccessibilityManagerService, 輔助器管理程式服務;
  • 16、 DevicePolicyManagerService,提供系統級別的設定及屬性;
  • 17、 StatusBarManagerService,狀態列管理服務;
  • 18、 ClipboardService,貼上板服務;
  • 19、 NetworkManagerService,網路管理服務;
  • 20、 TextServicesManagerService,使用者管理服務;
  • 21、 NetworkStatsService,手機網路狀態服務;
  • 22、 NetworkPolicyManagerService,low-level網路策略服務;
  • 23、 WifiP2pService,Wifi點對點服務;
  • 24、 WifiService,Wifi服務;
  • 25、 ConnectivityService,網路連線狀態服務;
  • 26、 MountService,磁碟載入服務;
  • 27、 NotificationManagerService,通知管理服務;
  • 28、 DeviceStorageMonitorService,儲存裝置容量監聽服務;
  • 29、 LocationManagerService,位置管理服務;
  • 30、 CountryDetectorService,檢查使用者當前所在國家服務;
  • 31、 SearchManagerService,搜尋管理服務;
  • 32、 DropBoxManagerService,系統日誌檔案管理服務;
  • 33、 WallpaperManagerService,桌布管理服務;
  • 34、 AudioService,AudioFlinger上層封裝音訊管理服務;
  • 35、 UsbService,USB Host 和 device管理服務;
  • 36、 UiModeManagerService,UI模式管理服務;
  • 37、 BackupManagerService,備份服務;
  • 38、 AppWidgetService,應用桌面部件服務;
  • 39、 RecognitionManagerService,身份識別服務;
  • 40、 DiskStatsService,磁碟統計服務;
  • 41、 SamplingProfilerService,效能統計服務;
  • 42、 NetworkTimeUpdateService,網路時間更新服務;
  • 43、 InputManagerService,輸入管理服務;
  • 44、 FingerprintService,指紋服務;
  • 45、 DreamManagerService, dreams服務;
  • 46、 HdmiControlService, HDMI控制服務;
  • 47、 SsvService,SIM卡狀態和轉換服務;

以上所列系統服務不代表最新Android系統的所有系統服務。

System server啟動的入口

這些服務那麼重要,它們什麼時候啟動?都做了些什麼事情?等等這些問題是本文以及大綱下面的文章將會一一道來。

瞭解這些系統服務之前,先來了解一個重量級的超級類SystemServer.java, 這個類在AOSP中的路徑是:frameworks/base/services/java/com/android/server/SystemServer.java,在上文中提到,從Zygote建立system_process程序時,便例項化了該類。熟悉java的開發者都知道,啟動某個java程式時,最先呼叫的就是聲明瞭main()方法的類。所以SystemServer.java被例項化後,便呼叫了main()方法。首先看看SystemServer.java的構造方法:

public SystemServer() {
    // Check for factory test mode.
    mFactoryTestMode = FactoryTest.getMode();
}

構造方法裡面只做了從屬性系統中讀取了工廠測試模式,這個不在本文以及本大綱的文章中贅述的內容,這裡就不在敘述了。

下面直接進入main()方法:

public static void main(String[] args) {
    new SystemServer().run();
}     

直接呼叫了類內的run()方法,繼續跟蹤:

private void run() {
    try {
        // AndroidRuntime using the same set of system properties, but only the system_server
        // Initialize the system context.
        createSystemContext();

        // Create the system service manager.
        mSystemServiceManager = new SystemServiceManager(mSystemContext);
        LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
    } finally {
        Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }

    // Start services.
    try {
        Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartServices");
        startBootstrapServices();
        startCoreServices();
        startOtherServices();
    } catch (Throwable ex) {
        Slog.e("System", "******************************************");
        Slog.e("System", "************ Failure starting system services", ex);
        throw ex;
    } finally {
        Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
    .....
}

上述程式碼中,首先建立一個system context,這個物件在整個system server中使用非常頻繁。接著建立一個SystemServiceManager.java的例項,顧名思義就是SystemService的管理者,管理所有的SystemService。程式碼中把接著建立一個SystemServiceManager的例項通過LocalServices.addService(SystemServiceManager.class, mSystemServiceManager)語句設定到LocalService中,LocalServices的功能類似SystemServiceManager,不同點在於LocalServices專門用來管理system_process程序中的SystemService,也就沒有真正的跨程序通訊,也就沒有Binder物件。

System server啟動的過程

接著就是啟動各種系統服務,在這裡分三種類型的SystemService,依次啟動,分別對應三個方法:

        startBootstrapServices();
        startCoreServices();
        startOtherServices();

這三個方法的順序不能混亂,一定要按照上述順序依次執行,先看startBootstrapServices()中啟動了那些系統服務

private void startBootstrapServices() {
    Installer installer = mSystemServiceManager.startService(Installer.class);

    // Activity manager runs the show.
    mActivityManagerService = mSystemServiceManager.startService(
            ActivityManagerService.Lifecycle.class).getService();
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    mActivityManagerService.setInstaller(installer);


    mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);

    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "InitPowerManagement");
    mActivityManagerService.initPowerManagement();
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);

    // Manages LEDs and display backlight so we need it to bring up the display.
    mSystemServiceManager.startService(LightsService.class);

    // Display manager is needed to provide display metrics before package manager
    // starts up.
    mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);

    // We need the default display before we can initialize the package manager.
    mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);

    ......

    // Start the package manager.
    .....

    traceBeginAndSlog("StartUserManagerService");
    mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
    ......
}

上述程式碼可以看到,這裡啟動了

  • Installer
  • ActivityManagerService.Lifecycle
  • PowerManagerService
  • LightsService
  • DisplayManagerService
  • UserManagerService

啟動這些SystemService都是通過SystemServiceManager的startService()的方式啟動,啟動完成後會回撥SystemService的onStart()方法。 
繼續看第二個方法startCoreServices()啟動了那些系統服務

private void startCoreServices() {
    // Tracks the battery level.  Requires LightService.
    mSystemServiceManager.startService(BatteryService.class);

    // Tracks application usage stats.
    mSystemServiceManager.startService(UsageStatsService.class);
    mActivityManagerService.setUsageStatsManager(
            LocalServices.getService(UsageStatsManagerInternal.class));

    // Tracks whether the updatable WebView is in a ready state and watches for update installs.
    mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
}

startCoreServices()中啟動了

  • BatteryService
  • UsageStatsService
  • WebViewUpdateService

上文中提到,startBootstrapServices()必須在startCoreServices()前面執行,這裡就能找到一個原因,startCoreServices()中用到mActivityManagerService物件,而該物件在startBootstrapServices()中被例項化,如果先呼叫startCoreServices(),mActivityManagerService物件便會發生NullPointerException的RuntimeException異常。

接著就是startOtherServices()中啟動的service了,先看程式碼

private void startOtherServices() {
    try {
        ServiceManager.addService("scheduling_policy", new SchedulingPolicyService());

        mSystemServiceManager.startService(TelecomLoaderService.class);

        traceBeginAndSlog("StartTelephonyRegistry");
        telephonyRegistry = new TelephonyRegistry(context);
        ServiceManager.addService("telephony.registry", telephonyRegistry);
        Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);

        mEntropyMixer = new EntropyMixer(context);

        mContentResolver = context.getContentResolver();

        mSystemServiceManager.startService(CameraService.class);

        mSystemServiceManager.startService(ACCOUNT_SERVICE_CLASS);

        mSystemServiceManager.startService(CONTENT_SERVICE_CLASS);

        mActivityManagerService.installSystemProviders();

        vibrator = new VibratorService(context);
        ServiceManager.addService("vibrator", vibrator);

        consumerIr = new ConsumerIrService(context);
        ServiceManager.addService(Context.CONSUMER_IR_SERVICE, consumerIr);

        mSystemServiceManager.startService(AlarmManagerService.class);

        final Watchdog watchdog = Watchdog.getInstance();
        watchdog.init(context, mActivityManagerService);

        traceBeginAndSlog("StartInputManagerService");
        inputManager = new InputManagerService(context);
        Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);

        wm = WindowManagerService.main(context, inputManager,
                mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,
                !mFirstBoot, mOnlyCore);
        ServiceManager.addService(Context.WINDOW_SERVICE, wm);
        ServiceManager.addService(Context.INPUT_SERVICE, inputManager);

        mSystemServiceManager.startService(VrManagerService.class);

        mActivityManagerService.setWindowManager(wm);

        inputManager.setWindowManagerCallbacks(wm.getInputMonitor());
        inputManager.start();

        // TODO: Use service dependencies instead.
        mDisplayManagerService.windowManagerAndInputReady();

        .....
            mSystemServiceManager.startService(BluetoothService.class);
        .....

        mSystemServiceManager.startService(MetricsLoggerService.class);

        mSystemServiceManager.startService(PinnerService.class);
    } catch (RuntimeException e) {
    }
    // Bring up services needed for UI.
    if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
        mSystemServiceManager.startService(InputMethodManagerService.Lifecycle.class);

        traceBeginAndSlog("StartAccessibilityManagerService");
        try {
            ServiceManager.addService(Context.ACCESSIBILITY_SERVICE,
                    new AccessibilityManagerService(context));
        } catch (Throwable e) {
        }
    }
    if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
        if (!disableStorage &&
            !"0".equals(SystemProperties.get("system_init.startmountservice"))) {
            try {
                mSystemServiceManager.startService(MOUNT_SERVICE_CLASS);
                mountService = IMountService.Stub.asInterface(
                        ServiceManager.getService("mount"));
            } catch (Throwable e) {
                reportWtf("starting Mount Service", e);
            }
        }
    }
    mSystemServiceManager.startService(UiModeManagerService.class);
    .....

    if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
        if (!disableNonCoreServices) {
            try {
                mSystemServiceManager.startService(LOCK_SETTINGS_SERVICE_CLASS);
                lockSettings = ILockSettings.Stub.asInterface(
                        ServiceManager.getService("lock_settings"));
            } catch (Throwable e) {
            }

            if (!SystemProperties.get(PERSISTENT_DATA_BLOCK_PROP).equals("")) {
                mSystemServiceManager.startService(PersistentDataBlockService.class);
            }

            mSystemServiceManager.startService(DeviceIdleController.class);
            mSystemServiceManager.startService(DevicePolicyManagerService.Lifecycle.class);
        }

        if (!disableSystemUI) {
            try {
                statusBar = new StatusBarManagerService(context, wm);
                ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);
            } catch (Throwable e) {
            }
        }

        if (!disableNonCoreServices) {
            try {
                ServiceManager.addService(Context.CLIPBOARD_SERVICE,
                        new ClipboardService(context));
            } catch (Throwable e) {
            }
        }

        if (!disableNetwork) {
            try {
                networkManagement = NetworkManagementService.create(context);
                ServiceManager.addService(Context.NETWORKMANAGEMENT_SERVICE, networkManagement);
            } catch (Throwable e) {
            }
        }

        if (!disableNonCoreServices && !disableTextServices) {
            mSystemServiceManager.startService(TextServicesManagerService.Lifecycle.class);
        }

        if (!disableNetwork) {
            traceBeginAndSlog("StartNetworkScoreService");
            try {
                networkScore = new NetworkScoreService(context);
                ServiceManager.addService(Context.NETWORK_SCORE_SERVICE, networkScore);
            } catch (Throwable e) {
            }
            try {
                networkStats = NetworkStatsService.create(context, networkManagement);
                ServiceManager.addService(Context.NETWORK_STATS_SERVICE, networkStats);
            } catch (Throwable e) {
            }

            try {
                networkPolicy = new NetworkPolicyManagerService(
                        context, mActivityManagerService,
                        (IPowerManager)ServiceManager.getService(Context.POWER_SERVICE),
                        networkStats, networkManagement);
                ServiceManager.addService(Context.NETWORK_POLICY_SERVICE, networkPolicy);
            } catch (Throwable e) {
            }

            if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI_NAN)) {
                mSystemServiceManager.startService(WIFI_NAN_SERVICE_CLASS);
            } else {
                Slog.i(TAG, "No Wi-Fi NAN Service (NAN support Not Present)");
            }
            mSystemServiceManager.startService(WIFI_P2P_SERVICE_CLASS);
            mSystemServiceManager.startService(WIFI_SERVICE_CLASS);
            mSystemServiceManager.startService(
                        "com.android.server.wifi.scanner.WifiScanningService");

            if (!disableRtt) {
                mSystemServiceManager.startService("com.android.server.wifi.RttService");
            }

            if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_ETHERNET) ||
                mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)) {
                mSystemServiceManager.startService(ETHERNET_SERVICE_CLASS);
            }

            traceBeginAndSlog("StartConnectivityService");
            try {
                connectivity = new ConnectivityService(
                        context, networkManagement, networkStats, networkPolicy);
                ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity);
                networkStats.bindConnectivityManager(connectivity);
                networkPolicy.bindConnectivityManager(connectivity);
            } catch (Throwable e) {
            }

            try {
                serviceDiscovery = NsdService.create(context);
                ServiceManager.addService(
                        Context.NSD_SERVICE, serviceDiscovery);
            } catch (Throwable e) {
                reportWtf("starting Service Discovery Service", e);
        }

        if (!disableNonCoreServices) {
            try {
                ServiceManager.addService(Context.UPDATE_LOCK_SERVICE,
                        new UpdateLockService(context));
            } catch (Throwable e) {
            }
        }

        if (!disableNonCoreServices) {
            mSystemServiceManager.startService(RecoverySystemService.class);
        }
        ......

        mSystemServiceManager.startService(NotificationManagerService.class);
        notification = INotificationManager.Stub.asInterface(
                ServiceManager.getService(Context.NOTIFICATION_SERVICE));
        networkPolicy.bindNotificationManager(notification);

        mSystemServiceManager.startService(DeviceStorageMonitorService.class);

        if (!disableLocation) {
            try {
                location = new LocationManagerService(context);
                ServiceManager.addService(Context.LOCATION_SERVICE, location);
            } catch (Throwable e) {
            }
            try {
                countryDetector = new CountryDetectorService(context);
                ServiceManager.addService(Context.COUNTRY_DETECTOR, countryDetector);
            } catch (Throwable e) {
            }
        }

        if (!disableNonCoreServices && !disableSearchManager) {
            traceBeginAndSlog("StartSearchManagerService");
            try {
                mSystemServiceManager.startService(SEARCH_MANAGER_SERVICE_CLASS);
            } catch (Throwable e) {
            }
        }

        mSystemServiceManager.startService(DropBoxManagerService.class);

        if (!disableNonCoreServices && context.getResources().getBoolean(
                    R.bool.config_enableWallpaperService)) {
            mSystemServiceManager.startService(WALLPAPER_SERVICE_CLASS);
        }

        mSystemServiceManager.startService(AudioService.Lifecycle.class);

        if (!disableNonCoreServices) {
            mSystemServiceManager.startService(DockObserver.class);

            if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH)) {
                mSystemServiceManager.startService(THERMAL_OBSERVER_CLASS);
            }
        }
        try {
            // Listen for wired headset changes
            inputManager.setWiredAccessoryCallbacks(
                    new WiredAccessoryManager(context, inputManager));
        } catch (Throwable e) {
        }

        if (!disableNonCoreServices) {
            if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_MIDI)) {
                // Start MIDI Manager service
                mSystemServiceManager.startService(MIDI_SERVICE_CLASS);
            }

            if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)
                    || mPackageManager.hasSystemFeature(
                            PackageManager.FEATURE_USB_ACCESSORY)) {
                mSystemServiceManager.startService(USB_SERVICE_CLASS);
            }

            if (!disableSerial) {
                try {
                    // Serial port support
                    serial = new SerialService(context);
                    ServiceManager.addService(Context.SERIAL_SERVICE, serial);
                } catch (Throwable e) {
                }
            }

                    "StartHardwarePropertiesManagerService");
            try {
                hardwarePropertiesService = new HardwarePropertiesManagerService(context);
                ServiceManager.addService(Context.HARDWARE_PROPERTIES_SERVICE,
                        hardwarePropertiesService);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting HardwarePropertiesManagerService", e);
            }
        }

        mSystemServiceManager.startService(TwilightService.class);

        mSystemServiceManager.startService(JobSchedulerService.class);

        mSystemServiceManager.startService(SoundTriggerService.class);

        if (!disableNonCoreServices) {
            if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_BACKUP)) {
                mSystemServiceManager.startService(BACKUP_MANAGER_SERVICE_CLASS);
            }

            if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_APP_WIDGETS)
                || context.getResources().getBoolean(R.bool.config_enableAppWidgetService)) {
                mSystemServiceManager.startService(APPWIDGET_SERVICE_CLASS);
            }

            if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_VOICE_RECOGNIZERS)) {
                mSystemServiceManager.startService(VOICE_RECOGNITION_MANAGER_SERVICE_CLASS);
            }

            if (GestureLauncherService.isGestureLauncherEnabled(context.getResources())) {
                Slog.i(TAG, "Gesture Launcher Service");
                mSystemServiceManager.startService(GestureLauncherService.class);
            }
            mSystemServiceManager.startService(SensorNotificationService.class);
            mSystemServiceManager.startService(ContextHubSystemService.class);
        }

        try {
            ServiceManager.addService("diskstats", new DiskStatsService(context));
        } catch (Throwable e) {
        }

        if (!disableSamplingProfiler) {
            traceBeginAndSlog("StartSamplingProfilerService");
            try {
                ServiceManager.addService("samplingprofiler",
                            new SamplingProfilerService(context));
            } catch (Throwable e) {
            }
        }

        if (!disableNetwork && !disableNetworkTime) {
            traceBeginAndSlog("StartNetworkTimeUpdateService");
            try {
                networkTimeUpdater = new NetworkTimeUpdateService(context);
                ServiceManager.addService("network_time_update_service", networkTimeUpdater);
            } catch (Throwable e) {
            }
        }

        traceBeginAndSlog("StartCommonTimeManagementService");
        try {
            commonTimeMgmtService = new CommonTimeManagementService(context);
            ServiceManager.addService("commontime_management", commonTimeMgmtService);
        } catch (Throwable e) {
        }
        Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);

        if (!disableNetwork) {
            try {
                CertBlacklister blacklister = new CertBlacklister(context);
            } catch (Throwable e) {
            }
        }

        if (!disableNonCoreServices) {
            mSystemServiceManager.startService(DreamManagerService.class);
        }

        if (!disableNonCoreServices && ZygoteInit.PRELOAD_RESOURCES) {
            traceBeginAndSlog("StartAssetAtlasService");
            try {
                atlas = new AssetAtlasService(context);
                ServiceManager.addService(AssetAtlasService.ASSET_ATLAS_SERVICE, atlas);
            } catch (Throwable e) {
            }
        }

        if (!disableNonCoreServices) {
            ServiceManager.addService(GraphicsStatsService.GRAPHICS_STATS_SERVICE,
                    new GraphicsStatsService(context));
        }

        if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PRINTING)) {
            mSystemServiceManager.startService(PRINT_MANAGER_SERVICE_CLASS);
        }

        mSystemServiceManager.startService(RestrictionsManagerService.class);

        mSystemServiceManager.startService(MediaSessionService.class);

        if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_HDMI_CEC)) {
            mSystemServiceManager.startService(HdmiControlService.class);
        }

        if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LIVE_TV)) {
            mSystemServiceManager.startService(TvInputManagerService.class);
        }

        if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) {
            mSystemServiceManager.startService(MediaResourceMonitorService.class);
        }

        if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {
            mSystemServiceManager.startService(TvRemoteService.class);
        }

        if (!disableNonCoreServices) {
            traceBeginAndSlog("StartMediaRouterService");
            try {
                mediaRouter = new MediaRouterService(context);
                ServiceManager.addService(Context.MEDIA_ROUTER_SERVICE, mediaRouter);
            } catch (Throwable e) {
            }

            if (!disableTrustManager) {
                mSystemServiceManager.startService(TrustManagerService.class);
            }

            if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
                mSystemServiceManager.startService(FingerprintService.class);
            }
        }
        // LauncherAppsService uses ShortcutService.
        mSystemServiceManager.startService(ShortcutService.Lifecycle.class);

        mSystemServiceManager.startService(LauncherAppsService.class);
    }

    if (!disableNonCoreServices && !disableMediaProjection) {
        mSystemServiceManager.startService(MediaProjectionManagerService.class);
    }

    if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH)) {
        mSystemServiceManager.startService(WEAR_BLUETOOTH_SERVICE_CLASS);
    }
    mmsService = mSystemServiceManager.startService(MmsServiceBroker.class);

    // It is now time to start up the app processes...

    try {
        vibrator.systemReady();
    } catch (Throwable e) {
    }

    if (lockSettings != null) {
        try {
            lockSettings.systemReady();
        } catch (Throwable e) {
        }
    }

    // Needed by DevicePolicyManager for initialization
    mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);

    mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);

    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeWindowManagerServiceReady");
    try {
        wm.systemReady();
    } catch (Throwable e) {
    }
    try {
        // TODO: use boot phase
        mPowerManagerService.systemReady(mActivityManagerService.getAppOpsService());
    } catch (Throwable e) {
    }

    try {
        mPackageManagerService.systemReady();
    } catch (Throwable e) {
    }

    try {
        // TODO: use boot phase and communicate these flags some other way
        mDisplayManagerService.systemReady(safeMode, mOnlyCore);
    } catch (Throwable e) {
    }
    mActivityManagerService.systemReady(new Runnable() {
        @Override
        public void run() {
            try {
                startSystemUi(context);
            } catch (Throwable e) {
            }
            "MakeNetworkManagementServiceReady");
            try {
                if (networkManagementF != null) networkManagementF.systemReady();
            } catch (Throwable e) {
                reportWtf("making Network Managment Service ready", e);
            }
            "MakeNetworkStatsServiceReady");
            try {
                if (networkStatsF != null) networkStatsF.systemReady();
            } catch (Throwable e) {
            }
            try {
                if (networkPolicyF != null) networkPolicyF.systemReady();
            } catch (Throwable e) {
                reportWtf("making Network Policy Service ready", e);
            }
            "MakeConnectivityServiceReady");
            try {
                if (connectivityF != null) connectivityF.systemReady();
            } catch (Throwable e) {
            }
            Watchdog.getInstance().start();

            try {
                if (locationF != null) locationF.systemRunning();
            } catch (Throwable e) {
            }
            try {
                if (countryDetectorF != null) countryDetectorF.systemRunning();
            } catch (Throwable e) {
            }
            try {
                if (networkTimeUpdaterF != null) networkTimeUpdaterF.systemRunning();
            } catch (Throwable e) {
            }
            try {
                if (commonTimeMgmtServiceF != null) {
                    commonTimeMgmtServiceF.systemRunning();
                }
            } catch (Throwable e) {
            }
            try {
                if (atlasF != null) atlasF.systemRunning();
            } catch (Throwable e) {
            }
            try {
                // TODO(BT) Pass parameter to input manager
                if (inputManagerF != null) inputManagerF.systemRunning();
            } catch (Throwable e) {
            }
            try {
                if (telephonyRegistryF != null) telephonyRegistryF.systemRunning();
            } catch (Throwable e) {
                reportWtf("Notifying TelephonyRegistry running", e);
            }
            try {
                if (mediaRouterF != null) mediaRouterF.systemRunning();
            } catch (Throwable e) {
            }

            try {
                if (mmsServiceF != null) mmsServiceF.systemRunning();
            } catch (Throwable e) {
            }

            try {
                if (networkScoreF != null) networkScoreF.systemRunning();
            } catch (Throwable e) {
            }
        }
    });
}

這個方法中啟動的service非常多,程式碼量非常巨大,所以可見,這個方法對於Android系統而言,不言也可知其重要性。由於程式碼量巨大,將startOtherServices()分成三部分解說:

1.startOtherServices()中啟動了那些服務

  • SchedulingPolicyService
  • TelecomLoaderService
  • TelephonyRegistry
  • CameraService
  • AccountManagerService$Lifecycle
  • ContentService$Lifecycle
  • VibratorService
  • ConsumerIrService
  • AlarmManagerService
  • InputManagerService
  • WindowManagerService
  • VrManagerService
  • MetricsLoggerService
  • PinnerService
  • InputMethodManagerService
  • AccessibilityManagerService
  • MountService$Lifecycle
  • UiModeManagerService
  • LockSettingsService$Lifecycle
  • PersistentDataBlockService
  • DeviceIdleController
  • DevicePolicyManagerService
  • StatusBarManagerService
  • ClipboardService
  • NetworkManagementService
  • TextServicesManagerService
  • NetworkScoreService
  • NetworkStatsService
  • NetworkPolicyManagerService
  • WifiNanService
  • WifiP2pService
  • WifiService
  • WifiScanningService
  • RttService
  • EthernetService
  • ConnectivityService
  • NsdService
  • UpdateLockService
  • RecoverySystemService
  • NotificationManagerService
  • DeviceStorageMonitorService
  • LocationManagerService
  • CountryDetectorService
  • SearchManagerService$Lifecycle
  • DropBoxManagerService
  • WallpaperManagerService$Lifecycle
  • AudioService.Lifecycle
  • DockObserver
  • ThermalObserver
  • MidiService$Lifecycle
  • UsbService$Lifecycle
  • SerialService
  • HardwarePropertiesManagerService
  • TwilightService
  • JobSchedulerService
  • SoundTriggerService
  • BackupManagerService$Lifecycle
  • AppWidgetService
  • VoiceInteractionManagerService
  • GestureLauncherService
  • SensorNotificationService
  • ContextHubSystemService
  • DiskStatsService
  • SamplingProfilerService
  • NetworkTimeUpdateService
  • CommonTimeManagementService
  • DreamManagerService
  • AssetAtlasService
  • GraphicsStatsService
  • PrintManagerService
  • RestrictionsManagerService
  • MediaSessionService
  • HdmiControlService
  • TvInputManagerService
  • MediaResourceMonitorService
  • TvRemoteService
  • MediaRouterService
  • TrustManagerService
  • FingerprintService
  • ShortcutService.Lifecycle
  • LauncherAppsService
  • MediaProjectionManagerService
  • WearBluetoothService
  • MmsServiceBroker

所列的這些服務,不一定全部都啟動,系統會依照一些配置,選擇性啟動某些服務。如,因為Android系統會用於眾多裝置,手機,電視等等,當Android安裝到電視裝置是,TvInputManagerService、TvRemoteService這些service才會被啟動,相反,手機裝置時,這兩個服務就不會被啟動了。

2.不同的啟動服務的方式

不知讀者是否注意到,在startOtherServices()中存在和startBootstrapServices()、startCoreServices()中不同的啟動service的方法,在startBootstrapServices()、startCoreServices()中見到SystemServiceManager.startService()和LocalServices.addService()的方式,而startOtherServices()中又多了ServiceManager.addService(),這三種方式有什麼不同呢?

  1. 型別不同 
    SystemServiceManager.startService()和LocalServices.addService()啟動的系統服務是SystemService的子類,啟動這些服務後會回撥SystemService的onStart()方法。ServiceManager.addService()啟動的系統服務是實現了Android IPC 的Binder的子類,這些服務啟動後會呼叫systemReady()或systemRunning()方法。

  2. SystemServiceManager.startService()和ServiceManager.addService()中啟動的服務需要Binder物件,而LocalServices.addService()卻沒有Binder物件。

  3. SystemServiceManager.startService()中啟動的是需要關心lifecycle events的服務,而ServiceManager.addService()和LocalServices.addService()不關心lifecycle events。

  4. ServiceManager.addService()啟動的服務本身是實現Binder通訊的子類,而一般SystemServiceManager.startService()啟動的服務是某個服務的內部類且這個內部類是SystemService的子類,如BackupManagerService$Lifecycle,在啟動這個Lifecycle的內部類服務時,當回撥onStart()方法時通過SystemService的publishBinderService()方法應用某個服務的Binder物件,且這個Binder的實現類也是某個服務的內部類。也就是說需要啟動服務,而這個服務需要關心lifecycle events,所以不能通過ServiceManager.addService()的方式啟動,然後在這個服務中宣告一個實現了SystemService的子類Lifecycle,來接受lifecycle events,通過SystemServiceManager.startService()的方式啟動這個服務,在SystemService的回撥方法onStart()中應用這個服務的Binder物件。所以通過SystemServiceManager.startService()啟動的服務,實際是啟動了一個即需要關心lifecycle events,也需要像ServiceManager.addService()那樣需要Binder物件的服務。

所以,其實在startBootstrapServices()中就已經通過ServiceManager.addService()的方式啟動了一些特別特別重要的服務,如:

    private void startBootstrapServices() {
        mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
            mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
    }


    public static PackageManagerService main(Context context, Installer installer,
        boolean factoryTest, boolean onlyCore) {
        ......
        ServiceManager.addService("package", m);
        return m;
    }

3.通過ServiceManager.addService()啟動的服務,會呼叫服務的systemReady()或systemRunning()方法,初始化一些需要在系統服務啟動後的其它程式碼。如啟動SystemUI。

全部啟動所需要的服務以後,SystemServer便要進入了接受Message的迴圈中,等待Message的事件。

總結

在本大綱中,認識了Android系統啟動時需要啟動的服務,以及

  • SystemServiceManager.startService()
  • ServiceManager.addService()
  • LocalServices.addService()

三種不同的啟動系統服務的方式,通過這三種啟動的服務各有什麼不同。另外,Android系統除了在啟動的時候可以初始化服務,在執行中,也可能有新的服務被加進來,如某些APP啟動時,會增加一些服務,如Phone APP(Telephony)

public void onCreate() {
        phoneMgr = PhoneInterfaceManager.init(this, PhoneFactory.getDefaultPhone());
}

static PhoneInterfaceManager init(PhoneGlobals app, Phone phone) {
    synchronized (PhoneInterfaceManager.class) {
        if (sInstance == null) {
            sInstance = new PhoneInterfaceManager(app, phone);
        ......
        return sInstance;
    }
}

private PhoneInterfaceManager(PhoneGlobals app, Phone phone) {
    publish();
}

private void publish() {
    ServiceManager.addService("phone", this);
}

到此,System Server的大綱介紹到這裡