前言
最近在看android源码中Window的内容,在看到WindowManagerImpl创建对象时发现了SystemServiceRegistry,这个类主要是用来缓存、注册、获取系统服务的。因为对它的缓存机制比较感兴趣,所以就研究下它的源码并记录下来,以便以后回顾迭代。
1. SystemServiceRegistry刚被导入内存时的分析
先来看一段源码:
package android.app;
final class SystemServiceRegistry {
//用来保存所有Service的名字
private static final HashMap<Class<?>, String> SYSTEM_SERVICE_NAMES =
new HashMap<Class<?>, String>();
//用来保存所有的ServiceFetcher,后面会拿出ServiceFetcher源码来说
//现在只要知道它是从缓存中拿Service,缓存中没有就创建Service就可以了
private static final HashMap<String, ServiceFetcher<?>> SYSTEM_SERVICE_FETCHERS =
new HashMap<String, ServiceFetcher<?>>();
//记录缓存的大小
private static int sServiceCacheSize;
//注意构造方法是private的
private SystemServiceRegistry() { }
static{
//注册服务代码
registerService(Context.ACCESSIBILITY_SERVICE, AccessibilityManager.class,
new CachedServiceFetcher<AccessibilityManager>() {
@Override
public AccessibilityManager createService(ContextImpl ctx) {
return AccessibilityManager.getInstance(ctx);
}});
//注册服务代码
registerService(Context.CAPTIONING_SERVICE, CaptioningManager.class,
new CachedServiceFetcher<CaptioningManager>() {
@Override
public CaptioningManager createService(ContextImpl ctx) {
return new CaptioningManager(ctx);