Search code examples
androidandroid-servicesystem-services

How to get a service from ServiceManager in Android?


I have a doubt concern the services registered by the ServiceManager and not register by the SystemServiceRegistry.

In the comments of SystemServiceRegistry

/**
 * Manages all of the system services that can be returned by {@link Context#getSystemService}.
 * Used by {@link ContextImpl}.
 */

That means the services registered by System can be get his reference from the Context.

Concern the ServiceManager, how can I access a service added by the ServiceManager in an Application that was not register by the SystemServiceRegistry ?


Solution

  • This answer is really late but another way to access the methods on the Hidden class ServiceManager is using reflection. Since all of the methods on the class are static, you don't need a object reference to pass into the invoke method. You can simply pass in the class instance. In order to get the class instance on a hidden class, you can use a bit more reflection. Example:

    Class localClass = Class.forName("android.os.ServiceManager");
    Method getService = localClass.getMethod("getService", new Class[] {String.class});
    if(getService != null) {
       Object result = getService.invoke(localClass, new Object[]{Context.AUDIO_SERVICE});
       if(result != null) {
          IBinder binder = (IBinder) result;
          // DO WHAT EVER YOU WANT AT THIS POINT, YOU WILL
          // NEED TO CAST THE BINDER TO THE PROPER TYPE OF THE SERVICE YOU USE.
       }
    }
    

    This is pretty much all you need to do to access hidden or private methods (Albeit with private methods, you need to modify the access of the method). I am aware that reflection is bad in Android and their are usually good reasons why some API's aren't exposed but there are some valid use-cases to use it. If you're are not calling the reflected code a lot, the performance hit isn't terrible and if you are, you can cache the methods so you don't have to perform the lookups on every call. With that being said, be careful and analyse if you really need to access non-public API's.