安卓原生框架层代码位于frameworks目录下,在这里基于vendor目录下的ctyun-framework添加一个自定义的系统服务,并在system server中进行启动。以ApplicationAccessManagerService为例。
1.添加自定义服务。
一个系统服务需要包含manager类和service实现,通过aidl进行通信。首先新建以下三个文件定义接口功能。
1.1 IApplicationAccessManager.aidl
在/vendor/ctyun/source/frameworks/core/java/android/app/下添加aidl文件,定义API。
interface IApplicationAccessManager {
// add your method here
}
1.2 ApplicationAccessManager.java
在/vendor/ctyun/source/frameworks/core/java/android/app/下添加manager文件,实现第三方调用接口。
public class ApplicationAccessManager {
Context mContext;
IApplicationAccessManager mApplicationAccessManagerService;
public ApplicationAccessManager(Context context, IApplicationAccessManager aam) {
mContext = context;
mApplicationAccessManagerService = aam;
}
//......
}
1.3 ApplicationAccessManagerService.java
在/vendor/ctyun/source/frameworks/services/core/java/com/android/server/下添加service文件,实现服务端逻辑。
public class ApplicationAccessManagerService extends IApplicationAccessManager.Stub {
private static final String TAG = "ApplicationAccessManagerService";
public ApplicationAccessManagerService(Context context){
//.....
}
//@Override
//......
}
2. 修改Android.bp,声明新增的aidl
在/vendor/ctyun/source/frameworks/Android.bp中声明新增aidl编译,这样编译时才会生成IApplicationAccessManager类。
java_library {
name: "ctyun-framework",
srcs: [
......
"core/java/android/app/IApplicationAccessManager.aidl",
......
],
......
}
3. 声明service name
在/vendor/ctyun/source/frameworks/core/java/android/content/ContextExternal.java中声明系统服务的service name。
public static final String APP_ACCESS_SERVICE = "app_access";
4. 注册service
在/vendor/ctyun/source/frameworks/services/core/java/com/android/server/SystemServerExternal的startExternalServices()方法中注册服务,开机自启动。
private void startApplicationAccessManagerService() {
try {
ServiceManager.addService(ContextExternal.APP_ACCESS_SERVICE, new ApplicationAccessManagerService(mSystemContext));
} catch (Exception e) {
e.printStackTrace();
}
}
5. 注册manager
在/vendor/ctyun/source/frameworks/core/java/android/app/ExternalSystemServiceManager中注册自定义的manager,绑定service name和manager实例。
registerExternalService(ContextExternal.APP_ACCESS_SERVICE, ApplicationAccessManager.class,
new ExternalCachedServiceFetcher<ApplicationAccessManager>() {
@Override
public ApplicationAccessManager createService(Context ctx) throws ServiceManager.ServiceNotFoundException {
IBinder b = ServiceManager.getServiceOrThrow(ContextExternal.APP_ACCESS_SERVICE);
IApplicationAccessManager service = IApplicationAccessManager.Stub.asInterface(b);
return new ApplicationAccessManager(ctx, service);
}});