转:Android系统之System Server大纲

Android系统之System Server大纲

System Server content

前言

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的大纲介绍到这里,在本大纲的牵引下,一一以分文章(文档)的形式对各个系统服务进入全面的了解。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,227评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,755评论 1 298
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,899评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,257评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,617评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,757评论 1 221
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,982评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,715评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,454评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,666评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,148评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,512评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,156评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,112评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,896评论 0 198
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,809评论 2 279
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,691评论 2 272

推荐阅读更多精彩内容