SystemServer类解析

SystemServer类解析

安卓系统有一个system_server进程,该进程由zygote进程创建,负责运行所有的系统服务,该进程的入口类是frameworks/base/services/java/com/android/server/SystemServer.java。下面来解析一下该类的主要功能。

该类有一个main方法,说起main方法学过java的都熟悉,main方法是一段java程序的入口,也可以说是一个java进程的入口。我们来看一下该方法源码(源码版本是android 7.1.1):

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

从该方法的源码可知,该main方法是zygote创建system_server进程的入口,方法里面只是新创建了SystemServer对象,然后调用其run方法。

我们来看一下SystemServer.run()都干了什么:

private void run() {
         //此处省略n行代码
        // 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);
        }

       //此处省略n行代码

    }

run方法我们只看与服务调度有关的逻辑,其他逻辑屏蔽掉。从上面代码看,run方法会调用三个startService方法来分别启动不同性质的服务:startBootstrapSerivces()、startCoreServices()、startOtherServices()。

1.startBootstrapSerivces()

/**
     * 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() {
        // 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);

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

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

        // Now that the power manager has been started, let the activity manager
        // initialize power management features.
        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);

        // Only run "core" apps if we're encrypting the device.
        String cryptState = SystemProperties.get("vold.decrypt");
        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.
        traceBeginAndSlog("StartPackageManagerService");
        mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
                mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
        mFirstBoot = mPackageManagerService.isFirstBoot();
        mPackageManager = mSystemContext.getPackageManager();
        Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);

        // 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 {
                    OtaDexoptService.main(mSystemContext, mPackageManagerService);
                } catch (Throwable e) {
                    reportWtf("starting OtaDexOptService", e);
                } finally {
                    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
                }
            }
        }

        traceBeginAndSlog("StartUserManagerService");
        mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
        Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);

        // Initialize attribute cache used to cache resources from packages.
        AttributeCache.init(mSystemContext);

        // Set up the Application instance for the system process and get started.
        mActivityManagerService.setSystemProcess();

        // The sensor service needs access to package manager service, app ops
        // service, and permissions service, therefore we start it after them.
        startSensorService();
    }

先看一下爱该方法的注释,可知该方法启动一些极重要的services,这些服务相互依赖,所以统一在这里进行初始化。再看一下方法里面的代码,创建了一个Installer、ActivityManagerService、PowerManagerService、DisplayManagerService、PackageManagerService、UserManagerService等,ActivityManagerService和Installer、PowerManagerService是有关联的:

mActivityManagerService.setInstaller(installer);
mActivityManagerService.initPowerManagement();

这些服务都是继承了一个叫SystemService的抽象类,该抽象类里面定义了一个抽象方法onStart,系统服务实现这个方法。SystemServiceManager.startService最终调用的就是这个onStart方法来启动系统服务,来看一下源码吧:

/**
     * Starts a service by class name.
     *
     * @return The service instance.
     */
    @SuppressWarnings("unchecked")
    public SystemService startService(String className) {
        final Class<SystemService> serviceClass;
        try {
            serviceClass = (Class<SystemService>)Class.forName(className);
        } catch (ClassNotFoundException ex) {
            Slog.i(TAG, "Starting " + className);
            throw new RuntimeException("Failed to create service " + className
                    + ": service class not found, usually indicates that the caller should "
                    + "have called PackageManager.hasSystemFeature() to check whether the "
                    + "feature is available on this device before trying to start the "
                    + "services that implement it", ex);
        }
        return startService(serviceClass);
    }

    /**
     * Creates and starts a system service. The class must be a subclass of
     * {@link com.android.server.SystemService}.
     *
     * @param serviceClass A Java class that implements the SystemService interface.
     * @return The service instance, never null.
     * @throws RuntimeException if the service fails to start.
     */
    @SuppressWarnings("unchecked")
    public <T extends SystemService> T startService(Class<T> serviceClass) {
        try {
            final String name = serviceClass.getName();
            Slog.i(TAG, "Starting " + name);
            Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + name);

            // Create the service.
            if (!SystemService.class.isAssignableFrom(serviceClass)) {
                throw new RuntimeException("Failed to create " + name
                        + ": service must extend " + SystemService.class.getName());
            }
            final T service;
            try {
                Constructor<T> constructor = serviceClass.getConstructor(Context.class);
                service = constructor.newInstance(mContext);
            } catch (InstantiationException ex) {
                throw new RuntimeException("Failed to create service " + name
                        + ": service could not be instantiated", ex);
            } catch (IllegalAccessException ex) {
                throw new RuntimeException("Failed to create service " + name
                        + ": service must have a public constructor with a Context argument", ex);
            } catch (NoSuchMethodException ex) {
                throw new RuntimeException("Failed to create service " + name
                        + ": service must have a public constructor with a Context argument", ex);
            } catch (InvocationTargetException ex) {
                throw new RuntimeException("Failed to create service " + name
                        + ": service constructor threw an exception", ex);
            }

            // Register it.
            mServices.add(service);

            // Start it.
            try {
                service.onStart();
            } catch (RuntimeException ex) {
                throw new RuntimeException("Failed to start service " + name
                        + ": onStart threw an exception", ex);
            }
            return service;
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
        }
    }

我们以Installer服务来举例说明启动流程,看一下其onStart方法实现:

@Override
    public void onStart() {
        Slog.i(TAG, "Waiting for installd to be ready.");
        mInstaller.waitForConnection();
    }

2 startCoreServices()

/**
     * Starts some essential services that are not tangled up in the bootstrap process.
     */
    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);
    }

发方法里面启动了BateerService、UsageStatsService、WebViewUpdateService。

我们来看一下BatteryService的onStart方法:

 @Override
    public void onStart() {
        IBinder b = ServiceManager.getService("batteryproperties");
        final IBatteryPropertiesRegistrar batteryPropertiesRegistrar =
                IBatteryPropertiesRegistrar.Stub.asInterface(b);
        try {
            batteryPropertiesRegistrar.registerListener(new BatteryListener());
        } catch (RemoteException e) {
            // Should never happen.
        }

        mBinderService = new BinderService();
        publishBinderService("battery", mBinderService);
        publishLocalService(BatteryManagerInternal.class, new LocalService());
    }

我们注意一下publishBinderService方法,这个方法的定义SystemService抽象类中,我们看一下其定义:

/**
     * Publish the service so it is accessible to other services and apps.
     */
    protected final void publishBinderService(String name, IBinder service) {
        publishBinderService(name, service, false);
    }

    /**
     * Publish the service so it is accessible to other services and apps.
     */
    protected final void publishBinderService(String name, IBinder service,
            boolean allowIsolated) {
        ServiceManager.addService(name, service, allowIsolated);
    }

我们再看一下ServiceManager的addService方法:

/**
     * Place a new @a service called @a name into the service
     * manager.
     * 
     * @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
     */
    public static void addService(String name, IBinder service, boolean allowIsolated) {
        try {
            getIServiceManager().addService(name, service, allowIsolated);
        } catch (RemoteException e) {
            Log.e(TAG, "error in addService", e);
        }
    }

该方法调用了ServiceManagerNative.addService方法:

public void addService(String name, IBinder service, boolean allowIsolated)
            throws RemoteException {
        Parcel data = Parcel.obtain();
        Parcel reply = Parcel.obtain();
        data.writeInterfaceToken(IServiceManager.descriptor);
        data.writeString(name);
        data.writeStrongBinder(service);
        data.writeInt(allowIsolated ? 1 : 0);
        mRemote.transact(ADD_SERVICE_TRANSACTION, data, reply, 0);
        reply.recycle();
        data.recycle();
    }

然后是跟Native层的服务交互了。此处把service添加到了ServiceManagerNative里面了,getSystemService方法获取系统服务的时候会用到此处逻辑,参考getSystemService追根溯源

3 startOtherServices()

ServiceManager.addService("scheduling_policy", new SchedulingPolicyService());
            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
mSystemServiceManager.startService(TelecomLoaderService.class);

startOtherServices方法里面启动了很多服务,启动方式有两种,如上段代码所示,一种是直接new一个服务对象,然后调用ServiceManager.addService方法添加到ServiceManagerNative中,这种方式启动的服务一般是继承了某个接口的Stub类;另一种是通过SystemServiceManager.startService方法来启动,这种服务是继承了SystemService抽象类。

另外补充一下,在run方法里面创建了Looper,可见该进程通信也是使用Handler的。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
SystemServer 是 Android 系统启动过程中的关键组件之一,它负责启动和管理系统中的各种服务和进程。SystemServer 的主要功能如下: 1. 启动 Android 系统中的各种系统服务,如 ActivityManagerService、PackageManagerService、WindowManagerService 等; 2. 初始化和启动 Zygote 进程,该进程将作为应用程序进程的父进程; 3. 启动系统中的各种进程,如系统进程、系统应用进程等; 4. 加载和初始化 Android 系统的各种服务和组件。 下面是 SystemServer 的源码解析: 1. SystemServer 的入口 SystemServer 的入口在 frameworks/base/services/java/com/android/server/SystemServer.java 文件中。在该文件中,SystemServer 继承了 Binder 和 Runnable 接口,并且实现了 Runnable 接口的 run() 方法,该方法是 SystemServer 的入口。 在 run() 方法中,SystemServer 执行了以下操作: 1.1. 初始化 SystemServer 的环境 SystemServer 首先初始化自己的环境,包括设置系统属性、设置线程优先级等。 1.2. 启动各种系统服务 SystemServer 启动 Android 系统中的各种系统服务,包括 ActivityManagerService、PackageManagerService、WindowManagerService 等。这些服务都是在 SystemServer 的构造方法中创建的。 1.3. 初始化和启动 Zygote 进程 SystemServer 初始化和启动 Zygote 进程,该进程将作为应用程序进程的父进程。具体而言,SystemServer 调用 Zygote 的 main() 方法启动 Zygote 进程,并且设置 Zygote 的命令行参数。 1.4. 启动系统中的各种进程 SystemServer 启动 Android 系统中的各种进程,包括系统进程、系统应用进程等。具体而言,SystemServer 调用 ActivityManagerService 的 startSystemServer() 方法启动系统进程,并且调用 PackageManagerService 的 scanDirTracedLI() 方法扫描系统应用。 1.5. 加载和初始化 Android 系统的各种服务和组件 SystemServer 加载和初始化 Android 系统的各种服务和组件,包括 SystemUI、Launcher、InputMethodService 等。具体而言,SystemServer 调用 ActivityManagerService 的 startHomeActivity() 方法启动 Launcher,并且调用 PackageManagerService 的 packageInstalled() 方法加载和初始化应用程序。 2. SystemServer 的启动流程 SystemServer 的启动流程如下: 2.1. 启动 init 进程 在 Android 系统启动过程中,init 进程是第一个进程。init 进程启动时,会执行 init.rc 脚本中的命令,并且启动 SystemServer 进程。 2.2. 创建 SystemServer 进程 SystemServer 进程是在 init.rc 脚本中通过 service 命令创建的。具体而言,init.rc 脚本中会执行以下命令: ``` service system_server /system/bin/app_process -Xbootclasspath:/system/framework/core-libart.jar:/system/framework/conscrypt.jar:/system/framework/okhttp.jar:/system/framework/bouncycastle.jar:/system/framework/apache-xml.jar:/system/framework/core-junit.jar -classpath /system/framework/services.jar com.android.server.SystemServer ``` 该命令会启动 SystemServer 进程,并且设置 SystemServer 的启动参数。 2.3. 执行 SystemServer 的 run() 方法 当 SystemServer 进程启动后,会执行 SystemServer 的 run() 方法。在 run() 方法中,SystemServer 完成了 Android 系统的初始化和启动过程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Android海纳百川

打赏加微信,送跑车加管理

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

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

打赏作者

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

抵扣说明:

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

余额充值