为什么context可以获取service?

Context框架

Context框架

Android程序Context的数量= Activity + Service + Application
ContextThemeWrapper、ContextWrapper功能委托给ContextImpl实现;

1. ContextImpl::getSystemService

public Object getSystemService(String name) {
    return SystemServiceRegistry.getSystemService(this, name);
}

public String getSystemServiceName(Class<?> serviceClass) { // 2
    return SystemServiceRegistry.getSystemServiceName(serviceClass);
}

2. SystemServiceRegistry::getSystemService

public static Object getSystemService(ContextImpl ctx, String name) {
    ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
    return fetcher != null ? fetcher.getService(ctx) : null;
}

public static String getSystemServiceName(Class<?> serviceClass) {
    return SYSTEM_SERVICE_NAMES.get(serviceClass); // 4
}

3. SystemServiceRegistry::SYSTEM_SERVICE_NAMES初始化

static {
    ...
    registerService(Context.ACTIVITY_SERVICE, ActivityManager.class,
            new CachedServiceFetcher<ActivityManager>() {
        @Override
        public ActivityManager createService(ContextImpl ctx) {
            return new ActivityManager(ctx.getOuterContext(), ctx.mMainThread.getHandler());
        }});
    ...
}

static块,会在类被加载的时候执行且仅会被执行一次,一般用来初始化静态变量和调用静态方法。

4. SystemServiceRegistry::registerService

private static <T> void registerService(String serviceName, Class<T> serviceClass,
        ServiceFetcher<T> serviceFetcher) {
    SYSTEM_SERVICE_NAMES.put(serviceClass, serviceName);
    SYSTEM_SERVICE_FETCHERS.put(serviceName, serviceFetcher);
}

5. SystemServiceRegistry::SYSTEM_SERVICE_FETCHERS 保存服务引用且final

// Service registry information.
// This information is never changed once static initialization has completed.
private static final HashMap<String, ServiceFetcher<?>> SYSTEM_SERVICE_FETCHERS =
        new HashMap<String, ServiceFetcher<?>>();
private static final HashMap<Class<?>, String> SYSTEM_SERVICE_NAMES =
        new HashMap<Class<?>, String>();
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容