新博客地址 http://wossoneri.github.io/2018/09/15/[Android][Framework]create system service/ 做系統開發,有時候需要自己定義一些介面供App使用, 同時為了方便維護管理,就會需要自己建立一個服務,把新的功能集中在一起。下 ...
新博客地址
http://wossoneri.github.io/2018/09/15/[Android][Framework]create-system-service/
做系統開發,有時候需要自己定義一些介面供App使用, 同時為了方便維護管理,就會需要自己建立一個服務,把新的功能集中在一起。下麵就是新建一個系統服務的基本步驟。
添加介面
frameworks/base/core/java/android/app/IDemoManager.aidl
package android.app; interface IDemoManager { int getCpuTemperature(); }
添加服務,實現aidl文件定義的介面
frameworks/base/services/core/java/com/android/server/DemoManagerService.java
package com.android.server; import android.app.IDemoManager; import android.content.Context; import android.util.Slog; public class DemoManagerService extends IDemoManager.Stub { private Context mContext; public DemoManagerService(Context context) { mContext = context; Slog.d("Demo", "Construct"); } @Override public int getCpuTemperature() { return 100; // Test code } }
添加對應的Manager
frameworks/base/core/java/android/app/DemoManager.java
package android.app; import android.content.Context; import android.os.RemoteException; import android.util.Slog; public class DemoManager { Context mContext; IDemoManager mService; public DemoManager(Context context, IDemoManager service) { mContext = context; mService = service; } public int getCpuTemperature() { if (mService != null) { try { return mService.getCpuTemperature(); } catch (RemoteException e) { Slog.e("Demo", "RemoteException " + e); } } return -1; } }
添加aidl到Makefile src
frameworks/base/Android.mk
LOCAL_SRC_FILES += \ core/java/android/app/IDemoManager.aidl \
添加DEMO_SERVICE常量
frameworks/base/core/java/android/content/Context.java
public static final String DEMO_SERVICE = "demo";
註冊系統服務
frameworks/base/core/java/android/app/SystemServiceRegistry.java
registerService(Context.ORISLINK_SERVICE, DemoManager.class, new CachedServiceFetcher<DemoManager>() { @Override public DemoManager createService(ContextImpl ctx) { IBinder b = ServiceManager.getService(Context.DEMO_SERVICE); return new DemoManager(ctx, IDemoManager.Stub.asInterface(b)); }});
開機啟動服務
frameworks/base/services/java/com/android/server/SystemServer.java
try { ServiceManager.addService(Context.DEMO_SERVICE, new DemoManagerService(context)); } catch (Throwable e) { Slog.e("Demo", "Failed to start Demo Service " + e); }
編譯源碼,因為添加了介面,所以需要
make update-api
更新介面。然後再整編刷機。
service list 查看服務,不存在,這是因為selinux許可權沒加。
添加sepolicy許可權
device/qcom/sepolicy/msm8937/service.te
type demo_service, system_api_service, system_server_service, service_manager_type;
device/qcom/sepolicy/msm8937/service_contexts
demo u:object_r:demo_service:s0
重新編譯代碼,使用下麵測試代碼驗證
import android.app.DemoManager; DemoManager om = (DemoManager) getSystemService(Context.DEMO_SERVICE); Log.d(TAG, "Current temperature is " + om.getCpuTemperature());
最終log列印出100,服務添加完成。