定制Android系统开发之五——ServiceFetcher

来源:互联网 发布:java使用的字符码集 编辑:程序博客网 时间:2024/05/31 18:35

总觉得在上篇博文里面对在ContextImpl里面注册系统服务的过程讲的很乱,这里再写一点,说明一下注册的过程。
注册的核心是一个类:ServiceFetcher。ServiceFetcher的定义如下:

static class ServiceFetcher {    int mContextCacheIndex = -1;    /**     * Main entrypoint; only override if you don't need caching.     */    public Object getService(ContextImpl ctx) {        ArrayList<Object> cache = ctx.mServiceCache;        Object service;        synchronized (cache) {            if (cache.size() == 0) {                // Initialize the cache vector on first access.                // At this point sNextPerContextServiceCacheIndex                // is the number of potential services that are                // cached per-Context.                for (int i = 0; i < sNextPerContextServiceCacheIndex; i++) {                    cache.add(null);                }            } else {                service = cache.get(mContextCacheIndex);                if (service != null) {                    return service;                }            }            service = createService(ctx);            cache.set(mContextCacheIndex, service);            return service;        }    }    /**     * Override this to create a new per-Context instance of the     * service.  getService() will handle locking and caching.     */    public Object createService(ContextImpl ctx) {        throw new RuntimeException("Not implemented");    }}

可见,这个类没有字段,只有两个函数,一个get和一个create。所以,可以把这个类当作一个Service的生产工厂,当你创建这样一个工厂的时候,你可以设置这个工厂生产什么样的服务,即重载createService方法。

再来看注册服务的代码:

registerService(IFLYTEK_RADIO_MANAGER_SERVICE, new ServiceFetcher() {    public Object createService(ContextImpl ctx) {        IBinder b = ServiceManager.getService(IFLYTEK_RADIO_MANAGER_SERVICE);        return new android.os.iflytek.RadioManager(ctx, IRadioManager.Stub.asInterface(b));    }});

registerService方法有两个参数,第一个参数就是服务的名称,第二个参数就是新建的一个ServiceFetcher对象。这个过程可以这么理解,为了生产服务,我新建了一个工厂(ServiceFetcher),然后我告诉了工厂怎么生产这个对象(重载createService()方法)。这样,当我需要服务的时候,工厂就能够生产我需要的服务(通过createService()方法)。

1 0
原创粉丝点击