经常看到有类似于如下的语句,之前不知道这个究竟是如何返回一个TelephonyManager对象的,今天简单地看了下,发现其实这个也没有太过复杂
(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
主要是调用了Context的getSystemService方法
public abstract Object getSystemService(@ServiceName @NonNull String name);
这个地方是一个抽象方法,那么一定是在其子类中调用的,因此ContextImpl.java文件中
@Override
public Object getSystemService(String name) {
return SystemServiceRegistry.getSystemService(this, name);
}
好,继续看SystemServiceRegistry的getSystemService方法
/**
* Gets a system service from a given context.
*/
public static Object getSystemService(ContextImpl ctx, String name) {
ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
return fetcher != null ? fetcher.getService(ctx) : null;
}
那么,SYSTEM_SERVICE_FETCHERS是什么?
/**
* Statically registers a system service with the context.
* This method must be called during static initialization only.
*/
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);
}
是一个private方法,在哪儿调用的呢?
static {
......
registerService(Context.TELEPHONY_SERVICE, TelephonyManager.class,
new CachedServiceFetcher<TelephonyManager>() {
@Override
public TelephonyManager createService(ContextImpl ctx) {
return new TelephonyManager(ctx.getOuterContext());
}});
......
}
回到registerService方法,SYSTEM_SERVICE_FETCHERS中添加的是这个static的CachedServiceFetcher对象,getSystemService返回的应该是fetcher.getService(ctx)才对,那么看一下CachedServiceFetcher类的getService方法
/**
* Override this class when the system service constructor needs a
* ContextImpl and should be cached and retained by that context.
*/
static abstract class CachedServiceFetcher<T> implements ServiceFetcher<T> {
private final int mCacheIndex;
public CachedServiceFetcher() {
mCacheIndex = sServiceCacheSize++;
}
@Override
@SuppressWarnings("unchecked")
public final T getService(ContextImpl ctx) {
final Object[] cache = ctx.mServiceCache;
synchronized (cache) {
// Fetch or create the service.
Object service = cache[mCacheIndex];
if (service == null) {
service = createService(ctx);
cache[mCacheIndex] = service;
}
return (T)service;
}
}
public abstract T createService(ContextImpl ctx);
}
getService方法中调用了createService方法,而createService方法是在SystemServiceRegistry类的静态区域中定义的,回到上述registerService调用的地方
registerService(Context.TELEPHONY_SERVICE, TelephonyManager.class,
new CachedServiceFetcher<TelephonyManager>() {
@Override
public TelephonyManager createService(ContextImpl ctx) {
return new TelephonyManager(ctx.getOuterContext());
}});
createService返回的是新建的一个TelephonyManager对象,而CachedServiceFetcher的getService方法中return的就是这个
所以
(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
这个返回的就是new TelephonyManager(context)对象了