您的位置:首页 > 移动开发 > Android开发

Android getSystemService

2016-12-19 00:00 447 查看

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: