Android Framework学习八:SystemServer及startService原理

SystemServer、SystemServiceManger、SystemService、serviceManager的关系

在这里插入图片描述

  • 管理机制:SystemServer 通过 SystemServiceManager 管理所有实现了 SystemService 的服务。每个服务初始化后会将自身注册到 ServiceManager,以实现跨进程调用 。
  • SystemServer 进程:它是一个包含众多服务的进程,像常见的 AMS(Activity Manager Service,活动管理器服务 )、PKMS(Package Manager Service,包管理器服务 )、WMS(Window Manager Service,窗口管理器服务 )等,大概有 80 多个。
  • SystemServiceManager 作用:专门用于管理 SystemServer 中的服务,这些服务基本都实现了 SystemService 类,使得 SystemServiceManager 能够对其进行管理 。
  • App 调用方式:当 App 需要调用 systemService 时,在 SystemServer 启动 AMS、WMS、PKMS 等服务时,会将它们添加到 ServiceManager 中,供外部 app 进程调用。ServiceManager 是独立进程,负责管理服务列表。
    在这里插入图片描述

SystemServer进程的执行

在这里插入图片描述
frameworks/base/services/java/com/android/server/SystemServer.java

    /**
     * The main entry point from zygote.
     */
    public static void main(String[] args) {
        new SystemServer().run();
    }

    private void run() {
    ...
        // Initialize native services.
        System.loadLibrary("android_servers");
    ...
        // Initialize the system context.
        createSystemContext();

       // Call per-process mainline module initialization.
       ActivityThread.initializeMainlineModules();
       
       // Create the system service manager.
       mSystemServiceManager = new SystemServiceManager(mSystemContext);
       ...
        // Start services.
        try {
            t.traceBegin("StartServices");
            startBootstrapServices(t);
            startCoreServices(t);
            startOtherServices(t);
            startApexServices(t);
        } catch (Throwable ex) {
            Slog.e("System", "******************************************");
            Slog.e("System", "************ Failure starting system services", ex);
            throw ex;
        } finally {
            t.traceEnd(); // StartServices
        }
    }

包含的Service

在这里插入图片描述
startBootstrapServices

    /**
     * Starts the small tangle of critical services that are needed to get the system off the
     * ground.  These services have complex mutual dependencies which is why we initialize them all
     * in one place here.  Unless your service is also entwined in these dependencies, it should be
     * initialized in one of the other functions.
     */
    private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
        ....
        // FileIntegrityService responds to requests from apps and the system. It needs to run after
        // the source (i.e. keystore) is ready, and before the apps (or the first customer in the
        // system) run.
        mSystemServiceManager.startService(FileIntegrityService.class);

        // 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.
        Installer installer = mSystemServiceManager.startService(Installer.class);

        // In some cases after launching an app we need to access device identifiers,
        // therefore register the device identifier policy before the activity manager.
        mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);

        // Uri Grants Manager.
        mSystemServiceManager.startService(UriGrantsManagerService.Lifecycle.class);

        // Tracks rail data to be used for power statistics.
        mSystemServiceManager.startService(PowerStatsService.class);
      ...
   }

startCoreServices

    /**
     * Starts some essential services that are not tangled up in the bootstrap process.
     */
    private void startCoreServices(@NonNull TimingsTraceAndSlog t) {
        t.traceBegin("startCoreServices");

        // Service for system config
        t.traceBegin("StartSystemConfigService");
        mSystemServiceManager.startService(SystemConfigService.class);
        t.traceEnd();

        t.traceBegin("StartBatteryService");
        // Tracks the battery level.  Requires LightService.
        mSystemServiceManager.startService(BatteryService.class);
        t.traceEnd();

        // Tracks application usage stats.
        t.traceBegin("StartUsageService");
        mSystemServiceManager.startService(UsageStatsService.class);
        mActivityManagerService.setUsageStatsManager(
                LocalServices.getService(UsageStatsManagerInternal.class));
        t.traceEnd();

        // Tracks whether the updatable WebView is in a ready state and watches for update installs.
        if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {
            t.traceBegin("StartWebViewUpdateService");
            mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
            t.traceEnd();
        }

        // Tracks and caches the device state.
        t.traceBegin("StartCachedDeviceStateService");
        mSystemServiceManager.startService(CachedDeviceStateService.class);
        t.traceEnd();

        // Tracks cpu time spent in binder calls
        t.traceBegin("StartBinderCallsStatsService");
        mSystemServiceManager.startService(BinderCallsStatsService.LifeCycle.class);
        t.traceEnd();
    ...
    }

在这里插入图片描述
在这里插入图片描述

    /**
     * Starts a miscellaneous grab bag of stuff that has yet to be refactored and organized.
     */
    private void startOtherServices(@NonNull TimingsTraceAndSlog t) {
    ...
                ServiceManager.addService("sec_key_att_app_id_provider",
                    new KeyAttestationApplicationIdProviderService(context));
            t.traceEnd();

            t.traceBegin("StartKeyChainSystemService");
            mSystemServiceManager.startService(KeyChainSystemService.class);
            t.traceEnd();

            t.traceBegin("StartBinaryTransparencyService");
            mSystemServiceManager.startService(BinaryTransparencyService.class);
            t.traceEnd();

            t.traceBegin("StartSchedulingPolicyService");
            ServiceManager.addService("scheduling_policy", new SchedulingPolicyService());
            t.traceEnd();

            // TelecomLoader hooks into classes with defined HFP logic,
            // so check for either telephony or microphone.
            if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_MICROPHONE)
                    || mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELECOM)
                    || mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
                t.traceBegin("StartTelecomLoaderService");
                mSystemServiceManager.startService(TelecomLoaderService.class);
                t.traceEnd();
            }

            t.traceBegin("StartTelephonyRegistry");
            telephonyRegistry = new TelephonyRegistry(
                    context, new TelephonyRegistry.ConfigurationProvider());
            ServiceManager.addService("telephony.registry", telephonyRegistry);
            t.traceEnd();

            t.traceBegin("StartEntropyMixer");
            mEntropyMixer = new EntropyMixer(context);
            t.traceEnd();

            mContentResolver = context.getContentResolver();

            // The AccountManager must come before the ContentService
            t.traceBegin("StartAccountManagerService");
            mSystemServiceManager.startService(ACCOUNT_SERVICE_CLASS);
            t.traceEnd();
        ...
    }

安卓13中,手动查询SystemServer中的service数量,如下有183个:

cat frameworks/base/services/java/com/android/server/SystemServer.java | grep startService | wc -l
183

SystemServer启动服务的流程

在这里插入图片描述

startService

所有的服务都是通过这个函数启动的

  1. getConstructor是调的反射进行service构造
    在这里插入图片描述
  2. service创建后,会调用publishBinderService把它注册到serviceManager中
    在这里插入图片描述
  3. 通过addService把service添加到sLocalServiceObjects中
    在这里插入图片描述

startService的流程:
在这里插入图片描述
startServicer用反射:方便扩展及管理,不然90个service就要实现90种创建的接口。
publishBinderService:注册到serviceManager中,由它统一管理。
addService到LocalServices: 方便Framework层平级的调用。

上层调用service,是通过binder来访问其中功能的,如下图,具体可以参照另外一篇binder的文章
在这里插入图片描述

Framework学习系列文章

Android Framework学习一:系统框架、启动过程
Android Framework学习二:Activity创建及View绘制流程
Android Framework学习三:zygote
Android Framework学习四:APP速度优化
Android Framework学习五:APP启动过程原理及速度优化
Android Framework学习六:Binder原理
Android Framework学习七:Handler、Looper、Message
Android Framework学习八:SystemServer及startService原理
作者:帅得不敢出门

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

帅得不敢出门

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值