<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ankityadav on Medium]]></title>
        <description><![CDATA[Stories by Ankityadav on Medium]]></description>
        <link>https://medium.com/@ankityadav91?source=rss-0a6a741e53b2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TB7hZDvsOwVFivlDsD23MQ.jpeg</url>
            <title>Stories by Ankityadav on Medium</title>
            <link>https://medium.com/@ankityadav91?source=rss-0a6a741e53b2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 19:48:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ankityadav91/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Create a Custom System Service and Listener in AOSP using JNI (Android Open Source Project)]]></title>
            <link>https://ankityadav91.medium.com/how-to-create-a-custom-system-service-and-listener-in-aosp-using-jni-android-open-source-project-aadd84e16454?source=rss-0a6a741e53b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/aadd84e16454</guid>
            <category><![CDATA[andorid]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[social-media]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ankityadav]]></dc:creator>
            <pubDate>Thu, 26 Jun 2025 07:39:24 GMT</pubDate>
            <atom:updated>2025-06-26T07:39:24.026Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>1. Introduction</strong></h3><h4><strong>What is a System Service?</strong></h4><p>System services in Android are essential components that run in the background to provide various functionalities such as network management, power control, media handling, and more. These services expose APIs through which apps and other services can interact with system-level features, abstracting the complexity of low-level hardware or OS tasks.</p><p><em>Examples of System Services: Notification Service, Alarm Manager Service, Power Service, Battery Service, Package Manager Service…</em></p><h4>About This Service</h4><p>we’ll walk through creating and integrating a custom Android system service named AnkitService. Once triggered via an application, it sends a timestamp every second and allows interaction through a listener interface.It can be interacted with through AIDL, and clients can register/unregister listeners to receive timestamp updates.</p><h4><strong>Project File Structure</strong></h4><p>AOSP14/<br>├── frameworks/<br>│ ├── base/<br>│ │ ├── core/<br>│ │ │ ├── java/android/hardware/ankit/<br>│ │ │ │ ├── AnkitManager.java<br>│ │ │ │ ├── AnkitListener.java<br>│ │ │ │ ├── IAnkitManager.aidl<br>│ │ │ │ └── IAnkitListener.aidl<br>│ │ ├── api/current.txt<br>│ │ └── Android.bp<br>│ ├── services/<br>│ │ ├── core/<br>│ │ │ ├── java/com/android/server/<br>│ │ │ │ └── AnkitManagerService.java<br>│ │ │ ├── jni/<br>│ │ │ │ └── com_android_server_ANKITService.cpp<br>│ │ │ └── jni/onload.cpp</p><p>Here’s a breakdown of the flow:</p><p><strong>1. Java Application:</strong></p><p>The Android application initiates the interaction by calling a Java method that is declared as native. This method acts as the entry point for JNI calls.</p><p><strong>2. JNI Interface (Java to Native):</strong></p><p>The JNI (Java Native Interface) acts as a bridge between the Java code and native C/C++ code. When the native method is called, the JNI layer is invoked. This layer translates the Java method call into a C/C++ function call.</p><p><strong>3. Native Implementation (C/C++):</strong></p><p>The C/C++ code, defined in a separate library (e.g., .so file), receives the JNI call and executes its logic. This might involve interacting with the system, performing calculations, or accessing hardware resources.</p><p><strong>4. Result Return (Native to Java):</strong></p><p>After the native code completes its operations, it can return a result back to the Java layer. This result is typically packaged and passed back through the JNI interface.</p><p><strong>5. Java Handling (Result):</strong></p><p>The Java method receives the result from the native code and can then process or display it as needed</p><h3>2.Steps to Create a Custom System Service</h3><h3>Writing the Service</h3><h3>Native Layer:</h3><p>An Android service using JNI (Java Native Interface) to interact with native C/C++ code typically involves a flow where the Android application calls a Java method, which in turn calls a native method through JNI. This native method, implemented in C/C++, performs some operations and potentially returns a result back to the Java layer. This allows leveraging native code for performance-critical tasks or accessing platform-specific functionalities not readily available in Java.</p><ul><li><strong>Performance:</strong></li><li>JNI can improve performance by leveraging optimized native code, especially for tasks like image processing, cryptography, or hardware interactions.</li><li><strong>Code Reuse:</strong></li><li>It allows reusing existing C/C++ libraries within the Android application.</li><li><strong>Platform Specificity:</strong></li><li>JNI is useful for accessing platform-specific features or hardware components that are not directly accessible from Java.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/0*pXsNp0L35BKh28bm.png" /></figure><h4>com_android_server_ANKITService.cpp</h4><blockquote>Path:</blockquote><blockquote>frameworks/services/core/jni/com_android_server_ANKITService.cpp</blockquote><p>This native layer uses JNI to send timestamps from C++ to the Java layer.</p><pre>#define LOG_TAG &quot;AnkitServiceJNI&quot;<br>#include &lt;jni.h&gt;<br>#include &lt;utils/Log.h&gt;<br>#include &lt;thread&gt;<br>#include &lt;chrono&gt;<br><br>namespace android {<br><br>static JavaVM* javaVM = nullptr;<br>static jobject serviceObject = nullptr;<br>static jclass serviceClass = nullptr;<br><br>void sendTimestamp() {<br>    JNIEnv* env;<br>    javaVM-&gt;AttachCurrentThread(&amp;env, nullptr);<br>    jmethodID methodID = env-&gt;GetMethodID(serviceClass, &quot;onTimestampReceived&quot;, &quot;(J)Ljava/lang/String;&quot;);<br><br>    while (true) {<br>        auto now = std::chrono::system_clock::now();<br>        long timestamp = std::chrono::duration_cast&lt;std::chrono::milliseconds&gt;(now.time_since_epoch()).count();<br><br>        jstring result = (jstring)env-&gt;CallObjectMethod(serviceObject, methodID, timestamp);<br>        env-&gt;ReleaseStringUTFChars(result, env-&gt;GetStringUTFChars(result, 0));<br>        std::this_thread::sleep_for(std::chrono::seconds(1));<br>    }<br><br>    javaVM-&gt;DetachCurrentThread();<br>}<br><br>static jstring nativestartSendingTimestamps(JNIEnv* env, jobject obj) {<br>    env-&gt;GetJavaVM(&amp;javaVM);<br>    serviceClass = (jclass) env-&gt;NewGlobalRef(env-&gt;GetObjectClass(obj));<br>    serviceObject = env-&gt;NewGlobalRef(obj);<br><br>    std::thread(sendTimestamp).detach();<br>    return env-&gt;NewStringUTF(&quot;Started&quot;);<br>}<br><br>static const JNINativeMethod sMethods[] = {<br>    {&quot;nativestartSendingTimestamps&quot;, &quot;()Ljava/lang/String;&quot;, (void *)nativestartSendingTimestamps},<br>};<br><br>int register_android_server_AnkitService(JNIEnv* env) {<br>    return jniRegisterNativeMethods(env, &quot;com/android/server/AnkitManagerService&quot;, sMethods, NELEM(sMethods));<br>}<br><br>}</pre><p>Key Responsibilities:</p><ul><li>Attaches to JVM</li><li>Starts a thread sending timestamps every second</li><li>Invokes a Java method and stores the latest timestamp</li></ul><h3>Service Implementation: AnkitManagerService.java</h3><blockquote><strong>Path:</strong></blockquote><blockquote>frameworks/services/core/java/com/android/server/AnkitManagerService.java</blockquote><p><strong>AnkitManagerService</strong> manages listeners for receiving timestamp updates. It uses JNI (Java Native Interface) to interact with native code that generates and sends timestamps. The service allows clients to register or unregister listeners, who are notified whenever a new timestamp is received.</p><pre>package com.android.server;<br><br>import android.content.Context;<br>import android.hardware.ankit.IAnkitManager;<br>import android.hardware.ankit.IAnkitListener;<br>import android.util.Log;<br><br>import java.util.ArrayList;<br><br>public class AnkitManagerService extends IAnkitManager.Stub {<br><br>    private final ArrayList&lt;IAnkitListener&gt; mListeners = new ArrayList&lt;&gt;();<br>    private static final String TAG = &quot;AnkitService&quot;;<br>    private Context mContext;<br><br>    public AnkitManagerService(Context context) {<br>        super();<br>        mContext = context;<br>        Log.i(TAG, &quot;AnkitManagerService Service Started&quot;);<br>    }<br><br>    @Override<br>    public void registerListener(IAnkitListener listener) {<br>        synchronized (mListeners) {<br>            if (!mListeners.contains(listener)) {<br>                mListeners.add(listener);<br>                Log.i(TAG,&quot;registerListener&quot; );<br>              <br>            }<br>        }<br>    }<br><br>    @Override<br>    public void unregisterListener(IAnkitListener listener) {<br>        synchronized (mListeners) {<br>            mListeners.remove(listener);<br>            Log.i(TAG,&quot;unregisterListener&quot; );<br>            <br>        }<br>    }<br><br>   <br><br>    @Override<br>    public String startSendingTimestamps() {<br>        return nativestartSendingTimestamps();<br>    }<br><br>    <br>    public String onTimestampReceived(long timestamp) {<br>        Log.i(TAG, &quot;Timestamp received: &quot; + timestamp);<br>        notifyListeners(timestamp);<br>        return &quot;Received timestamp: &quot; + timestamp;<br>    }<br><br>    private void notifyListeners(long timestamp) {<br>        synchronized (mListeners) {<br>            for (IAnkitListener listener : mListeners) {<br>                try {<br>                    listener.onTimestampReceived(timestamp);<br>                } catch (Exception e) {<br>                   <br>                }<br>            }<br>        }<br>    }<br><br>   <br>    private native String nativestartSendingTimestamps();  <br>}</pre><p>Key Responsibilities:</p><ul><li>Interacts with native layer</li><li>Manages a list of IAnkitListener clients</li><li>Sends periodic timestamp updates via callbacks</li></ul><h3>Interface: AnkitListener.java</h3><blockquote><strong>Path:</strong></blockquote><blockquote>frameworks/base/core/java/android/hardware/ankit/AnkitListener.java</blockquote><p>Interface for receiving timestamp updates . onTimestampReceived(long timestamp): This method is called when a new timestamp is received from the AnkitService.</p><pre>/*<br> * Copyright (C) 2008 The Android Open Source Project<br> *<br> * Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);<br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at<br> *<br> *      http://www.apache.org/licenses/LICENSE-2.0<br> *<br> * Unless required by applicable law or agreed to in writing, software<br> * distributed under the License is distributed on an &quot;AS IS&quot; BASIS,<br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.<br> * See the License for the specific language governing permissions and<br> * limitations under the License.<br> */<br><br>package android.hardware.ankit;<br><br>import androidx.annotation.NonNull;<br><br>/**<br> * Listener interface to receive timestamp updates from AnkitManager.<br> */<br>public interface AnkitListener {<br><br>    /**<br>     * Called when a new timestamp is received.<br>     *<br>     * @param timestamp The timestamp received from the service.<br>     */<br>    void onTimestampReceived(long timestamp);<br>}</pre><p>Apps or services can implement this to receive updates.</p><h3>Manager Class : AnkitManager.java</h3><blockquote>Path:</blockquote><blockquote><strong>frameworks/base/core/java/android/hardware/ankit/AnkitManager.java</strong></blockquote><p>Provides methods for interacting with the AnkitService, such as registering/unregistering listeners and starting timestamp updates.</p><pre>package android.hardware.ankit;<br><br>import android.annotation.NonNull;<br>import android.annotation.SystemService;<br>import android.content.Context;<br>import android.os.RemoteException;<br>import android.util.Log;<br><br>import androidx.annotation.Nullable;<br><br>import java.util.concurrent.Executor;<br><br>/**<br> * This class allows you to interact with the ankit device.<br> *<br> * &lt;p&gt;You can obtain an instance of this class by calling<br> * {@link android.content.Context#getSystemService(java.lang.String) Context.getSystemService()}.<br> * &lt;br&gt;<br> * &lt;pre&gt;<br> * {@code<br> * AnkitManager ankit = (AnkitManager) getSystemService(ANKIT_SERVICE);<br> * &lt;/pre&gt;<br> *<br> */<br>@SystemService(Context.ANKIT_SERVICE)<br>public final class AnkitManager {<br><br>    private static final String TAG = &quot;AnkitManager&quot;;<br>    private final Context mContext;<br>    private final IAnkitManager mAnkitManager;<br><br>    /**<br>     * Starts sending timestamps.<br>     *<br>     * @return A string indicating the status of the operation.<br>     */<br>    @Nullable<br>    public String startSendingTimestamps() {<br>        try {<br>            return mAnkitManager.startSendingTimestamps();<br>        } catch (RemoteException e) {<br>            Log.e(TAG, &quot;Failed to start sending timestamps&quot;, e);<br>            return &quot;Failed to start sending timestamps&quot;;<br>        }<br>    }<br><br>    /**<br>     * Registers a listener to receive timestamps.<br>     *<br>     * @param listener The listener to register.<br>     */<br>    public void addListener(@NonNull AnkitListener listener) {<br>        try {<br>            mAnkitManager.registerListener(new IAnkitListener.Stub() {<br>                @Override<br>                public void onTimestampReceived(long timestamp) throws RemoteException {<br>                    listener.onTimestampReceived(timestamp);<br>                }<br>            });<br>        } catch (RemoteException e) {<br>            Log.e(TAG, &quot;Failed to add listener&quot;, e);<br>        }<br>    }<br><br>    /**<br>     * Registers a listener to receive timestamps, with an Executor for thread management.<br>     *<br>     * @param listener The listener to register.<br>     * @param executor The executor to run the callback on.<br>     */<br>    public void addListener(@NonNull Executor executor,@NonNull AnkitListener listener) {<br>        try {<br>            mAnkitManager.registerListener(new IAnkitListener.Stub() {<br>                @Override<br>                public void onTimestampReceived(long timestamp) throws RemoteException {<br>                    executor.execute(() -&gt; listener.onTimestampReceived(timestamp));<br>                }<br>            });<br>        } catch (RemoteException e) {<br>            Log.e(TAG, &quot;Failed to add listener with executor&quot;, e);<br>        }<br>    }<br><br>    /**<br>     * Unregisters a listener from receiving timestamps.<br>     *<br>     * @param listener The listener to unregister.<br>     */<br>    public void removeListener(@NonNull AnkitListener listener) {<br>        try {<br>            mAnkitManager.unregisterListener(new IAnkitListener.Stub() {<br>                @Override<br>                public void onTimestampReceived(long timestamp) throws RemoteException {<br>                    listener.onTimestampReceived(timestamp);<br>                }<br>            });<br>        } catch (RemoteException e) {<br>            Log.e(TAG, &quot;Failed to remove listener&quot;, e);<br>        }<br>    }<br><br>    /**<br>     * {@hide}<br>     */<br>    public AnkitManager(Context context, IAnkitManager service) {<br>        mContext = context;<br>        mAnkitManager = service;<br>    }<br>}</pre><p>Key Responsibilities:</p><ul><li>Binds to the custom system service through ServiceManager</li><li>Establishes communication via JNI to native code</li><li>Sends configuration or control commands to the native layer</li><li>Receives updates (like sensor data or timestamps) from the native daemon or service</li><li>Maintains a cached reference to the listener or callback interface</li><li>Exposes high-level APIs for Android apps to interact with the service</li><li>Handles permission checks and context management when interacting with system services</li></ul><h3>AIDL Interfaces :</h3><h4>IAnkitManager.aidl</h4><blockquote><strong>Path:</strong></blockquote><blockquote>frameworks/base/core/java/android/hardware/ankit/IAnkitManager.aidl</blockquote><p>Defines service methods for starting timestamp sending and managing listeners.</p><pre>/*<br> * Copyright (C) 2017 The Android Open Source Project<br> *<br> * Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);<br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at<br> *<br> *      http://www.apache.org/licenses/LICENSE-2.0<br> *<br> * Unless required by applicable law or agreed to in writing, software<br> * distributed under the License is distributed on an &quot;AS IS&quot; BASIS,<br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.<br> * See the License for the specific language governing permissions and<br> * limitations under the License.<br> */<br>package android.hardware.ankit;<br><br>import android.os.ParcelFileDescriptor;<br>import android.hardware.ankit.IAnkitListener;<br><br>/** @hide */<br>interface IAnkitManager { <br> <br> String startSendingTimestamps();<br>  String onTimestampReceived(long timestamp);<br>   void registerListener(IAnkitListener listener);<br>  void unregisterListener(IAnkitListener listener);<br>}</pre><h4>IAnkitListener.aidl</h4><blockquote><strong>Path:</strong></blockquote><blockquote>frameworks/base/core/java/android/hardware/ankit/IAnkitListener.aidl</blockquote><p>Allows the service to push timestamp updates to the app using callbacks.</p><pre>/*<br> * Copyright (C) 2017 The Android Open Source Project<br> *<br> * Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);<br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at<br> *<br> *      http://www.apache.org/licenses/LICENSE-2.0<br> *<br> * Unless required by applicable law or agreed to in writing, software<br> * distributed under the License is distributed on an &quot;AS IS&quot; BASIS,<br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.<br> * See the License for the specific language governing permissions and<br> * limitations under the License.<br> */// AnkitListener.aidl<br>package android.hardware.ankit;<br>/** {@hide} */<br>interface IAnkitListener {<br>    void onTimestampReceived(long timestamp);<br>}</pre><h3>3. Service Integration in AOSP</h3><p>To fully integrate your service in AOSP:</p><h4>Edit current.txt</h4><blockquote><strong>Path:</strong></blockquote><blockquote>frameworks/base/api/current.txt</blockquote><p>Add:</p><blockquote><em>field public static final String ANKIT_SERVICE = “ankit”;</em></blockquote><h4>Modify Android.bp</h4><p>In frameworks/base/core/java/Android.bp:</p><pre>filegroup {<br>    name: &quot;IAnkitManager.aidl&quot;,<br>    srcs: [&quot;android/hardware/ankit/IAnkitManager.aidl&quot;],<br>}</pre><p>In services/core/jni/Android.bp:</p><pre>&quot;com_android_server_ANKITService.cpp&quot;,</pre><h4>Modify SystemServiceRegistry.java</h4><blockquote><strong>Path:</strong></blockquote><blockquote>frameworks/base/core/java/android/app/SystemServiceRegistry.java</blockquote><p>Add imports and register your service:</p><pre>import android.hardware.ankit.AnkitManager;<br>import android.hardware.ankit.IAnkitManager;<br><br>registerService(Context.ANKIT_SERVICE, AnkitManager.class,<br>    new CachedServiceFetcher&lt;AnkitManager&gt;() {<br>        public AnkitManager createService(ContextImpl ctx)<br>                throws ServiceNotFoundException {<br>            IBinder b = ServiceManager.getService(Context.ANKIT_SERVICE);<br>            return new AnkitManager(ctx, IAnkitManager.Stub.asInterface(b));<br>        }<br>});</pre><h4>Add ANKIT_SERVICE in Context.java</h4><blockquote><strong>Path:</strong></blockquote><blockquote>frameworks/base/core/java/android/content/Context.java</blockquote><pre>public static final String ANKIT_SERVICE = &quot;ankit&quot;;</pre><h4>Register Native Service</h4><blockquote><strong>Path:</strong></blockquote><blockquote>frameworks/services/core/jni/onload.cpp</blockquote><pre>int register_android_server_AnkitService(JNIEnv* env);<br>register_android_server_AnkitService(env);</pre><h4>Start Service in SystemServer.java</h4><blockquote><strong>Path:</strong></blockquote><blockquote>frameworks/base/services/java/com/android/server/SystemServer.java</blockquote><pre>t.traceBegin(&quot;AddAnkitService&quot;);<br>ServiceManager.addService(Context.ANKIT_SERVICE, new AnkitManagerService(context));<br>t.traceEnd();</pre><h3>4. Build the AOSP and Test</h3><h4>Build Commands:</h4><pre>source build/envsetup.sh<br>lunch &lt;your_target&gt;<br>make -j$(nproc)</pre><h4>Run Emulator and Verify Service</h4><pre>adb shell service list | grep &quot;AnkitService&quot;</pre><h3>Troubleshooting Common Issues and Testing:</h3><p>Service not starting, we can see from the below logs our service not started in the boot time.</p><h3>Issues</h3><p><strong>1. Problem: Service not found</strong></p><ul><li><strong>Cause:</strong> Service is not registered with ServiceManager.</li><li><strong>Solution:</strong> Make sure to call ServiceManager::addService() with the correct service name during system startup.</li></ul><p><strong>2. Problem: </strong><strong>Permission denied in logs</strong></p><ul><li><strong>Cause:</strong> SELinux is blocking access to the service.</li><li><strong>Solution:</strong> Run logcat or dmesg, then use audit2allow to generate the required allow rules and update your sepolicy.</li></ul><p><strong>3. Problem: App can’t bind to the service</strong></p><ul><li><strong>Cause:</strong> Missing or incorrect permission setup.</li><li><strong>Solution:</strong> Check the AIDL interface for permission tags and ensure the required permissions are declared in your app’s manifest.</li></ul><p><strong>4. Problem: JNI crashes</strong></p><ul><li><strong>Cause:</strong> Native method signatures do not match Java declarations.</li><li><strong>Solution:</strong> Confirm the method names and signatures in C++ exactly match those declared in Java (including parameter types).</li></ul><p><strong>5. Problem: Service not loading on boot</strong></p><ul><li><strong>Cause:</strong> The service is not added in SystemServer.java.</li><li><strong>Solution:</strong> Ensure your service is properly registered in SystemServer.java</li></ul><h4>Boot Time Log Check (replace AnkitService with actual your service name)</h4><p>Service not starting, we can see from the below logs our service not started in the boot time</p><pre>adb logcat | grep AnkitService<br>01-19 01:04:46.553   653   653 I SystemServerTiming: AnkitService<br>01-19 01:04:46.553   653   653 E SystemServer: BOOT FAILURE starting AnkitService<br>01-19 01:04:46.554   653   653 D SystemServerTiming: AnkitService took to complete: 1ms</pre><ol><li><strong>Check AVC Denial</strong></li></ol><pre>adb shell dmesg | grep avc<br># or<br>adb logcat | grep denied<br><br>01-19 01:08:25.768 195 195 E SELinux : avc: denied { add } for pid=648 uid=1000 name=ankit scontext=u:r:system_server:s0 tcontext=u:object_r:default_android_service:s0 tclass=service_manager permissive=0</pre><h3>Fix Steps</h3><h4>Add Service Labeling in service_contexts</h4><blockquote>system/sepolicy/private/service_contexts</blockquote><p>Add these lines:</p><pre>yourservice     u:object_r:yourservice_service:s0</pre><blockquote>yourservice = your service name<br> yourservice_service = custom SELinux type we’ll define next</blockquote><h4>Define a New Type in service.te</h4><blockquote>system/sepolicy/private/service.te</blockquote><p>Add these lines:</p><pre>type yourservice_service, system_api_service, service_manager_type;</pre><h4>Allow system_server to Add and Use Your Service</h4><blockquote>system/sepolicy/private/system_server.te</blockquote><p>Add these lines:</p><pre>allow system_server yourservice_service:service_manager { add find };</pre><h4>Recompile SEPolicy and Build AOSP</h4><p>Run full build again (or at least sepolicy + system image):</p><h3>Conclusion</h3><p>Creating a custom system service in Android involves defining an AIDL interface, implementing the service, and registering it with the <strong>System Server</strong>. Debugging and SELinux policies are critical for ensuring the service runs properly. In the upcoming article, we will discuss how to create the system service in an optimized way.</p><p>With these steps, you’ve successfully added a custom system service in AOSP backed by native code and accessible from apps via AnkitManager. This pattern is powerful for building real-time services like sensors, external devices, or native hardware modules.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aadd84e16454" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>