具体实现类 base/core/java/android/app/ContextImpl.java
里面含有静态代码块,registerService(SENSOR_SERVICE, new ServiceFetcher() {
public Object createService(ContextImpl ctx) { return new SystemSensorManager(ctx.mMainThread.getHandler().getLooper()); }});各种实例都在其中,主要是通过Map来集中管理,
private static final HashMap<String, ServiceFetcher> SYSTEM_SERVICE_MAP =
268 new HashMap<String, ServiceFetcher>(); 269 270 private static int sNextPerContextServiceCacheIndex = 0; 271 private static void registerService(String serviceName, ServiceFetcher fetcher) { 272 if (!(fetcher instanceof StaticServiceFetcher)) { 273 fetcher.mContextCacheIndex = sNextPerContextServiceCacheIndex++; 274 } 275 SYSTEM_SERVICE_MAP.put(serviceName, fetcher); 276 } @Override1478 public Object getSystemService(String name) { 1479 ServiceFetcher fetcher = SYSTEM_SERVICE_MAP.get(name);1480 return fetcher == null ? null : fetcher.getService(this);1481 }fetch.getService会调用createService,然后直接返回 代码如下
public Object getService(ContextImpl ctx) {
215 ArrayList<Object> cache = ctx.mServiceCache; 216 Object service; 217 synchronized (cache) { 218 if (cache.size() == 0) { 219 // Initialize the cache vector on first access. 220 // At this point sNextPerContextServiceCacheIndex 221 // is the number of potential services that are 222 // cached per-Context. 223 for (int i = 0; i < sNextPerContextServiceCacheIndex; i++) { 224 cache.add(null); 225 } 226 } else { 227 service = cache.get(mContextCacheIndex); 228 if (service != null) { 229 return service; 230 } 231 } 232 service = createService(ctx); 233 cache.set(mContextCacheIndex, service); 234 return service; 235 } 236 }获取的时候直接在SYSTEM_SERVICE_MAP取出来,
@Override
1478 public Object getSystemService(String name) { 1479 ServiceFetcher fetcher = SYSTEM_SERVICE_MAP.get(name);1480 return fetcher == null ? null : fetcher.getService(this);1481 }