AOSP – Creating a System Service

In the previous post, we built a native daemon in Android native layer. We wrote a simple application to communicate with the daemon using a socket (UDS/UDP/TCP). Most of the services provided by Android using the Android Framewok layer

If for example, the camera application wants to get the current GPS location, it connects to the Location service using the binder. The service load the hardware module using the HAL and returns the position.

To create a system service, we need the following components:

  • AIDL service interface
  • Application to host the service(s)
  • Client library for untrusted applications (from the play store) to use the service
  • Simple client application for testing our service

AIDL and the Client Library

We start with the AIDL file that will generate the stub and proxy. We also build a Manager class for the client application.

Create a folder framework in ~/aosp/device/generic/goldfish

Add a general file to scan the child directories


include $(call all-subdir-makefiles)

Build the following directory structure:



interface ISampService {
  int add(int a,int b);
  int sub(int a,int b);


import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.util.Log;
import android.util.Slog; 
import java.util.HashSet;
import java.util.Set;

public class SampManager {
  private static final String REMOTE_SERVICE_NAME = ISampService.class.getName();  
  private final ISampService service;
  public static SampManager getInstance() {
    return new SampManager();

    public int add(int a,int b) 
		return service.add(a,b);
	}catch(Exception ec){}
	return 0;

   public int sub(int a,int b) 
		return service.sub(a,b);
	}catch(Exception ec){}
	return 0;

  private SampManager() {
    this.service = ISampService.Stub.asInterface(
    if (this.service == null) {
      throw new IllegalStateException("Failed to find ISampService by name [" + REMOTE_SERVICE_NAME + "]");

LOCAL_PATH := $(call my-dir)

# Build the library
include $(CLEAR_VARS)
LOCAL_SRC_FILES := $(call all-java-files-under,.)
LOCAL_SRC_FILES += com/android/sampservice/ISampService.aidl

# Copy to /system/etc/permissions/
include $(CLEAR_VARS)

To let the untrusted application access the library we need to add a permission file:

<?xml version="1.0" encoding="utf-8"?>
  <library name=""

The purpose of the permission file is to tell the system where to find the required library so if untrusted application wants to use the library, it should add <uses-library  …. /> tag to AndroidManifest.xml file with the required name

The generated components are: jar file to access the service and xml file for permission

The Service Implementation

To build the service we need to implement the interface and write an application to host it. We can use the system_server but its a bad practice to merge our code with google’s code.

Create a folder app in ~/aosp/device/generic/goldfish

Add a general file to scan the child directories


include $(call all-subdir-makefiles)

Build the following directory structure:

The service implementation

We need to derive from the Stub class and simply implement the interface



import android.os.Binder;
import android.os.IBinder;
import android.os.RemoteException;

class ISampServiceImpl extends ISampService.Stub {

  public int add(int a,int b) {

    return a+b ;                           

  public int sub(int a,int b) {
    return a-b;                           


Now we create an application to host the service. We need to create an object from our implementation and add it to the Service Manager (the binder context)


import android.os.ServiceManager;
import android.util.Log;

public class SampServiceApp extends Application {
  private static final String REMOTE_SERVICE_NAME = ISampService.class.getName();
  private ISampServiceImpl serviceImpl;

  public void onCreate() {
    this.serviceImpl = new ISampServiceImpl();
    ServiceManager.addService(REMOTE_SERVICE_NAME, this.serviceImpl);

  public void onTerminate() {

To build a system application we need to update the AndroidManifest.xml file.

  • To make it run as system user add android:sharedUserId=”android.uid.system”
  • To make it run automatically on startup add android:persistent=”true”
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
  <application android:name=".SampServiceApp" android:persistent="true"> 
    <uses-library android:name="" />    

The following build the package (apk)

LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
LOCAL_SRC_FILES := $(call all-java-files-under,src)
include $(BUILD_PACKAGE)

Note the platform certificate we need to sign the application (LOCAL_CERTIFICATE := platform , LOCAL_PRIVILEGED_MODULE := true)

Build and run the emulator – You will see that the service is not running and in the log you will see the following error:

01-01 00:02:44.148  1819  1819 E SELinux : avc:  denied  { add } for pid=16277 uid=1000 scontext=u:r:system_app:s0 tcontext=u:object_r:my_service:s0 tclass=service_manager permissive=0
01-01 00:02:44.148  1819  1819 E ServiceManager: add_service('',7b) uid=1000 - PERMISSION DENIED
01-01 00:02:44.150 16277 16277 D AndroidRuntime: Shutting down VM
01-01 00:02:44.151 16277 16277 E AndroidRuntime: FATAL EXCEPTION: main
01-01 00:02:44.151 16277 16277 E AndroidRuntime: Process:, PID: 16277
01-01 00:02:44.151 16277 16277 E AndroidRuntime: java.lang.RuntimeException: Unable to create application java.lang.SecurityException
01-01 00:02:44.151 16277 16277 E AndroidRuntime: 	at
01-01 00:02:44.151 16277 16277 E AndroidRuntime: 	at Source:0)

We need to add SE Linux permissions:

SE Linux

Declare the new type my_service in public/service.te:

type my_service, system_api_service,  service_manager_type;

In service_contexts file label the service	  u:object_r:my_service:s0

Add rule: (in public/servicemanager.te)

allow system_app my_service:service_manager add;

In android 8.1 google added a new policy language  called the Common Intermediate Language (CIL). To add a system service you need:

in file system/sepolicy/private/compat/26.0/26.0.cil

(typeattributeset my_service_26_0 (my_service))

in file /system/sepolicy/prebuild/api/26.0/nonplat_sepolicy.cil

(typeattribute my_service_26_0)
(roletype object_r my_service_26_0)

and add my_service to the line

(typeattributeset service_manager_type (audioserver_service_26_0 , ... , my_service_26_0


Build and run the emulator again, you will see the service running


Create a client Application

First we need to create a jar file for the application developer. The project in Android Studio depends on that library

In AOSP root, run the following command:

# make

You will find the file classes-full-debug.jar in out/target/common/obj/JAVA_LIBRARIES/

Create a new Android Studio application, add module and select import jar

import the above jar file and click finish

In the application module settings add module dependency to the jar file module and select compile only


To use the library from the device we need to add <uses-library> tag to the manifest file:


        <uses-library android:name="" android:required="true" />

        <activity android:name=".MainActivity">
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />


Now just create an object from the SampManager class and use it:

SampManager man = SampManager.getInstance();
Log.d("calling system service", "res:" + man.add(100,200));


Last thing we need to add SE Linux rule to allow untrusted application. Add the following rule to the untrusted_app.te file

allow untrusted_app my_service:service_manager { find };


Run the application on the emulator and use logcat to see the results



Tagged , ,

12 thoughts on “AOSP – Creating a System Service

  1. Hello It is very helpful to me,
    Thank you for the post. I am trying to investigate also how can we use Binder to communicate with currently systemServices which already available like ActivityManager, WindowManager and how to influences it also.
    eg : Tell ActivityManager to kill and app or Pause a app..
    I know that AOSP allow me to do that somehow but it will be nice to learn from your experiences .
    Thank you,

  2. “allow system_app my_service:service_manager add;”
    This line conflicts with “neverallow” rules (AOSP compilation fails) and without it the service FAILS because of INSUFFICIENT permissions. Is there any workaround for this?

    1. Hi Stanislav,
      Did you find any solution for this issue?

  3. Hi,
    I am getting issue like when build and run emulator
    “ninja: error: ‘/AndroidManifest.xml’, needed by ‘out/target/product/generic/obj/APPS/SampServiceApp_intermediates/package.apk’, missing and no known rule to make it
    17:03:48 ninja failed with: exit status 1
    build/core/ recipe for target ‘run_soong_ui’ failed
    make: *** [run_soong_ui] Error 1

    Can you help on this.

    i followed everything what you said above

  4. Hi Team,
    After successfully completed the service implement to project i am getting exception like below..
    E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.kundasub.myapplication, PID: 2734
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.kundasub.myapplication/com.example.kundasub.myapplication.MainActivity}: java.lang.IllegalStateException: Failed to find ISampService by name []
    at Source:0)
    at android.os.Handler.dispatchMessage(
    at android.os.Looper.loop(
    at java.lang.reflect.Method.invoke(Native Method)
    Caused by: java.lang.IllegalStateException: Failed to find ISampService by name []
    at com.example.kundasub.myapplication.MainActivity.onCreate(

  5. Hi,
    I added the policies in my target policy folder: device/xx/sepolicy/, like service.te, service_contexts, xxx_service.te, system_server.te, but still see the violation, like:

    denied { add } for service=xxx.service scontext=u:r:xxx_Service:s0 tcontext=u:object_r:default_android_service:s0 tclass=service_manager

    Then i tried to update the cil file in system/sepolicy/, but build failed because the service is defined in device folder. Is there any other way to resolve this issue?

  6. Nice example.
    I wanted to create a custom Manager or System Service, which can save data to sqlitedb and also perform network operation.

    Any help will be appreciated.


  7. Sorry to revive an old thread. Am I correct in assuming you need a rooted device to be able to do this?

    1. Nevermind I didn’t notice AOSP at first.

  8. Thank you!
    You are a lifesaver!
    it’s working!

  9. Hey Liran,

  10. Hey Liran
    I am getting error while building JAR
    FAILED: ninja: unknown target ‘’
    16:13:08 ninja failed with: exit status 1

Comments are closed.