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
相关文章推荐
- Android之getSystemService()方法
- android中LayoutInflater的3种使用以及getSystemService的API
- android中的系统级服务getSystemService(name)
- Android getSystemService
- [转载]android中getSystemService详解
- Android之getSystemService 各种系统服务总结
- Android getSystemService()
- Android的getSystemService(String)
- Android中getSystemService详解
- Android的 getSystemService
- android中LayoutInflater的3种使用以及getSystemService的API
- Android之getSystemService
- Android getSystemService()
- Android中LayoutInflater的3种使用以及getSystemService的API
- android中LayoutInflater的3种使用以及getSystemService的API
- android getSystemService
- Service---android中getSystemService详解
- getSystemService()是Android很重要的一个API
- 添加android service并通过getSystemService调用
- Android getSystemService()调用