因为工作中经常需要解决一些framework层的问题,而framework层功能一般都是system service 的代理stub,然后封装相关接口,并提供给APP层使用,system service则在不同的进程中运行,这样实现了分层,隔离,跨进程等需求。
下面以Vibrator为例,总结一下实现流程
public class VibratorService extends IVibratorService.Stub
5.将VibratorServicey添加到系统服务
frameworks/base/services/java/com/android/server/SystemServer.java
VibratorService vibrator = null;
...
//实例化VibratorService并添加到ServiceManager
Slog.i(TAG, "Vibrator Service");
vibrator = new VibratorService(context);
ServiceManager.addService("vibrator", vibrator);
...
//通知服务系统启动完成
try {
vibrator.systemReady();
} catch (Throwable e) {
reportWtf("making Vibrator Service ready", e);
}
6.在SystemVibrator中通过IVibratorService的代理连接到VibratorService,这样SystemVibrator的接口实现里就可以调用IVibratorService的接口:
frameworks/base/core/java/android/os/SystemVibrator.java
private final IVibratorService mService;
...
public SystemVibrator() {
...
mService = IVibratorService.Stub.asInterface( ServiceManager.getService("vibrator"));
...
public boolean hasVibrator() {
...
try {
return mService.hasVibrator();
} catch (RemoteException e) { }
...
}
}
7.在Context里定义一个代表Vibrator服务的字符串
frameworks/base/core/java/android/content/Context.java
public static final String VIBRATOR_SERVICE = "vibrator";
8.注册SystemVibrator,在ContextImpl里添加SystemVibrator的实例化过程,static方法中注册 registerService
frameworks/base/core/java/android/app/ContextImpl.java
registerService(VIBRATOR_SERVICE, new ServiceFetcher() {
public Object createService(ContextImpl ctx) {
return new SystemVibrator(ctx);
}});
9.在应用中使用Vibrator的接口
Vibrator mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); mVibrator.vibrate(500);
10.为保证编译正常,还需要将AIDL文件添加到编译配置里
frameworks/base/Android.mk
LOCAL_SRC_FILES += \
...
core/java/android/os/IVibratorService.aidl \
上面的流程在location service和Bluetooth service等流程基本一致,也可以参照上面流程,实现自定义的系统服务,比如车机开发中经常面临这样的需求。