Context
android/framework/base/core/java/android/content/Context.java
public abstract @Nullable Object getSystemService(@ServiceName @NonNull String name);
public abstract @Nullable String getSystemServiceName(@NonNull Class<?> serviceClass);
public final @Nullable <T> T getSystemService(@Nullable Class<T> serviceClass){
String serviceName = getSystemServiceName(serviceClass);
return serviceName != null ? (T)getSystemService(serviceName) : null;
}
context.getSystemService(serviceName); //获取系统服务
ContextImpl
android/frameworks/base/core/java/android/app/ContextImpl.java
public Object getSystemService(String name){
return SystemServiceRegistry.getSystemService(this,name);
}
public String getSystemServiceName(Class<?> serviceClass){
return SystemServiceRegistry.getSystemServiceName(serviceClass);
}
SystemServiceRegistery
android/app/SystemServiceRegistry.java
具体实现
//contextImpl调用
//从给定上下文获取系统服务
public static Object getSystemService(ContextImpl ctx,String name){
ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
return fetcher != null ? fetcher.getService(ctx):null;
}
//SYSTEM_SERVICE_NAMES
//SYSTEM_SERVICE_FETCHERS <服务名,取款机-->
private static final Map<Class<?>,String> SYSTEM_SERVICE_NAMES =
new ArrayMap<Class<?>,String>();
private static final Map<String,serviceFetcher<?>>() SYSTEM_SERVICE_FETCHERS =
new ArrayMap<String,serviceFetcher<?>>();
//在静态初始化期间调用
private static <T> void registerService(String serviceName,Class<T> serviceClass,
ServiceFetcher<T> serviceFetcher){//ServiceFetcher接口
SYSTEM_SERVICE_NAMES.put(serviceClass,serviceName);
SYSTEM_SERVICE_FETCHERS.put(serviceName,serviceFetcher);
}
//调用
静态代码块,在虚拟机加载类的时候就会加载执行,而且只执行一次;
非静态代码块,在创建对象的时候(即new一个对象的时候)执行,每次创建对象都会执行一次
static{
registerService(Context.WINDOW_SERVICE,WindowManager.class,new CachedServiceFetcher<WindowManager>(){
public WindowManager createService(ContextImpl ctx){
return new WindowManagerImpl(ctx);
}
});
}
//获取服务类的基接口 只能在静态初始化时被创建
static abstract interface ServiceFetcher<T>{
T getService(Context ctx);
}
static abstract class StaticServiceFetcher<T> implements ServiceFetcher<T>{
private T mCachedInstance;
public final T getService(ContextImpl ctx){
synchronized (StaticServiceFetcher.this){
if(mCachedInstance == null){
try{
mCachedInstance = createService();
}catch(ServiceNotFoundException e){
onServiceNotFound(e);
}
}
return mCachedInstance;
}
}
public abstract T createService() throws ServiceNotFoundException;
}
public static String getSystemServiceName(){
return SYSTEM_SERVICE_NAMES.get(serviceClass);
}