Android System Services Patterns

Android has around 100 system services, providing various system functionality and services. Applications run in their own process and communicate with those system services through client class, aka all kinds of Managers, which talks to the service through Binder.

In this article, we will exam Android system service implementation patterns.


1. Client: get a client to access the system services

The most common way to get a client is to call  context.getSystemService(XXXX_SERVICE)
and you will be returned an XxxxManager. Or, be explicit, call context.getPackageManager().
Finally, new a client yourself, e.g new MediaPlayer().

2. Connect : Those XxxxManagers are actually a wrapper of the proxy side of the corresponding service and they always connect to the service with Binder. Following code snippet illustrates the pattern ,assuming XxxxManager is the client of XxxxServices,

    class XxxxManager {
           IXxxxService mXxxxServcie;
           XxxxManager() {
           mXxxxServcie = IXxxxService.Stub.asInterface(
                                                ServiceManager.getService(XXXX_SERVICE_BINDER_NAME));
          }
    }

Where the IXxxxService.Stub.asInterface(ob) simply returns IXxxxxService.Stub.Proxy(obj), which is a proxy side of service. 

3. Services and Server

The services are either hosted in system_server, or one of the native servers, such as mediaserver, surfaceflinger. 

For the services hosted in the system server, there are four varieties. 
  • The service is complete java based, no native code is needed. e.g PackageManagerService.
  • The service has native code, e.g. ComsuerIrService.
  • The service in turn connects to the system daemon with socket, e.g MountService talks to vold.
  • The service connects to another native services, e.g. DisplayManagerService connects to SurfaceFlinger through SurfaceControl class. In this case, DisplayManagerService acts like a client of SurfaceFlinger.
The XxxManager can also connect to the native service directly.
  • CameraManager connects to native CameraService directly through a java wrapper to ServiceManager.
  • SensorManager connects to native SensorServices through the jni. Or, MediaPlayer connects directly to native MediaPlayerService.
Following diagram visualizes what we just talked. 
Android System Services Pattern
Please click here for a complete list of the android system services and their implementation details, including the interface file, client class and server class. Note that this is a unfinished work and I am sure it will never be finished....since the number of services is just too much.. However, once you understand the patterns explained in this article, there is no necessity of checking each and every services. They just look similar and fall into the patterns we talked here. If it is not yet, let me know and I will add it :)