鸿蒙OS 连接Service

2020-09-18 10:04 更新

如果 Service 需要与 Page Ability 或其他应用的 Service Ability 进行交互,则应创建用于连接的 Connection。Service 支持其他 Ability 通过 connectAbility()方法与其进行连接。

在使用 connectAbility() 处理回调时,需要传入目标 Service 的 Intent 与 IAbilityConnection 的实例。IAbilityConnection 提供了两个方法供开发者实现: onAbilityConnectDone() 用来处理连接的回调,onAbilityDisconnectDone() 用来处理断开连接的回调。

连接 Service 的代码示例如下:

  1. // 创建连接回调实例
  2. private IAbilityConnection connection = new IAbilityConnection() {
  3. // 连接到Service的回调
  4. @Override
  5. public void onAbilityConnectDone(ElementName elementName, IRemoteObject iRemoteObject, int resultCode) {
  6. // 在这里开发者可以拿到服务端传过来IRemoteObject对象,从中解析出服务端传过来的信息
  7. }
  8. // 断开与连接的回调
  9. @Override
  10. public void onAbilityDisconnectDone(ElementName elementName, int resultCode) {
  11. }
  12. };
  13. // 连接Service
  14. connectAbility(intent, connection);

同时,Service 侧也需要在 onConnect() 时返回 IRemoteObject,从而定义与 Service 进行通信的接口。onConnect() 需要返回一个 IRemoteObject 对象,HarmonyOS 提供了 IRemoteObject 的默认实现,用户可以通过继承 RemoteObject 来创建自定义的实现类。Service 侧把自身的实例返回给调用侧的代码示例如下:

  1. // 创建自定义IRemoteObject实现类
  2. private class MyRemoteObject extends RemoteObject {
  3. public MyRemoteObject() {
  4. super("MyRemoteObject");
  5. }
  6. }
  7. // 把IRemoteObject返回给客户端
  8. @Override
  9. protected IRemoteObject onConnect(Intent intent) {
  10. return new MyRemoteObject();
  11. }
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号