We need to register our service with the Android system and create an object. The Service Manager is a component that maintains a mapping of the service name and the associated service object. Processes invoke the Service Manager to obtain a reference to the system server by name. The method invoked to obtain a reference to a service object is ServiceManager.getService(String)
. You can think of the Service Manager as a directory service that is available to service consumers.
We will add our custom server to SystemServer.java
located at ANDROID_SRC/frameworks/base/services/java/com/android/server
.
The following code represents modifications you need to make to the SystemServer.java
file. Locate the run()
method and add the following lines at an appropriate location. For the purpose of illustration, we choose to add this after all services have been started.
... //begin packt Slog.i(TAG, "PacktCrypto service"); com.android.packt.PacktCrypto pcrypt = com.android.packt.PacktCrypto.getInstance(); ServiceManager.addService("PacktCryptoService", pcrypt); //end packt …
The preceding code modification obtains a reference to an object of type PacktCrypto
. It then adds that object to the ServiceManager
class, which, if you recall, is a directory service for all system services. It adds the PacktCrypto
object to the directory by invoking the addService()
method that takes as arguments a string service identifier and the object itself.
In the code fragment, we must create an object of PacktCrypto
and add it to the Service Manager directory with a string name. We choose PacktCryptoService
for our example. At this stage, our custom server will be created and registered with the Service Manager.