ContextImpl实现了context.java中的方法,
位于: base\core\java\android\content
关键方法:
static class ServiceFetcher {
int mContextCacheIndex = -1;
/**
* Main entrypoint; only override if you don‘t need caching.
*/
public Object getService(ContextImpl ctx) {
ArrayList<Object> cache = ctx.mServiceCache;//mServiceCache是ArrayList<Object>类型对象
Object service;
synchronized (cache) {
if (cache.size() == 0) {
// Initialize the cache vector on first access.
// At this point sNextPerContextServiceCacheIndex
// is the number of potential services that are
// cached per-Context.
for (int i = 0; i < sNextPerContextServiceCacheIndex; i++) { // sNextPerContextServiceCacheIndex为每个Android服务的索引值
cache.add(null);//添加null对象
}
} else {// size不为0的时候,即,之前已经调用过getSystemService
service = cache.get(mContextCacheIndex);
if (service != null) {
return service;
}
}
service = createService(ctx); // cache.size=0并且已经添加了一个null对象到cache里
cache.set(mContextCacheIndex, service); // 设置新创建的服务添加到cache里
return service;
}
}
// 在getService中先获取当前的服务,保存在cache(缓存)中,首先去注册服务, sNextPerContextServiceCacheIndex就是你注册服务的数量,对于一个新创建的Activity,ctx.mServiceCache中没有元素,此时cache.size() = 0,为cache中添加null对象,再创建一个服务给这个个新创建的Activity,对于一个不是新的Activity来说,找到之前 cache中的索引,返回service
/**
* Override this to create a new per-Context instance of the
* service. getService() will handle locking and caching.
*/
public Object createService(ContextImpl ctx) {
throw new RuntimeException("Not implemented");
}
}
/**
* Override this class for services to be cached process-wide.
*/
abstract static class StaticServiceFetcher extends ServiceFetcher {
private Object mCachedInstance;
@Override
public final Object getService(ContextImpl unused) {
synchronized (StaticServiceFetcher.this) {
Object service = mCachedInstance;
if (service != null) {
return service;
}
return mCachedInstance = createStaticService();
}
}
public abstract Object createStaticService();
}
private static final HashMap<String, ServiceFetcher> SYSTEM_SERVICE_MAP =
new HashMap<String, ServiceFetcher>();
private static int sNextPerContextServiceCacheIndex = 0;
private static void registerService(String serviceName, ServiceFetcher fetcher) {
if (!(fetcher instanceof StaticServiceFetcher)) {
fetcher.mContextCacheIndex = sNextPerContextServiceCacheIndex++;
}
SYSTEM_SERVICE_MAP.put(serviceName, fetcher);
}
注册的服务有:
1、AccessibilityManagerService-> AccessibilityManager和ActivityManagerService高度粘合,窗口管理,这里最核心的就是输入事件的分发和管理。
40、USER_SERVICE
获取应用程序的信息,像包名、主线程的Looper、Theme、文件路径、contentResolver、SQLitedatabase
重写了Context.java中的接口,实现了Activity的启动关闭,Sendboardcast(消息的广播、接收)、Service的启动关闭、绑定,系统运行时的文件、权限的增加(grant)、检查(check)、删除(revoke)
framework之 ContextImpl文件解析,布布扣,bubuko.com
原文:http://blog.csdn.net/ahjxly/article/details/20777963