Android -- 网络相关的系统服务启动简要分析

Android --  网络相关的系统服务启动简要分析

转自http://blog.csdn.net/csdn_of_coder/article/details/51636855
Android中众多的系统服务都是在SystemServer中启动的,一般有两种方式:
  1. SystemServiceManager.startServcie()
  2. ServiceManageraddService()
前一种方式也是通过后者将一个服务添加到Android的服务体系中的。我们知道,Android的服务体系都是基于Binder来实现的;Java代码里调用的这些启动、添加服务的方法,实际上是对底层C++实现的服务体系的代码封装,这里我们不做深入探讨。
我们以EthernetService为例,简单介绍下该服务的启动过程。进入SystemServer:
  1. private static final String ETHERNET_SERVICE_CLASS =  
  2.             "com.android.server.ethernet.EthernetService";  
  1. if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_ETHERNET) ||  
  2.                     mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)) {  
  3.                     mSystemServiceManager.startService(ETHERNET_SERVICE_CLASS);  
  4. }  
如果支持Ethernet,则会调用SystemServiceManager.startService()方法开启服务:
  1. /** 
  2.     * Starts a service by class name. 
  3.     * 
  4.     * @return The service instance. 
  5.     */  
  6.    @SuppressWarnings("unchecked")  
  7.    public SystemService startService(String className) {  
  8.        final Class<SystemService> serviceClass;  
  9.        try {  
  10.            serviceClass = (Class<SystemService>)Class.forName(className);  
  11.        } catch (ClassNotFoundException ex) {  
  12.            Slog.i(TAG, "Starting " + className);  
  13.            throw new RuntimeException("Failed to create service " + className  
  14.                    + ": service class not found, usually indicates that the caller should "  
  15.                    + "have called PackageManager.hasSystemFeature() to check whether the "  
  16.                    + "feature is available on this device before trying to start the "  
  17.                    + "services that implement it", ex);  
  18.        }  
  19.        return startService(serviceClass);  
  20.    }  
  21.   
  22.    /** 
  23.     * Creates and starts a system service. The class must be a subclass of 
  24.     * {@link com.android.server.SystemService}. 
  25.     * 
  26.     * @param serviceClass A Java class that implements the SystemService interface. 
  27.     * @return The service instance, never null. 
  28.     * @throws RuntimeException if the service fails to start. 
  29.     */  
  30.    @SuppressWarnings("unchecked")  
  31.    public <T extends SystemService> T startService(Class<T> serviceClass) {  
  32.        final String name = serviceClass.getName();  
  33.        Slog.i(TAG, "Starting " + name);  
  34.   
  35.        // Create the service.  
  36.        if (!SystemService.class.isAssignableFrom(serviceClass)) {  
  37.            throw new RuntimeException("Failed to create " + name  
  38.                    + ": service must extend " + SystemService.class.getName());  
  39.        }  
  40.        final T service;  
  41.        try {  
  42.            Constructor<T> constructor = serviceClass.getConstructor(Context.class);  
  43.            service = constructor.newInstance(mContext);  
  44.        } catch (InstantiationException ex) {  
  45.            throw new RuntimeException("Failed to create service " + name  
  46.                    + ": service could not be instantiated", ex);  
  47.        } catch (IllegalAccessException ex) {  
  48.            throw new RuntimeException("Failed to create service " + name  
  49.                    + ": service must have a public constructor with a Context argument", ex);  
  50.        } catch (NoSuchMethodException ex) {  
  51.            throw new RuntimeException("Failed to create service " + name  
  52.                    + ": service must have a public constructor with a Context argument", ex);  
  53.        } catch (InvocationTargetException ex) {  
  54.            throw new RuntimeException("Failed to create service " + name  
  55.                    + ": service constructor threw an exception", ex);  
  56.        }  
  57.   
  58.        // Register it.  
  59.        mServices.add(service);  
  60.   
  61.        // Start it.  
  62.        try {  
  63.            service.onStart();  
  64.        } catch (RuntimeException ex) {  
  65.            throw new RuntimeException("Failed to start service " + name  
  66.                    + ": onStart threw an exception", ex);  
  67.        }  
  68.        return service;  
  69.    }  
startService()通过反射,调用构造函数得到一个EthernetService的实例化对象;同时,EthernetService中会创建一个EthernetServiceImpl对象,它是EthernetManager的服务端。调用EthernetService的onStart()方法,注册该服务:
  1. public final class EthernetService extends SystemService {  
  2.   
  3.     private static final String TAG = "EthernetService";  
  4.     final EthernetServiceImpl mImpl;  
  5.   
  6.     public EthernetService(Context context) {  
  7.         super(context);  
  8.         mImpl = new EthernetServiceImpl(context);  
  9.     }  
  10.   
  11.     @Override  
  12.     public void onStart() {  
  13.         Log.i(TAG, "Registering service " + Context.ETHERNET_SERVICE);  
  14.         publishBinderService(Context.ETHERNET_SERVICE, mImpl);  
  15.     }  
  16.   
  17.     @Override  
  18.     public void onBootPhase(int phase) {  
  19.         if (phase == SystemService.PHASE_SYSTEM_SERVICES_READY) {  
  20.             mImpl.start();  
  21.         }  
  22.     }  
  23. }  
EthernetService继承自SystemService。SystemService是一个抽象类,它的设计初衷是用来表示一个运行在system进程中的服务。根据生命周期阶段的不同,它提供了很多系统回调方法,我们可以对它们进行重写,以在生命周期的不同阶段完成某些工作。这里主要看两个方法:
  1. /** 
  2.  * Called when the dependencies listed in the @Service class-annotation are available 
  3.  * and after the chosen start phase. 
  4.  * When this method returns, the service should be published. 
  5.  */  
  6. public abstract void onStart();  
  7.   
  8. /** 
  9.  * Called on each phase of the boot process. Phases before the service's start phase 
  10.  * (as defined in the @Service annotation) are never received. 
  11.  * 
  12.  * @param phase The current boot phase. 
  13.  */  
  14. public void onBootPhase(int phase) {}  
当我们需要启动一个服务时,调用onStart()方法将该服务注册到ServiceManager中;
  1. /** 
  2.     * Publish the service so it is accessible to other services and apps. 
  3.     */  
  4.    protected final void publishBinderService(String name, IBinder service) {  
  5.        publishBinderService(name, service, false);  
  6.    }  
  7.   
  8.    /** 
  9.     * Publish the service so it is accessible to other services and apps. 
  10.     */  
  11.    protected final void publishBinderService(String name, IBinder service,  
  12.            boolean allowIsolated) {  
  13.        ServiceManager.addService(name, service, allowIsolated);  
  14.    }  
onBootPhase()可以在boot的各个阶段被调用。在EthernetService中,当系统处于PHASE_SYSTEM_SERVICES_READY阶段时,会调用EthernetServiceImpl.start()方法,做一些Ethernet的初始化工作:
  1. public void start() {  
  2.        Log.i(TAG, "Starting Ethernet service");  
  3.   
  4.        HandlerThread handlerThread = new HandlerThread("EthernetServiceThread");  
  5.        handlerThread.start();  
  6.        mHandler = new Handler(handlerThread.getLooper());  
  7.   
  8.        mTracker.start(mContext, mHandler);//EthernetNetworkFactory  
  9.   
  10.        mStarted.set(true);  
  11.    }  
EthernetManager对外暴露接口,EthernetServiceImpl向EthernetManager提供服务,EthernetNetworkFactory包揽所有的网络管理操作。
这样,Ethernet服务的启动过程就结束了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值