应用程序开发者并不直接请求AccountManagerService服务。帐号相关的处理,由AccountManager提供接口。
按如下的方式获得AccountManager实例:
AccountManager accountManager = AccountManager.get(context);
实际上get()方法中,调用了Context.getSystemService()来创建实例:
public static AccountManager get(Context context) { if (context == null) throw new IllegalArgumentException("context is null"); return (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE); }
ContextImpl.getSystemService():
@Override public Object getSystemService(String name) { ServiceFetcher fetcher = SYSTEM_SERVICE_MAP.get(name); return fetcher == null ? null : fetcher.getService(this); }
在此之前,ContextImpl类在一个静态块中注册AccountManager:
class ContextImpl extends Context { static { ... registerService(ACCOUNT_SERVICE, new ServiceFetcher() { public Object createService(ContextImpl ctx) { IBinder b = ServiceManager.getService(ACCOUNT_SERVICE); IAccountManager service = IAccountManager.Stub.asInterface(b); return new AccountManager(ctx, service); }}); ... } }
ServiceFetcher.getService():
public Object getService(ContextImpl ctx) { ArrayList<Object> cache = ctx.mServiceCache; 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++) { cache.add(null); } } else { service = cache.get(mContextCacheIndex); if (service != null) { return service; } } service = createService(ctx); cache.set(mContextCacheIndex, service); return service; } }