文档管理中心
开发与测试开放能力API系统硬件Wear Engine Kit(穿戴服务)穿戴侧应用开发应用间消息通信

应用间消息通信

约束与限制

  • 使用该功能前,请确保对端设备侧已有对应的应用。
  • 对端设备侧应用和穿戴设备应用必须同时处于已启动状态。

穿戴侧应用检测对端设备侧应用是否安装

  1. 参见已连接对端设备查询章节,从已连接设备列表中选定需要通信的对端设备。

  2. 调用getP2pClient方法,获取P2pClient对象。

  3. 调用isRemoteAppInstalled方法,查看对端设备是否安装指定应用。

    收起
    自动换行
    深色代码主题
    复制
    1. // 将对端应用包名定义为remoteBundleName
    2. let remoteBundleName: string = '';
    3. // 步骤2 获取P2pClient对象
    4. let p2pClient: wearEngine.P2pClient = wearEngine.getP2pClient(this.getUIContext().getHostContext());
    5. // 步骤3 查看是否安装指定的对端应用
    6. p2pClient.isRemoteAppInstalled(targetDevice.randomId, remoteBundleName).then((isInstall) => {
    7. console.info(`Succeeded in checking remote app install, result is ${isInstall}.`);
    8. }).catch((error: BusinessError) => {
    9. console.error(`Failed to check remote app install. Code is ${error.code}, message is ${error.message}.`);
    10. })

穿戴侧应用发送点对点消息或文件到对端应用

消息长度大小的限制为4096字节。针对消息长度超过限制的情况可以采用发送文件(文件大小不超过100MB)的方式或进行消息分包控制。

穿戴侧实现发送消息和文件功能后,对端应用需要实现接收消息和文件的功能。

发送点对点消息

  1. 为了使用工具类构造消息体,请先导入所需模块。

    收起
    自动换行
    深色代码主题
    复制
    1. import { util } from '@kit.ArkTS';
  2. 参见已连接对端设备查询章节,从已连接设备列表中选定需要通信的对端设备。

  3. 构造对端应用参数P2pAppParam

  4. 构造需要发送的消息P2pMessage

  5. 调用getP2pClient方法,获取P2pClient对象。

  6. 调用sendMessage方法,从穿戴侧应用发送简短消息到对端应用。对端应用已注册监听消息接收后,即可收到穿戴侧应用发送的消息。

    说明

    步骤2中fingerprint表示应用指纹,具体请参考如何获取应用指纹

    收起
    自动换行
    深色代码主题
    复制
    1. // 步骤2 构造对端应用参数
    2. let appInfo: wearEngine.AppInfo = {
    3. // 设置对端应用的应用信息:包名与指纹
    4. bundleName: '',
    5. fingerprint: ''
    6. };
    7. let appParam: wearEngine.P2pAppParam = {
    8. remoteApp: appInfo
    9. };
    10. // 设置需要发送的消息内容,长度限制为4096字节
    11. let messageContent: string = 'this is message';
    12. // 步骤3 构造消息结构体
    13. let textEncoder: util.TextEncoder = new util.TextEncoder;
    14. let message: wearEngine.P2pMessage = {
    15. content: textEncoder.encodeInto(messageContent)
    16. };
    17. // 步骤4 获取P2pClient对象
    18. let p2pClient: wearEngine.P2pClient = wearEngine.getP2pClient(this.getUIContext().getHostContext());
    19. // 步骤5 发送消息
    20. p2pClient.sendMessage(targetDevice.randomId, appParam, message).then((p2pResult) => {
    21. console.info(`Succeeded in sending message, result is ${p2pResult.code}.`);
    22. }).catch((error: BusinessError) => {
    23. console.error(`Failed to send message. Code is ${error.code}, message is ${error.message}.`);
    24. });

发送文件

  1. 发送文件前需要打开文件描述符,请先导入模块。

    收起
    自动换行
    深色代码主题
    复制
    1. import { fileIo } from '@kit.CoreFileKit';
  2. 参见已连接对端设备查询章节,从已连接设备列表中选定需要通信的对端设备。

  3. 构造对端应用参数P2pAppParam

  4. 根据文件路径filePath,构造需要发送的文件P2pFile

  5. 调用getP2pClient方法,获取P2pClient对象。

  6. 调用transferFile方法,从穿戴侧应用发送文件到对端应用。

    说明

    步骤2中fingerprint表示应用指纹,具体请参考如何获取应用指纹

    收起
    自动换行
    深色代码主题
    复制
    1. // 步骤2 构造对端应用参数
    2. let appInfo: wearEngine.AppInfo = {
    3. // 设置对端应用的应用信息:包名与指纹
    4. bundleName: '',
    5. fingerprint: ''
    6. };
    7. let appParam: wearEngine.P2pAppParam = {
    8. remoteApp: appInfo
    9. };
    10. let p2pfile: wearEngine.P2pFile | undefined;
    11. try {
    12. // 步骤3 构造需要发送的文件
    13. p2pfile = {
    14. // 设置需要发送的文件路径,其中不能包含'..'
    15. file: fileIo.openSync('')
    16. };
    17. // 步骤4 获取P2pClient对象
    18. let p2pClient: wearEngine.P2pClient = wearEngine.getP2pClient(this.getUIContext().getHostContext());
    19. // 步骤5 发送指定文件至对端
    20. p2pClient.transferFile(targetDevice.randomId, appParam, p2pfile, (error: BusinessError,
    21. p2pResult: wearEngine.P2pResult) => {
    22. // callback处理逻辑
    23. if (error) {
    24. console.error(`Failed to transfer file. Code is ${error.code}, message is ${error.message}.`);
    25. return;
    26. }
    27. if (p2pResult.code) {
    28. if (p2pResult.code === wearEngine.P2pResultCode.COMMUNICATION_SUCCESS) {
    29. console.info(`Succeeded in transferring file, the result is ${p2pResult.code}.`);
    30. } else {
    31. console.error(`Failed to transfer file, the error code is ${p2pResult.code}.`);
    32. return;
    33. }
    34. }
    35. if (p2pResult.progress) {
    36. console.info(`Succeeded in transfering file, the progress is ${p2pResult.progress}.`);
    37. }
    38. });
    39. } catch(error) {
    40. console.error(`Failed to transferFile. Code is ${error.code}, message is ${error.message}.`);
    41. } finally {
    42. // 确保文件被关闭
    43. if (p2pfile && p2pfile.file) {
    44. fileIo.close(p2pfile.file)
    45. .then(() => {
    46. console.info('File closed successfully.');
    47. })
    48. .catch((closeError: BusinessError) => {
    49. console.error(`Failed to close file. Code is ${closeError.code}, message is${closeError.message}.`);
    50. });
    51. }
    52. };

订阅接收对端应用发来的消息

  1. 参见已连接对端设备查询章节,从已连接设备列表中选定需要通信的对端设备。

  2. 调用getP2pClient方法,获取P2pClient对象。

  3. 构造对端应用参数P2pAppParam

  4. 构造接收到对端传来消息后的回调函数Callback

  5. 调用registerMessageReceiver方法,订阅监听消息接收事件。

    说明

    步骤3中fingerprint表示应用指纹,具体请参考如何获取应用指纹

    收起
    自动换行
    深色代码主题
    复制
    1. // 步骤2 获取P2pClient对象
    2. let p2pClient: wearEngine.P2pClient = wearEngine.getP2pClient(this.getUIContext().getHostContext());
    3. // 步骤3 构造对端应用参数
    4. let appInfo: wearEngine.AppInfo = {
    5. bundleName: '',
    6. fingerprint: ''
    7. };
    8. // 将对端应用参数类定义为appParam
    9. let appParam: wearEngine.P2pAppParam = {
    10. remoteApp: appInfo
    11. };
    12. // 步骤4 构造回调函数
    13. let callback = (p2pMessage: wearEngine.P2pMessage) => {
    14. console.info(`Succeeded in receiving message, the message is ${p2pMessage.content}.`);
    15. };
    16. // 步骤5 订阅监听消息接收事件
    17. p2pClient.registerMessageReceiver(targetDevice.randomId, appParam, callback).then(() => {
    18. console.info(`Succeeded in registering message receiver.`);
    19. }).catch((error: BusinessError) => {
    20. console.error(`Failed to register message receiver. Code is ${error.code}, message is ${error.message}.`);
    21. });
  6. 调用unregisterMessageReceiver方法,穿戴侧应用取消接收对端应用发过来的消息,需要传入订阅监听时的同一个回调函数对象。

    收起
    自动换行
    深色代码主题
    复制
    1. p2pClient.unregisterMessageReceiver(targetDevice.randomId, appParam, callback).then(() => {
    2. console.info(`Succeeded in unregistering message receiver.`);
    3. }).catch((error: BusinessError) => {
    4. console.error(`Failed to unregister message receiver. Code is ${error.code}, message is ${error.message}.`);
    5. });

订阅接收对端应用发送来的文件

  1. 参见已连接对端设备查询章节,从已连接设备列表中选定需要通信的对端设备。

  2. 调用getP2pClient方法,获取P2pClient对象。

  3. 构造设备侧应用参数P2pAppParam

  4. 构造接收到设备侧传来文件后的回调函数Callback

  5. 调用registerFileReceiver方法,订阅监听文件接收事件。

    说明

    步骤3中fingerprint表示应用指纹,具体请参考如何获取应用指纹

    收起
    自动换行
    深色代码主题
    复制
    1. // 步骤2 获取P2pClient对象
    2. let p2pClient: wearEngine.P2pClient = wearEngine.getP2pClient(this.getUIContext().getHostContext());
    3. // 步骤3 构造对端应用参数
    4. let appInfo: wearEngine.AppInfo = {
    5. bundleName: '',
    6. fingerprint: ''
    7. };
    8. // 将对端应用参数类定义为appParam
    9. let appParam: wearEngine.P2pAppParam = {
    10. remoteApp: appInfo
    11. };
    12. // 步骤4 构造回调函数
    13. let callback = (p2pMessage: wearEngine.P2pFile) => {
    14. console.info(`Succeeded in receiving file.`);
    15. };
    16. // 步骤5 订阅监听文件接收事件
    17. p2pClient.registerFileReceiver(targetDevice.randomId, appParam, callback).then(() => {
    18. console.info(`Succeeded in registering file receiver.`);
    19. }).catch((error: BusinessError) => {
    20. console.error(`Failed to register file receiver. Code is ${error.code}, message is ${error.message}.`);
    21. });
  6. 调用unregisterFileReceiver方法,穿戴侧应用取消接收对端应用发过来的文件,需要传入订阅监听时的同一个回调函数对象。

    收起
    自动换行
    深色代码主题
    复制
    1. p2pClient.unregisterFileReceiver(targetDevice.randomId, appParam, callback).then(() => {
    2. console.info(`Succeeded in unregistering file receiver.`);
    3. }).catch((error: BusinessError) => {
    4. console.error(`Failed to unregister file receiver. Code is ${error.code}, message is ${error.message}.`);
    5. });

对端应用通过startRemoteApp拉起穿戴侧应用

如果对端应用通过调用startRemoteApp方法拉起穿戴侧应用时,需要在穿戴侧配置需要拉起的页面。

  1. 创建名为HiWearMainAbility.ets的文件,需继承UIAbility,重写onWindowStageCreate函数,配置要跳转的界面。

    收起
    自动换行
    深色代码主题
    复制
    1. // 必须继承UIAbility
    2. import { hilog } from '@kit.PerformanceAnalysisKit';
    3. import { UIAbility } from '@kit.AbilityKit';
    4. import { window } from '@kit.ArkUI';
    5. /**
    6. * 对端应用通过startRemoteApp方法拉起穿戴侧应用的HiWearMainAbility
    7. */
    8. export default class HiWearMainAbility extends UIAbility {
    9. onWindowStageCreate(windowStage: window.WindowStage): void {
    10. hilog.info(0x0000, 'HiWearMainAbility', '%{public}s', 'Ability onWindowStageCreate');
    11. // 配置要跳转的界面为”XXXPage”
    12. windowStage.loadContent('pages/XXXPage', (err, data) => {
    13. if (err.code) {
    14. hilog.error(0x0000, 'HiWearMainAbility', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
    15. return;
    16. }
    17. hilog.info(0x0000, 'HiWearMainAbility', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
    18. });
    19. }
    20. }
  2. 在module.json5中的abilities中配置HiWearMainAbility。更多配置详情参考abilities标签

    • 配置name为HiWearMainAbility。
    • 配置srcEntry为HiWearMainAbility.ets文件的路径。
    • 配置startWindowIcon为标识当前UIAbility组件启动页面图标资源文件的索引。
    • 配置startWindowBackground为标识当前UIAbility组件启动页面背景颜色资源文件的索引。
      收起
      自动换行
      深色代码主题
      复制
      1. "module": {
      2. "name": "xxxx",
      3. "type": "entry",
      4. "description": "xxxx",
      5. "mainElement": "xxxx",
      6. "deviceTypes": [],
      7. "pages": "xxxx",
      8. "abilities": [
      9. {
      10. "name": "HiWearMainAbility",
      11. "srcEntry": "xxxx",
      12. "startWindowIcon": "xxxx", // 标识当前UIAbility组件启动页面图标资源文件的索引
      13. "startWindowBackground": "xxxx" // 标识当前UIAbility组件启动页面背景颜色资源文件的索引
      14. }],
      15. "metadata": []
      16. }
  3. 在module.json5中的metadata中配置对端应用包名、待拉起的Ability名称,以及是否要等待穿戴侧完成订阅消息接收或者文件接收。

    • 对端应用包名配置时,name为wearEngineRemoteAppNameList,value为具体的对端应用包名,如果存在多个应用包名,使用英文逗号隔开,value值最长不超过4KB;
    • Ability名称配置时,name为wearEngineUIAbilityName,value为指定要拉起的UIAbility名称,不配置默认拉起HiWearMainAbility;
    • AwaitRegisterReceiver配置时,name为wearEngineAwaitRegisterReceiver,value取值为true、false。true表示要等待穿戴侧完成订阅消息接收或者文件接收,false则反之。
      收起
      自动换行
      深色代码主题
      复制
      1. "module": {
      2. "name": "xxxx",
      3. "type": "entry",
      4. "description": "xxxx",
      5. "mainElement": "xxxx",
      6. "deviceTypes": [],
      7. "pages": "xxxx",
      8. "abilities": [],
      9. "metadata": [ // 配置如下信息
      10. {
      11. "name": "wearEngineRemoteAppNameList",
      12. "value": "xxxx1,xxxx2,xxxx3"
      13. },
      14. {
      15. "name": "wearEngineUIAbilityName",
      16. "value": "xxxx"
      17. },
      18. {
      19. "name": "wearEngineAwaitRegisterReceiver",
      20. "value": "true"
      21. }
      22. ]}

穿戴侧应用拉起对端设备侧应用

  1. 参见已连接对端设备查询章节,从已连接设备列表中选定需要通信的对端设备。

  2. 构造对端应用参数remoteAppInfo

  3. 构造需要拉起对端应用的参数startConfig

  4. 调用getP2pClient方法,获取P2pClient对象。

  5. 调用startRemoteApp方法,指定需要拉起对端侧应用包名和对端侧应用的服务类型与名称。

    说明

    该接口的调用需要在开发者联盟申请拉起已配对设备的指定应用权限(请参考申请接入Wear Engine服务)。

    步骤2中fingerprint表示应用指纹,具体请参考如何获取应用指纹

    收起
    自动换行
    深色代码主题
    复制
    1. // 步骤2 构造对端应用参数
    2. let remoteAppInfo: wearEngine.AppInfo = {
    3. // 设置对端应用的应用信息:包名与指纹
    4. bundleName: 'xxx',
    5. fingerprint: 'xxx'
    6. }
    7. // 步骤3 构造需要拉起对端应用的组件类型
    8. let startConfig: wearEngine.StartConfig = {
    9. entryType: wearEngine.EntryType.DISTRIBUTED_SERVICE,
    10. entryName: 'xxx'
    11. };
    12. // 步骤4 获取P2pClient对象
    13. let p2pClient: wearEngine.P2pClient = wearEngine.getP2pClient(this.getUIContext().getHostContext());
    14. // 步骤5 拉起对端指定应用
    15. p2pClient.startRemoteApp(targetDevice.randomId, remoteAppInfo, startConfig).then((p2pResult) => {
    16. console.info(`Succeeded in starting remote app, result is ${p2pResult.code}.`);
    17. }).catch((error: BusinessError) => {
    18. console.error(`Failed to start remote app. Code is ${error.code}, message is ${error.message}.`);
    19. })

穿戴设备侧应用获取对端设备侧应用的版本号

  1. 参见已连接穿戴设备查询章节,获取已连接设备列表。

  2. 调用wearEngine中的getP2pClient方法,获取P2pClient对象。

  3. 调用getRemoteAppVersion方法,获取指定设备对应的应用版本号。

    收起
    自动换行
    深色代码主题
    复制
    1. // 构造对端应用参数
    2. let remoteBundleName: string = 'xxx';
    3. // 步骤2 获取P2pClient对象
    4. let p2pClient: wearEngine.P2pClient = wearEngine.getP2pClient(this.getUIContext().getHostContext());
    5. // 步骤3 获取指定设备应用对应的版本号
    6. p2pClient.getRemoteAppVersion(targetDevice.randomId, remoteBundleName).then((version) => {
    7. console.info(`Succeeded in getting remote app version, version is ${version}.`);
    8. }).catch((error: BusinessError) => {
    9. console.error(`Failed to check get remote app version. Code is ${error.code}, message is ${error.message}.`);
    10. })
在 开发与测试 开放能力API 中进行搜索
请输入您想要搜索的关键词