ServiceManager源码分析

来源:互联网 发布:淘宝大表情 编辑:程序博客网 时间:2024/05/31 19:18

1、背景

之前的文章中我们已经分析了SystemServer的启动过程SystemServer启动流程之SystemServer分析(三),由于之前我们有文章单独分析了SystemServer,所以这里我们就将重点放到ServiceManager,在SystemServer中我们可以看到所有的系统服务注册和启动都是通过ServiceManager和SystemServiceManager来完成的,这里我们就对二者进行详细分析。

2、源码分析

在SystemServer中注册和启动系统服务不外乎两种方式,我们一个一个分析。

(1)ServiceManager

在SystemServer中通过ServiceManager.addService()来注册服务,我们进入其源码。

public final class ServiceManager {    //定义一个IServiceManager对象,这是一个接口类,继承于IInterface接口。    private static IServiceManager sServiceManager;    private static HashMap<String, IBinder> sCache = new HashMap<String, IBinder>();    //单例对象    private static IServiceManager getIServiceManager() {        if (sServiceManager != null) {            return sServiceManager;        }        //调用ServiceManagerNative.asInterface来获得对象        sServiceManager =         //这里真正的Service对象是BinderInternal.getContextObject()        ServiceManagerNative.asInterface(BinderInternal.getContextObject());        return sServiceManager;    }}

接下来是该类的相关操作方法。

    //getService的获取方式    public static IBinder getService(String name) {        try {            IBinder service = sCache.get(name);            if (service != null) {                return service;            } else {                return getIServiceManager().getService(name);            }        } catch (RemoteException e) {            Log.e(TAG, "error in getService", e);        }        return null;    }    public static void addService(String name, IBinder service) {        try {            getIServiceManager().addService(name, service, false);        } catch (RemoteException e) {            Log.e(TAG, "error in addService", e);        }    }    //addService的最终实现    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);        }    }    //checkService    public static IBinder checkService(String name) {        try {            IBinder service = sCache.get(name);            if (service != null) {                return service;            } else {                return getIServiceManager().checkService(name);            }        } catch (RemoteException e) {            Log.e(TAG, "error in checkService", e);            return null;        }    }    //获得Services列表    public static String[] listServices() throws RemoteException {        try {            return getIServiceManager().listServices();        } catch (RemoteException e) {            Log.e(TAG, "error in listServices", e);            return null;        }    }    //initServiceCache    public static void initServiceCache(Map<String, IBinder> cache) {        if (sCache.size() != 0) {            throw new IllegalStateException("setServiceCache may only be called once");        }        sCache.putAll(cache);    }

可以发现所有的方法最终都是调用getIServiceManager()方法即IServiceManager对象或其子类相关方法,我们进入ServiceManagerNative类源码。

public abstract class ServiceManagerNative extends Binder implements IServiceManager{    static public IServiceManager asInterface(IBinder obj)    {        if (obj == null) {            return null;        }        IServiceManager in =            (IServiceManager)obj.queryLocalInterface(descriptor);        if (in != null) {            return in;        }        //创建ServiceManager的代理对象ServiceManagerProxy        return new ServiceManagerProxy(obj);    }}class ServiceManagerProxy implements IServiceManager {    public ServiceManagerProxy(IBinder remote) {        mRemote = remote;    }    public IBinder asBinder() {        return mRemote;    }}

可以发现和传统的Binder通信一样的,也有ServiceManager的代理对象ServiceManagerProxy,这里我们就不详细阐述了,如果大家不是很明白,可以去看另外一篇文章ActivityManagerService与应用程序通信分析,这里既然设计到IServiceManager接口,我们还是去了解一下吧。

public interface IServiceManager extends IInterface{    public IBinder getService(String name) throws RemoteException;    public IBinder checkService(String name) throws RemoteException;    public void addService(String name, IBinder service, boolean allowIsolated)                throws RemoteException;    public String[] listServices() throws RemoteException;    public void setPermissionController(IPermissionController controller)            throws RemoteException;    static final String descriptor = "android.os.IServiceManager";    int GET_SERVICE_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION;    int CHECK_SERVICE_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+1;    int ADD_SERVICE_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+2;    int LIST_SERVICES_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+3;    int CHECK_SERVICES_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+4;    int SET_PERMISSION_CONTROLLER_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+5;}

大家发现没,所有的抽象方法,在ServiceManager类中被封装以供外界调用,而真正的实现者却是BinderInternal.getContextObject()这个native方法,这里和传统的Binder通信没有什么两样,Android中使用了大量的代理模式,比如ActivityManagerService等。

我们来用一张图表示这几个类的相关关系。

ServiceManager相关类

(2)SystemServiceManager

在SystemServer中还有很多的服务是通过SystemServiceManager.startService()方法来注册和启动服务,我们进入该方法。

public class SystemServiceManager {    //用于保存通过startService来注册的服务,需要注意其都是SystemService类型    private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();    public SystemServiceManager(Context context) {        mContext = context;    }    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);    }    //startService的最终实现    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.        //将当前的Service添加到mServices集合中进行注册        mServices.add(service);        // Start it.        try {            //对当前的Service进行启动            service.onStart();        } catch (RuntimeException ex) {            throw new RuntimeException("Failed to start service " + name                    + ": onStart threw an exception", ex);        }        return service;    }    //......}

虽然我们还没有看到哪些服务是通过startService这个方法来注册和启动的,但是通过以上的源码我们可以猜想出这些必须要满足的条件。
(1)该服务肯定继承于SystemService类
(2)该服务肯定会重写SystemService的onStart()方法

基于以上两点,我们来看两个服务的示例。

3、Service示例

(1)UsbService

我们直接进入其源码查看其详细细节。

private static final String USB_SERVICE_CLASS =            "com.android.server.usb.UsbService$Lifecycle";//注册和启动servicemSystemServiceManager.startService(USB_SERVICE_CLASS);//UsbServicepublic class UsbService extends IUsbManager.Stub {    //继承自SystemService    public static class Lifecycle extends SystemService {        private UsbService mUsbService;        public Lifecycle(Context context) {            super(context);        }        //重写其onStart方法        @Override        public void onStart() {            mUsbService = new UsbService(getContext());            //调用父类的publishBinderService()方法            publishBinderService(Context.USB_SERVICE, mUsbService);        }        //重写其onBootPhase方法        @Override        public void onBootPhase(int phase) {            if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {                mUsbService.systemReady();            }        }    }}

(2)PowerManagerService

//继承于SystemServicepublic final class PowerManagerService extends SystemService        implements Watchdog.Monitor {    //重写父类的onStart()方法    @Override    public void onStart() {        //调用父类的publishBinderService和publishLocalService方法        publishBinderService(Context.POWER_SERVICE, new BinderService());        publishLocalService(PowerManagerInternal.class, new LocalService());        Watchdog.getInstance().addMonitor(this);        Watchdog.getInstance().addThread(mHandler);    }    //重写父类的onBootPhase()方法    @Override    public void onBootPhase(int phase) {        synchronized (mLock) {            if (phase == PHASE_BOOT_COMPLETED) {                final long now = SystemClock.uptimeMillis();                mBootCompleted = true;                mDirty |= DIRTY_BOOT_COMPLETED;                userActivityNoUpdateLocked(                        now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);                updatePowerStateLocked();            }        }    }}

通过以上两个Service我们可知,我们此前的猜想是完全正确的,我们接下来进入SystemService类来看其具体实现。

//抽象类public abstract class SystemService {    public SystemService(Context context) {        mContext = context;    }    //抽象方法onStart    public abstract void onStart();    //onBootPhase    public void onBootPhase(int phase) {}    //publishBinderService方法的具体实现    protected final void publishBinderService(String name, IBinder service,            boolean allowIsolated) {        //将当前service通过ServiceManager的addService类进行注册        ServiceManager.addService(name, service, allowIsolated);    }    //通过name来查找service    protected final IBinder getBinderService(String name) {        return ServiceManager.getService(name);    }    //注册本地服务    protected final <T> void publishLocalService(Class<T> type, T service) {        LocalServices.addService(type, service);    }    protected final <T> T getLocalService(Class<T> type) {        return LocalServices.getService(type);    }    private SystemServiceManager getManager() {        return LocalServices.getService(SystemServiceManager.class);    }}

当看到SystemService的源码后真相大白了,原来SystemServiceManager.startService()方法最终也是通过ServiceManager.addService()来对服务进行注册

当然有的服务同时还通过LocalServices.addService()来同时注册,我们来看一下其相关源码。

public final class LocalServices {    private LocalServices() {}    private static final ArrayMap<Class<?>, Object> sLocalServiceObjects =            new ArrayMap<Class<?>, Object>();    public static <T> T getService(Class<T> type) {        synchronized (sLocalServiceObjects) {            return (T) sLocalServiceObjects.get(type);        }    }    public static <T> void addService(Class<T> type, T service) {        synchronized (sLocalServiceObjects) {            if (sLocalServiceObjects.containsKey(type)) {                throw new IllegalStateException("Overriding service registration");            }            sLocalServiceObjects.put(type, service);        }    }}

好啦,到此整个ServiceManager我们就简单的分析完毕啦。

0 0
原创粉丝点击