service2-App获取系统service的过程

Android系统中提供了很多Service,如剪切板服务,AMS服务等.很有必要一个app是如何获得这些service的.
app中如何获取Android系统中提供的service

app是通过context来获取的.
例如获取AMS:
ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
可以看出,上面getSystemService 之后是ActivityManager,实际获取的是AMS

getSystemService()方法是Activity类中定义.
android/frameworks/base/core/java/android/app/Activity.java

    @Override
    public Object getSystemService(@ServiceName @NonNull String name) {
        if (getBaseContext() == null) {
            throw new IllegalStateException(
                    "System services not available to Activities before onCreate()");
        }

        if (WINDOW_SERVICE.equals(name)) {
            return mWindowManager;
        } else if (SEARCH_SERVICE.equals(name)) {
            ensureSearchManager();
            return mSearchManager;
        }
        return super.getSystemService(name);
    }
public class Activity extends ContextThemeWrapper{}  ---->ContextThemeWrapper
           public class ContextThemeWrapper extends ContextWrapper{} ---->ContextWrapper
                    public class ContextWrapper extends Context {}----------------------->Context 

ActivityThread中的performLaunchActivity()方法中,实例化了ContextImpl,然后调用activity的attach()方法传递给mBase的,具体流程可以跟一下startActivity的流程
图片.png

最后可以知道getSystemService 最后调用的是ContextImpl 中的getSystemService。

public Object getSystemService(String name) {
        return SystemServiceRegistry.getSystemService(this, name);
    }

frameworks/base/core/java/android/app/SystemServiceRegistry.java
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:

final class SystemServiceRegistry {
    private static final String TAG = "SystemServiceRegistry";
    // Service registry information.
    // This information is never changed once static initialization has completed.
    private static final HashMap, String> SYSTEM_SERVICE_NAMES =
            new HashMap, String>();
    private static final HashMap> SYSTEM_SERVICE_FETCHERS =
            new HashMap>();   //----> 可以看出是HashMap
    private static int sServiceCacheSize;
}

ServiceFetcher: 看看这个是什么
    /**
     * Base interface for classes that fetch services.
     * These objects must only be created during static initialization.
     */
    static abstract interface ServiceFetcher {
        T getService(ContextImpl ctx);
    }

总结: 有上面的可以看出,所有service 都记录在hashmap 中,name 是key ,value是ServiceFetcher
ServiceFetcher 最后返回一定是ActivityManager,因为(ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);

下面看看SYSTEM_SERVICE_FETCHERS
在SystemServiceRegistry类中只有registerService()这个方法操作了SYSTEM_SERVICE_FETCHERS:

private static  void registerService(String serviceName, Class serviceClass,
           ServiceFetcher serviceFetcher) {
       SYSTEM_SERVICE_NAMES.put(serviceClass, serviceName);
       SYSTEM_SERVICE_FETCHERS.put(serviceName, serviceFetcher);
   }

registerService是private 方法:查看SystemServiceRegistry 类中的调用关系

final class SystemServiceRegistry {
    ..........
    registerService(Context.ACTIVITY_SERVICE, ActivityManager.class,
              new CachedServiceFetcher() {
          @Override
          public ActivityManager createService(ContextImpl ctx) {
              return new ActivityManager(ctx.getOuterContext(), ctx.mMainThread.getHandler());
          }});
    ...............
  }

SystemServiceRegistry静态代码块中调用了registerService()方法.

也就是说当SystemServiceRegistry类初始化的时候,就会在其静态代码块中执行registerService()方法,填充SYSTEM_SERVICE_FETCHERS这个hashmap.

分析下面new CachedServiceFetcher() 匿名内部类createService

    registerService(Context.ACTIVITY_SERVICE, ActivityManager.class,
              new CachedServiceFetcher() {
          @Override
          public ActivityManager createService(ContextImpl ctx) {
              return new ActivityManager(ctx.getOuterContext(), ctx.mMainThread.getHandler());
          }});

registerService: 参数1,参数2,参数3 匿名内部类
参数1:Context.ACTIVITY_SERVICE-> public static final String ACTIVITY_SERVICE = "activity";
参数2:AMS代理类:ActivityManager
private static void registerService(String serviceName, Class serviceClass,
ServiceFetcher serviceFetcher) {
SYSTEM_SERVICE_NAMES.put(serviceClass, serviceName);-->serviceClass传递
SYSTEM_SERVICE_FETCHERS.put(serviceName, serviceFetcher);---->serviceFetcher传递
}

参数3:CachedServiceFetcher
frameworks/base/core/java/android/app/SystemServiceRegistry.java

static abstract class CachedServiceFetcher implements ServiceFetcher {
    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);--->如果service 不存在, 进行create
                cache[mCacheIndex] = service;
            }
            return (T)service;
        }
    }

    public abstract T createService(ContextImpl ctx);  ----->抽象,子类要实现
}

对于AMS来说,其T为ActivityManager.
CachedServiceFetcher这个模块类很简单,就是实现了ServiceFetcher接口中getService()方法.

定义了一个抽象方法:T createService().那么其子类要负责实现这个创建Service的方法.

最终通过registerService()方法,第一个参数作为key将第三个参数存入了SYSTEM_SERVICE_FETCHERS这个hashmap中. 参考下面
(SYSTEM_SERVICE_FETCHERS.put(serviceName, serviceFetcher))

缓存机制
SystemServiceRegistry::CachedServiceFetcher:getService

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;
    }
}

当调用这createService()方法创建对象之后,为了下次能快速获取,所以将其缓存起来了.
frameworks/base/core/java/android/app/ContextImpl.java

// The system service cache for the system services that are cached per-ContextImpl.
final Object[] mServiceCache = SystemServiceRegistry.createServiceCache();

可以看出app 中进行了缓存mServiceCache,
Object service = cache[mCacheIndex]; 没有理解mCacheIndex 如何与service 对应起来,如果有两个service 如何进行index

有人这样写:
下次在获取的时候,直接从context的缓存中拿.其中索引mCacheIndex在创建CachedServiceFetcher子类对象的时候的初始化.和其在SystemServiceRegistry静态代码块中注册的顺序一致.

REF:
https://www.jianshu.com/p/c89a8ad9708c

你可能感兴趣的:(service2-App获取系统service的过程)