美文网首页
Android SystemServiceManager 介绍

Android SystemServiceManager 介绍

作者: ZZH的Android | 来源:发表于2020-07-25 21:38 被阅读0次

    代码位置:frameworks/base/services/core/java/com/android/server/SystemServiceManager.java
    顾名思义,SystemServiceManager是管理SystemService的,这么说还不够严谨,应该说是管理继承了SystemService的类的,这个从注释中可以看到。

        /**
          * Manages creating, starting, and other lifecycle events of
          * {@link com.android.server.SystemService system services}.
         *
         * {@hide}
         */
    

    这个类在SystemServer中被大量用到,主要用于开机时的各种系统服务的初始化和配置工作。

    接下来看下具体实现:

        private static final String TAG = "SystemServiceManager";
        // 这个是操作service的一个延时提醒,如果对一个service的某个操作超过了这个值,Log中就会有日志
        // 输出,这个一会看warnIfTooLong函数时会看到 
        private static final int SERVICE_CALL_WARN_TIME_MS = 50;
    
        private final Context mContext;
        private boolean mSafeMode;
        private boolean mRuntimeRestarted;
    
        // 管理的所有继承SystemService的类的集合
        // Services that should receive lifecycle events.
        private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();
    
        private int mCurrentPhase = -1;
    
        SystemServiceManager(Context context) {
            mContext = context;
        }
    

    其中最重要的一个函数为startService,这里传入的是一个String类型的className,然后通过反射的方法得到具体的类(为什么要用反射呢?稍后有说明)

        /**
         * 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);
                // 注意这里的异常提示信息,前面我们抛出一个疑问,为什么startService要用反射
                // 构造Service呢?从这里的异常信息我们可以看出,如果当前设备有些featrue不支
                // 持的话,对应的Service类很可能不存在,如果直接引用的话编译就会报错。这里
                // 用反射的话,就可以避免因为编译报错而去修改代码,这样适配性也高。
                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);
        }
    
        /**
         * 下面这句话说参数必须是SystemService类的子类
         * 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.
                // isAssignableFrom函数的作用是判断是否为子类
                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);
                }
                
                // 这里就是真正执行启动service了
                startService(service);
                return service;
            } finally {
                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
            }
        }
    
        public void startService(@NonNull final SystemService service) {
            // Register it.
            // 将要启动的service加到mService列表中
            mServices.add(service);
            // Start it.
            long time = System.currentTimeMillis(); // 记录开始操作的时间
            try {
                service.onStart(); // 调用要启动的service的 onStart方法
            } catch (RuntimeException ex) {
                throw new RuntimeException("Failed to start service " + service.getClass().getName()
                        + ": onStart threw an exception", ex);
            }
            // 记录上述操作执行的时间,如果超时,会有warning提示
            warnIfTooLong(System.currentTimeMillis() - time, service, "onStart");
        }
    
        // 可以看到,如果对Service的某个操作超过了SERVICE_CALL_WARN_TIME_MS(50ms),Log中就会有warning提示
        private void warnIfTooLong(long duration, SystemService service, String operation) {
            if (duration > SERVICE_CALL_WARN_TIME_MS) {
                Slog.w(TAG, "Service " + service.getClass().getName() + " took " + duration + " ms in "
                        + operation);
            }
        }
    

    到此,SystemServiceManager的主要内容就介绍完了,还有剩下的一些对Service的操作都是类似的,循环遍历mService列表并回调相应的函数,比如:

        /**
         * Starts the specified boot phase for all system services that have been started up to
         * this point.
         *
         * @param phase The boot phase to start.
         */
        public void startBootPhase(final int phase) {
            if (phase <= mCurrentPhase) {
                throw new IllegalArgumentException("Next phase must be larger than previous");
            }
            mCurrentPhase = phase;
    
            Slog.i(TAG, "Starting phase " + mCurrentPhase);
            try {
                Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "OnBootPhase " + phase);
                final int serviceLen = mServices.size();
                 // 遍历mService并调用service的onBootPhase函数
                for (int i = 0; i < serviceLen; i++) {
                    final SystemService service = mServices.get(i);
                    long time = System.currentTimeMillis();
                    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, service.getClass().getName());
                    try {
                        service.onBootPhase(mCurrentPhase);
                    } catch (Exception ex) {
                        throw new RuntimeException("Failed to boot service "
                                + service.getClass().getName()
                                + ": onBootPhase threw an exception during phase "
                                + mCurrentPhase, ex);
                    }
                    // 如果操作延时则打印warning日志
                    warnIfTooLong(System.currentTimeMillis() - time, service, "onBootPhase");
                    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
                }
            } finally {
                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
            }
        }
    

    相关文章

      网友评论

          本文标题:Android SystemServiceManager 介绍

          本文链接:https://www.haomeiwen.com/subject/upjmlktx.html