android系统getSystemService原理分析

来源:互联网 发布:手机图片移花接木软件 编辑:程序博客网 时间:2024/06/15 01:32

平常有很多用到系统服务的地方 比如TelephonyManger

TelephonyManager tm =(TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);

系统会在frameworks/base/core/java/android/app/SystemServiceRegistry.java 这里注册

final class SystemServiceRegistry {  ......    private SystemServiceRegistry() { }    static {       registerService(Context.TELEPHONY_SERVICE, TelephonyManager.class,                new CachedServiceFetcher<TelephonyManager>() {                  @Override                  public TelephonyManager createService(ContextImpl ctx) {                      return new TelephonyManager(ctx.getOuterContext());        }});    }

ContextImpl会调用SystemServiceRegistry.java 中 getSystemService()方法

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

这里反射得到每个serviceString对应的 service服务 ContextImpl继承 Context 于是有如上的调用

原创粉丝点击