Android getSystemService

getSystemService的实际调用者-SystemServiceRegistry

getSystemService是Context中的方法,通过SystemServiceRegistry类获取SystemService实例,具体的实现在ContextImpl中。有关Context的简介,可以参考https://my.oschina.net/u/3026396/blog/791855

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

getSystemService在SystemServiceRegistry中的实现方式

1、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和名称;

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

 

2、在SystemServiceRegistry类加载时会创建服务实例并通过registerService方法将ServiceFetcher存放在HashMap中。

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

/**
 * 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);
}

 

3、调用getSystemService时根据名称从HashMap获取实例

/**
 * 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其实就是“使用容器实现单例”

有关单例模式可以参考:https://my.oschina.net/u/3026396/blog/795128

转载于:https://my.oschina.net/u/3026396/blog/808207

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值