[Android][Framework] 添加系统服务
新博客地址
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,服务添加完成。
上一篇: Vue脚手架的简单使用实例
下一篇: 理解Python中的类与实例