当前位置:   article > 正文

getSystemService追根溯源_context.getsystemservice(

context.getsystemservice(

getSystemService追根溯源

 

在安卓开发过程中,我们经常会用到getSystemService方法来获取各种系统服务,比如下面几种常见的获取服务代码:

  1. NetworkInfo networkInfo = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
  2. TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
  3. JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
  4. (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE)

简单说一下系统服务,系统服务对于第三方app来说简直是神一样的存在,它们拥有者各种各样的系统权限和资源,第三方app很多功能都得指望它们来做事。其实这些系统服务都是运行在一个进程之中,这个进程叫做system_server进程,每个服务都运行在各自的线程之中,比如ActivityManagerService、PackageManagerService等。我们下面来逆向分析一下我们是怎么得到系统服务对象或者是代理对象的。

1、先来看一下Activity.getSystemService的源码(我的源码版本是android 7.1.1):

  1. @Override
  2. public Object getSystemService(@ServiceName @NonNull String name) {
  3. if (getBaseContext() == null) {
  4. throw new IllegalStateException(
  5. "System services not available to Activities before onCreate()");
  6. }
  7. if (WINDOW_SERVICE.equals(name)) {
  8. return mWindowManager;
  9. } else if (SEARCH_SERVICE.equals(name)) {
  10. ensureSearchManager();
  11. return mSearchManager;
  12. }
  13. return super.getSystemService(name);
  14. }

上面的代码中,会先根据服务名称判断是否为WINDOW_SERVICE或者SEARCH_SERVICE,是这两个的话,因为Activity对象里面已经持有这两个服务的代理对象了,所以可以直接返回,如果不是这两个服务,则调用父类的getSystemService方法,其父类ContextThemeWrapper。

2、ContextThemeWrapper.getSystemService方法的源码:

  1. @Override
  2. public Object getSystemService(String name) {
  3. if (LAYOUT_INFLATER_SERVICE.equals(name)) {
  4. if (mInflater == null) {
  5. mInflater = LayoutInflater.from(getBaseContext()).cloneInContext(this);
  6. }
  7. return mInflater;
  8. }
  9. return getBaseContext().getSystemService(name);
  10. }
 

上面代码中,会判断是否是获取LAYOUT_INFLATER_SERVICE服务,如果是,则返回其持有的服务对象,如果不是,则调用getBaseContext().getSystemService(name)方法。我们先看getBaseContext()返回值是什么:

  1. /**
  2. * @return the base context as set by the constructor or setBaseContext
  3. */
  4. public Context getBaseContext() {
  5. return mBase;
  6. }
  7. public class ContextWrapper extends Context {
  8. Context mBase;
  9. public ContextWrapper(Context base) {
  10. mBase = base;
  11. }
  12.         //此处省略n行代码
  13. }
 

通过代码调试可知,mBase的类型其实是ContextImpl,我们来看一下ContextImpl.getSystemService的源码。此处附一张Context的继承关系类图。

3、ContextImpl.getSystemService的源码:

  1. @Override
  2.     public Object getSystemService(String name) {
  3.         return SystemServiceRegistry.getSystemService(this, name);
  4.     }

4、SystemServiceRegistry.getSystemService的源码:

  1. /**
  2.      * Gets a system service from a given context.
  3.      */
  4.     public static Object getSystemService(ContextImpl ctx, String name) {
  5.         ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
  6.         return fetcher != null ? fetcher.getService(ctx) : null;
  7.     }

我们先来看一下ServiceFetcher是何方神圣,它其实是一个接口,其定义如下:

  1. /**
  2. * Base interface for classes that fetch services.
  3. * These objects must only be created during static initialization.
  4. */
  5. static abstract interface ServiceFetcher<T> {
  6. T getService(ContextImpl ctx);
  7. }

再来看一下SYSTEM_SERVICE_FETCHERS的定义:

  1. private static final HashMap<String, ServiceFetcher<?>> SYSTEM_SERVICE_FETCHERS =
  2.             new HashMap<String, ServiceFetcher<?>>();

可知SYSTEM_SERVICE_FETCHERS是一个HashMap对象,其存放的是<String,ServiceFetcher>键值对,String表示服务名字,ServiceFetcher持有服务对象或者是代理对象。那么接下来我们要研究的就是SYSTEM_SERVICE_FETCHERS是什么put数据的。SYSTEM_SERVICE_FETCHERS存放数据是在registerService方法里面:

  1. /**
  2.      * Statically registers a system service with the context.
  3.      * This method must be called during static initialization only.
  4.      */
  5.     private static <T> void registerService(String serviceName, Class<T> serviceClass,
  6.             ServiceFetcher<T> serviceFetcher) {
  7.         SYSTEM_SERVICE_NAMES.put(serviceClass, serviceName);
  8.         SYSTEM_SERVICE_FETCHERS.put(serviceName, serviceFetcher);
  9.     }

而registerService方法的调用是在SystemServiceRegistry类的静态代码块里面:

  1. static {
  2.         registerService(Context.ACCESSIBILITY_SERVICE, AccessibilityManager.class,
  3.                 new CachedServiceFetcher<AccessibilityManager>() {
  4.             @Override
  5.             public AccessibilityManager createService(ContextImpl ctx) {
  6.                 return AccessibilityManager.getInstance(ctx);
  7.             }});
  8.         registerService(Context.CAPTIONING_SERVICE, CaptioningManager.class,
  9.                 new CachedServiceFetcher<CaptioningManager>() {
  10.             @Override
  11.             public CaptioningManager createService(ContextImpl ctx) {
  12.                 return new CaptioningManager(ctx);
  13.             }});
  14.         registerService(Context.ACCOUNT_SERVICE, AccountManager.class,
  15.                 new CachedServiceFetcher<AccountManager>() {
  16.             @Override
  17.             public AccountManager createService(ContextImpl ctx) {
  18.                 IBinder b = ServiceManager.getService(Context.ACCOUNT_SERVICE);
  19.                 IAccountManager service = IAccountManager.Stub.asInterface(b);
  20.                 return new AccountManager(ctx, service);
  21.             }});
  22.       //目测了一下,这里大概注册了七十多个服务
  23. }

在上面的代码中,我们可以看到返回服务对象的两种方法,一种是通过new或者getInstance直接返回服务对象,比如ACCESIBILITY_SERVICE;而另一种是通过IBinder返回服务的代理对象,比如ACCOUNT_SERVICE。第一种的服务我们就不再跟踪了,其产生机制到这里已经明白了。我们要研究的是第二种服务代理的对象,因为通过代码可以看出这种服务的对象本身不是在这里创建的,是通过ServiceManager.getService方法获取的,所以我们继续看下ServiceManager.getService方法。

5、ServiceManager.getService的源码:

  1. /**
  2. * Returns a reference to a service with the given name.
  3. *
  4. * @param name the name of the service to get
  5. * @return a reference to the service, or <code>null</code> if the service doesn't exist
  6. */
  7. public static IBinder getService(String name) {
  8. try {
  9. IBinder service = sCache.get(name);
  10. if (service != null) {
  11. return service;
  12. } else {
  13. return getIServiceManager().getService(name);
  14. }
  15. } catch (RemoteException e) {
  16. Log.e(TAG, "error in getService", e);
  17. }
  18. return null;
  19. }

从上面代码可知,IBinder对象有两种途径获取,一种是从sCache里面获取,另一种是通过getIServiceManager().getService()方法获取。我们先看第一种从sChache里面获取,sChache是一个HashMap对象,我们来看其存储数据的过程,首先是ServiceManager.initServiceCache方法:

  1. /**
  2. * This is only intended to be called when the process is first being brought
  3. * up and bound by the activity manager. There is only one thread in the process
  4. * at that time, so no locking is done.
  5. *
  6. * @param cache the cache of service references
  7. * @hide
  8. */
  9. public static void initServiceCache(Map<String, IBinder> cache) {
  10. if (sCache.size() != 0) {
  11. throw new IllegalStateException("setServiceCache may only be called once");
  12. }
  13. sCache.putAll(cache);
  14. }

我们再来看看该方法在哪被调用的,该方法是在ActivityThread.bindApplication方法里面调用的,

  1. public final void bindApplication(String processName, ApplicationInfo appInfo,
  2. List<ProviderInfo> providers, ComponentName instrumentationName,
  3. ProfilerInfo profilerInfo, Bundle instrumentationArgs,
  4. IInstrumentationWatcher instrumentationWatcher,
  5. IUiAutomationConnection instrumentationUiConnection, int debugMode,
  6. boolean enableBinderTracking, boolean trackAllocation,
  7. boolean isRestrictedBackupMode, boolean persistent, Configuration config,
  8. CompatibilityInfo compatInfo, Map<String, IBinder> services, Bundle coreSettings) {
  9. if (services != null) {
  10. // Setup the service cache in the ServiceManager
  11. ServiceManager.initServiceCache(services);
  12. }
  13. setCoreSettings(coreSettings);
  14. AppBindData data = new AppBindData();
  15. data.processName = processName;
  16. data.appInfo = appInfo;
  17. data.providers = providers;
  18. data.instrumentationName = instrumentationName;
  19. data.instrumentationArgs = instrumentationArgs;
  20. data.instrumentationWatcher = instrumentationWatcher;
  21. data.instrumentationUiAutomationConnection = instrumentationUiConnection;
  22. data.debugMode = debugMode;
  23. data.enableBinderTracking = enableBinderTracking;
  24. data.trackAllocation = trackAllocation;
  25. data.restrictedBackupMode = isRestrictedBackupMode;
  26. data.persistent = persistent;
  27. data.config = config;
  28. data.compatInfo = compatInfo;
  29. data.initProfilerInfo = profilerInfo;
  30. sendMessage(H.BIND_APPLICATION, data);
  31. }

而ActivityThread.bindApplication是在ActivityManagerService.attachApplicationLocked里面调用的

  1. private final boolean attachApplicationLocked(IApplicationThread thread,
  2. int pid) {
  3. ......
  4. try {
  5. ......
  6. thread.bindApplication(processName, appInfo, providers, app.instrumentationClass,
  7. profilerInfo, app.instrumentationArguments, app.instrumentationWatcher,
  8. app.instrumentationUiAutomationConnection, testMode,
  9. mBinderTransactionTrackingEnabled, enableTrackAllocation,
  10. isRestrictedBackupMode || !normalMode, app.persistent,
  11. new Configuration(mConfiguration), app.compat,
  12. getCommonServicesLocked(app.isolated),
  13. mCoreSettingsObserver.getCoreSettingsLocked());
  14. ......
  15. } catch (Exception e) {
  16. ......
  17. }
  18. ......
  19. return true;
  20. }

而ActivityManagerService.attachApplicationLocked是在ActivityManagerService.attachApplication里面调用的,

  1. @Override
  2. public final void attachApplication(IApplicationThread thread) {
  3. synchronized (this) {
  4. int callingPid = Binder.getCallingPid();
  5. final long origId = Binder.clearCallingIdentity();
  6. attachApplicationLocked(thread, callingPid);
  7. Binder.restoreCallingIdentity(origId);
  8. }
  9. }

而ActivityManagerService.attachApplication是在ActivityThread.attach里面调用的,

  1. private void attach(boolean system) {
  2. sCurrentActivityThread = this;
  3. mSystemThread = system;
  4. if (!system) {
  5. ......
  6. final IActivityManager mgr = ActivityManagerNative.getDefault();
  7. try {
  8. mgr.attachApplication(mAppThread);
  9. } catch (RemoteException ex) {
  10. throw ex.rethrowFromSystemServer();
  11. }
  12. }
  13. }

而ActivityThread.attach又是在ActivityThread.main里面调用的,此处就不贴代码了。我们再返回到ActivityManagerService.attachApplicationLocked的代码里面看看,调用ActivityThread.bindApplication时参数services传的是getCommonServicesLocked(app.isolated),

  1. private HashMap<String, IBinder> getCommonServicesLocked(boolean isolated) {
  2. // Isolated processes won't get this optimization, so that we don't
  3. // violate the rules about which services they have access to.
  4. if (isolated) {
  5. if (mIsolatedAppBindArgs == null) {
  6. mIsolatedAppBindArgs = new HashMap<>();
  7. mIsolatedAppBindArgs.put("package", ServiceManager.getService("package"));
  8. }
  9. return mIsolatedAppBindArgs;
  10. }
  11. if (mAppBindArgs == null) {
  12. mAppBindArgs = new HashMap<>();
  13. // Setup the application init args
  14. mAppBindArgs.put("package", ServiceManager.getService("package"));
  15. mAppBindArgs.put("window", ServiceManager.getService("window"));
  16. mAppBindArgs.put(Context.ALARM_SERVICE,
  17. ServiceManager.getService(Context.ALARM_SERVICE));
  18. }
  19. return mAppBindArgs;
  20. }

可知,services里面最多有三个系统服务的代理对象PackageManagerService、WindowManagerService、AlarmManagerService,并且可以知道这三个服务的获取又绕回到ServiceManager.getService方法,这里可知,当我们的应用进程创建好之后,如果我们获取的是PackageManagerService、WindowManagerService、AlarmManagerService这三者服务,这就从ServiceManager的sCache里面获取,其他服务目前来看,是通过getIServiceManager().getService()方法获取的,看下文讲述。

上面再说ServiceManager的getService方法里面,第二种服务对象的来源getIServiceManager().getService()还没说,这里续上。我们先来看一下getIServiceManager()的源码:

  1. private static IServiceManager getIServiceManager() {
  2. if (sServiceManager != null) {
  3. return sServiceManager;
  4. }
  5. // Find the service manager
  6. sServiceManager = ServiceManagerNative.asInterface(BinderInternal.getContextObject());
  7. return sServiceManager;
  8. }

BinderInternal.getContextObject()返回的是一个BinderProxy对象,所以ServiceManagerNative.asInterface返回对象其实是一个ServiceManagerProxy对象。我们来看一下ServiceManagerProxy的getService代码:

  1. public IBinder getService(String name) throws RemoteException {
  2. Parcel data = Parcel.obtain();
  3. Parcel reply = Parcel.obtain();
  4. data.writeInterfaceToken(IServiceManager.descriptor);
  5. data.writeString(name);
  6. mRemote.transact(GET_SERVICE_TRANSACTION, data, reply, 0);
  7. IBinder binder = reply.readStrongBinder();
  8. reply.recycle();
  9. data.recycle();
  10. return binder;
  11. }

 

总结:

获取系统服务最终都是通过java层先拿到native底层的ServiceManager的代理ServiceManagerProxy,然后通过这个代理从底层获取我们所需服务的代理对象,这个底层就是Binder的底层驱动。

 

其实系统服务start之后,都会通过ServiceManager.addService方法把服务的原始Binder对象对象添加到binder底层中去,不add如何get呢,以PackageManagerService为例,在其main方法中

  1. public static PackageManagerService main(Context context, Installer installer,
  2. boolean factoryTest, boolean onlyCore) {
  3. // Self-check for initial settings.
  4. PackageManagerServiceCompilerMapping.checkProperties();
  5. PackageManagerService m = new PackageManagerService(context, installer,
  6. factoryTest, onlyCore);
  7. m.enableSystemUserPackages();
  8. ServiceManager.addService("package", m);
  9. return m;
  10. }

各种系统服务的启动请请参考我的另一篇博客《SystemServer解析》。

 

好了,本文到这里就把getSystemService的流程分析了一遍,由于才疏学浅只追踪到Java层,再往下Native层的工作就不分析了,请读者们见谅,欢迎多提意见,

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/311049
推荐阅读
相关标签
  

闽ICP备14008679号