Android 系统服务的获取与创建
这里,ActivityManager就是堂主的角色,而ActivityManagerService就是总部的角色
创建Manager
在Android的系统中存在这么一个类SystemServiceRegistry,这个类就是负责注册并存储,让我带大家了解一下服务的注册过程吧~
static { registerService(Context.ACTIVITY_SERVICE, ActivityManager.class, new CachedServiceFetcher<ActivityManager>() { @Override public ActivityManager createService(ContextImpl ctx) { return new ActivityManager(ctx.getOuterContext(), ctx.mMainThread.getHandler()); }}); }
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); }
当我们需要获取Manager服务的时候,我们通常会这样写
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
那么我们就从这个开始跟起,看一下Context下的getSystemService函数,Context的实现类为ContextImpl,所以我们直接看ContextImpl的getSystemService就好了
@Override public Object getSystemService(String name) { return SystemServiceRegistry.getSystemService(this, name); }
public static Object getSystemService(ContextImpl ctx, String name) { ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name); return fetcher != null ? fetcher.getService(ctx) : null; }
这里通过传入的key值,从Map集合中在取出CachedServiceFetcher对象,并调用getService方法,我们看一下getService
@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) { try { service = createService(ctx); cache[mCacheIndex] = service; } catch (ServiceNotFoundException e) { onServiceNotFound(e); } } return (T)service; } }