Android getSystemService

getSystemService的实际调用者-SystemServiceRegistry

getSystemService是Context中的方法,经过SystemServiceRegistry类获取SystemService实例,具体的实如今ContextImpl中。有关Context的简介,能够参考http://www.javashuo.com/article/p-yegqpqxb-hz.htmljava

@Override
public Object getSystemService(String name) {
    return SystemServiceRegistry.getSystemService(this, name);
}

getSystemService在SystemServiceRegistry中的实现方式

一、SystemServiceRegistry中声明了两个静态HashMap设计模式

// Service registry information.
// This information is never changed once static initialization has completed.
private static final HashMap<Class<?>, String> SYSTEM_SERVICE_NAMES =
        new HashMap<Class<?>, String>();
private static final HashMap<String, ServiceFetcher<?>> SYSTEM_SERVICE_FETCHERS =
        new HashMap<String, ServiceFetcher<?>>();

SYSTEM_SERVICE_NAMES存放着SystemService的class和名称;ide

SYSTEM_SERVICE_FETCHERS存放着SystemService的名称和接口ServiceFetcher的实例。fetch

 

二、在SystemServiceRegistry类加载时会建立服务实例并经过registerService方法将ServiceFetcher存放在HashMap中。this

ServiceFetcher是一个用来获取Service实例的接口:spa

/**
 * Base interface for classes that fetch services.
 * These objects must only be created during static initialization.
 */
static abstract interface ServiceFetcher<T> {
    T getService(ContextImpl ctx);
}
static {
    registerService(Context.ACCESSIBILITY_SERVICE, AccessibilityManager.class,
            new CachedServiceFetcher<AccessibilityManager>() {
        @Override
        public AccessibilityManager createService(ContextImpl ctx) {
            return AccessibilityManager.getInstance(ctx);
        }});
    // 省略代码
}
/**
 * Statically registers a system service with the context.
 * This method must be called during static initialization only.
 */
private static <T> void registerService(String serviceName, Class<T> serviceClass,
        ServiceFetcher<T> serviceFetcher) {
    SYSTEM_SERVICE_NAMES.put(serviceClass, serviceName);
    SYSTEM_SERVICE_FETCHERS.put(serviceName, serviceFetcher);
}

 

三、调用getSystemService时根据名称从HashMap获取实例.net

/**
 * Gets a system service from a given context.
 */
public static Object getSystemService(ContextImpl ctx, String name) {
    ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
    return fetcher != null ? fetcher.getService(ctx) : null;
}

getSystemService中的设计模式

SystemService的两个静态HashMap其实就是“使用容器实现单例”设计

有关单例模式能够参考:http://www.javashuo.com/article/p-riuvmrsx-ht.htmlcode

相关文章
相关标签/搜索