android系列-SystemServer创建服务

SystemServer会开启很多服务,这些服务的创建流程类似,以Installer为例子

1.startBootstrapServices 

//frameworks\base\services\java\com\android\server\SystemServer.java

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

2.startService

通过反射创建service

//android10\frameworks\base\services\core\java\com\android\server\SystemServiceManager.java

    @SuppressWarnings("unchecked")
    public  T startService(Class serviceClass) {
        try {
            final String name = serviceClass.getName();//要创建的服务的类名

            final T service;
            try {
                //通过反射创建服务
                Constructor constructor = serviceClass.getConstructor(Context.class);
                service = constructor.newInstance(mContext);
            } catch (InstantiationException ex) {
                //......
            } catch (IllegalAccessException ex) {
                //......
            } catch (NoSuchMethodException ex) {
                //......
            } catch (InvocationTargetException ex) {
                //......
            }

            startService(service);
            return service;
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
        }
    }

3.startService

调用service的onStart方法

//android10\frameworks\base\services\core\java\com\android\server\SystemServiceManager.java

    // Services that should receive lifecycle events.
    private final ArrayList mServices = new ArrayList();

    //Installer服务继承自SystemService
    public void startService(@NonNull final SystemService service) {
        // Register it.
        mServices.add(service); //添加到ArrayList

        // Start it.
        try {
            service.onStart();//调用service的onStart方法
        } catch (RuntimeException ex) {
            //......
        }
    }

你可能感兴趣的:(Android,android)