Android Framework Development Guide

Android ConnectivityService

简介

在旧的Android系统,connecttivityService是在systemserver.java的init2中new,然后WiFiService是在connecttivityService中new。

 try {
        Log.i(TAG, "Starting Connectivity Service.");
        ServiceManager.addService(Context.CONNECTIVITY_SERVICE, new
ConnectivityService(context));
      } catch (Throwable e) {
        Log.e(TAG, "Failure starting Connectivity Service", e);
}

在Android5.0,系统的启动被改写了,没有之前init1,和init2了,connecttivityService是在startOtherServices()中创建启动,WifiService则是在startOtherServices()里通过starService()注册启动。

 private static final String WIFI_SERVICE_CLASS =
            "com.android.server.wifi.WifiService";

mSystemServiceManager.startService(WIFI_SERVICE_CLASS);

connectivity = new ConnectivityService(
            context, networkManagement, networkStats, networkPolicy);
ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity);

在starService函数中,通过包名参数,会将ServiceManager注册到ServiceManager中。

 public <T extends SystemService> T startService(Class<T> serviceClass) {
        final String name = serviceClass.getName();
        Slog.i(TAG, "Starting " + 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;
     }