实现目标: 客户端调用服务端的add
接口计算两数之和并返回.
服务端实现
创建IDL文件
在main
文件夹上右键点击创建.idl
文件, 输入文件名如IMyIdlInterface
目录结构如下:
在IMyIdlInterface.idl中定义方法如下:
// IMyIdlInterface.idl
// Declare any non-default types here with sequenceable or interface statements
interface work.wxmx.aidlstudyserver.IMyIdlInterface {
/*
* Example of a service method that uses some parameters
*/
void serviceMethod1([in] int anInt);
int add([in] int a, [in] int b);
}
build一下
build之后会生成对应的接口和类, 如下图所示.
创建ServiceAbility
实现内容如下:
public class ServiceAbility extends Ability {
private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "Demo");
private MyIdl mMyIdl = new MyIdl("MyIDL");
class MyIdl extends MyIdlInterfaceStub {
public MyIdl(String descriptor) {
super(descriptor);
}
@Override
public void serviceMethod1(int anInt) throws RemoteException {
}
@Override
public int add(int a, int b) throws RemoteException {
HiLog.info(LABEL_LOG, "add " + a + "");
return a + b;
}
}
@Override
public IRemoteObject onConnect(Intent intent) {
return mMyIdl;
}
}
要修改config.json, 暴露出此Service
{
"module": {
"abilities": [
//...
{
"name": "work.wxmx.aidlstudyserver.ServiceAbility",
"icon": "$media:icon",
"description": "$string:serviceability_description",
"type": "service",
"visible": true // 新增此行
}
]
}
}
客户端实现
再创建一个工程, 将服务端的.idl
文件和包一块儿复制到client
端. 项目结构如下:
在MainAbilitySlice
中去绑定服务端的Service, 并在绑定成功之后的回调中调用idl
中定义的add
方法.
public class MainAbilitySlice extends AbilitySlice {
private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0x002, "TAG");
IMyIdlInterface proxy;
private IAbilityConnection connection = new IAbilityConnection() {
@Override
public void onAbilityConnectDone(ElementName element, IRemoteObject remote, int resultCode) {
HiLog.error(LABEL_LOG, "AAA", "");
proxy = MyIdlInterfaceStub.asInterface(remote);
//MainAbilitySlice.this.proxy = new MyIdlInterfaceProxy(remote);
int add = 0;
try {
add = MainAbilitySlice.this.proxy.add(1, 1);
} catch (RemoteException e) {
e.printStackTrace();
}
HiLog.error(LABEL_LOG, " " + add);
}
@Override
public void onAbilityDisconnectDone(ElementName element, int resultCode) {
proxy = null;
}
};
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
}
@Override
public void onActive() {
super.onActive();
Intent intent = new Intent();
ElementName elementName = new ElementName("", "work.wxmx.aidlstudyserver",
"work.wxmx.aidlstudyserver.ServiceAbility");
intent.setElement(elementName);
connectAbility(intent, connection);
}
@Override
public void onForeground(Intent intent) {
super.onForeground(intent);
}
}