android service 获取 context,为什么context可以获取service?

Context框架

2a2a9f49f1c6

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() {

@Override

public ActivityManager createService(ContextImpl ctx) {

return new ActivityManager(ctx.getOuterContext(), ctx.mMainThread.getHandler());

}});

...

}

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

4. SystemServiceRegistry::registerService

private static void registerService(String serviceName, Class serviceClass,

ServiceFetcher 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> SYSTEM_SERVICE_FETCHERS =

new HashMap>();

private static final HashMap, String> SYSTEM_SERVICE_NAMES =

new HashMap, String>();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值