1、首先新建一个aidl
路径为:framwork/base/core/java/android/app
package android.app;
/**
* {@hide}
**/
interface IFirstService{
String sendMessage(String str);
}
上面的@hide重点 必须得加 不然update会报错
2、建个自定义serviceManager继承IFirstService.Stub类并实现接口
package android.app;
import android.annotation.SystemService;
import android.content.Context;
import android.os.RemoteException;
public class FirstManagerService extends IFirstService.Stub{
@Override
public String sendMessage(String str) throws RemoteException {
return "I am From Service " + str;
}
}
3、
在Context类中添加常量:
路径:framework/base/core/java/android/content/Context.java
public static final String PHQ_SERVICE = "phq";
4、创建对外暴露的manager类
package android.app;
import android.annotation.Nullable;
import android.annotation.SystemService;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.util.Singleton;
@SystemService(Context.PHQ_SERVICE)
public class PhqManager {
private Context mContext;
/**
* @hide
*/
public PhqManager(){
}
/**
* @hide
* @return
*/
public static IFirstService getService(){
return IFirstServiceSingleton.get();
}
@UnsupportedAppUsage
private static final Singleton<IFirstService> IFirstServiceSingleton =
new Singleton<IFirstService>() {
@Override
protected IFirstService create() {
final IBinder b = ServiceManager.getService(Context.PHQ_SERVICE);
final IFirstService im = IFirstService.Stub.asInterface(b);
return im;
}
};
@Nullable
public String sendMessage( @Nullable String msg){
try{
return getService().sendMessage(msg);
}catch (RemoteException e){
e.rethrowFromSystemServer();
}
return null;
}
}
5、在ServiceManager中注册
在framework/base/services/java/com/android/server/SystemServer.java中
ServiceManager.addService(Context.PHQ_SERVICE,new FirstManagerService());
6、SystemServiceRegistry注册
在静态代码块中注册
static {
registerService(Context.PHQ_SERVICE, PhqManager.class,
new CachedServiceFetcher<PhqManager>() {
@Override
public PhqManager createService(ContextImpl ctx) {
return new PhqManager();
}});
}
7、配置SELinux权限
在system/sepolicy/prebuilts/api/31.0/private/和system/sepolicy/private/目录下
service_contexts
#配置自定义服务selinux角色
phq u:object_r:phq_service:s0
service.te
#配置自定义服务类型
type phq_service, app_api_service, ephemeral_app_api_service, system_server_service, service_manager_type;
两个目录下面的文件内容必须一致
untrusted_app_all.te
#允许app使用自定义服务
allow untrusted_app_all phq_service:service_manager find;
8、更新并编译
#更新api
make update-api
#编译
m
#运行模拟器
emulator
以上的注解 必须得加不能有错、以上的注解 必须得加不能有错、以上的注解 必须得加不能有错