基于Andoird 4.2.2的Account Manager源代码分析学习:AccountManager的初始化

应用程序开发者并不直接请求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对象,实现了createService()。在获取AccountManager实例的时候,如果实例还不存在,则通过调用这个方法来创建:

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;
            }
        }

可以看到,ContextImpl类维护一个缓存mServiceCache,当服务实例被创建,则将其加入到缓存中。





你可能感兴趣的:(android,accountmanager)