系统服务
系统服务都是继承Binder类或者根据aidl文件生成的stub类,如IFpService.stub,但由于stub也是继承Binder,因此可以说
系统服务都是继承Binder类(Binder可以进行跨进程通信)。
apk服务
apk服务是继承Service类
添加自定义服务到ServiceManager中
可在自定义Application的onCreate()
方法中添加
try {
servicemanager = Class.forName("android.os.ServiceManager");
final Method addservice = servicemanager.getMethod("addService", String.class, IBinder.class);
mService = new FpService(context);
addservice.invoke(null, SERVICE_NAME, mService.onBind(null));
} catch (final ClassNotFoundException ex) {
throw new RuntimeException(ex);
}
-
通过反射获取ServiceManager的addService方法
-
初始化服务对象,并调用
onBind()
方法获取IBinder对象
FpService为继承Service类的服务public class FpService extends Service
并会重写方法onBind()
@Override
public IBinder onBind(final Intent intent) {
return mStub;
} -
mStub
为IBinder
对象,并实现了aidl中的方法,客户端apk可以跨进程调用aidl中定义的方法。private IFPService.Stub mStub = new IFPService.Stub() {
@Override
public int getInt() throws RemoteException {
return 0;
}
} -
addservice.invoke(null, SERVICE_NAME, mService.onBind(null));
第一个参数为调用addservice方法的对象,由于此方法为静态方法,可以直接通过类名调用,因此没有对象调用,可以填null。
第二个参数为添加进ServiceManager的服务的key值,通过此key值可以从ServiceManager获取对应的服务对象,在这里我设置SERVICE_NAME = “fpservice”
第三个参数为要添加进ServiceManager的服务,必须是继承了Binder类的对象,由于mService
的onBind
方法返回的mStub
是IBinder
对象,因此可以添加入ServiceManager中。
从ServiceManager中获取自定义服务
可通过
getService = Class.forName("android.os.ServiceManager").getMethod("getService", new Class[]{String.class});
this.mService = Stub.asInterface((IBinder)getService.invoke(new Object(), new Object[]{"fpservice"}));
- 通过反射获取ServiceManager的getService方法
getService.invoke(new Object(), new Object[]{"fpservice"})
第一个参数为调用getService方法的对象,这里没有,可以传new Object()
。
第二个参数为获取服务的key,由于在addservice
时设置key为"fpservice",因此在这里填"fpservice"- 调用
getService
返回的是mStub
,强转成IBinder
类型,再通过Stub.asInterface
方法生成aidl代理对象mService(IFPService类型)
,因此mService
可直接调用getInt()
方法。