• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# UIAbility与UIAbility连接开发指南
2
3
4## 简介
5
6应用跨设备连接管理可以通过分布式操作系统,将用户拥有的多个设备整合为一个整体,实现设备与设备之间的能力互助,为用户提供比单设备更加高效的沉浸式体验。<!--Del-->例如通过手表相机应用拉起手机的相机功能并实现实时画面预览和遥控拍照。<!--DelEnd-->
7
8
9### 能力范围
10
11- 跨设备拉起应用:可以通过本设备应用,拉起其他组网设备的同应用,并进行协同作业。
12- 数据交互:实现跨设备数据传输<!--Del-->,包括文本信息、字节流、图片、传输流(三方应用仅支持文本信息交互能力)<!--DelEnd-->。
13
14
15### 亮点特征
16
17通过多样化的跨设备传输流特性,实现本设备相机拉起对端设备相机功能。为用户提供<!--Del-->实时预览对端设备摄像头的画面、<!--DelEnd-->文本信息交互<!--Del-->、接受回传照片、遥控拍照等<!--DelEnd-->能力。
18
19
20### 基本概念
21
22在进行应用跨设备连接管理开发前,开发者应了解以下基本概念:
23
24- **DMS**
25
26  DMS(Distributedsched Management Service)是分布式组件管理框架,提供分布式组件的管理能力。
27
28- **UIAbility**
29
30  描述应用程序的界面交互能力,负责管理应用界面的生命周期、用户交互以及界面渲染等任务。
31
32- **Extension**
33
34  用于扩展应用的功能或实现跨设备协同。它允许应用在后台运行某些任务,或者将部分功能迁移到其他设备上执行,从而实现分布式能力。
35
36<!--Del-->
37- **字节流**
38
39  字节流是数据类型为[ArrayBuffer](../arkts-utils/arraybuffer-object.md)类型的数据。可以被用于存储二进制数据,例如图像或音频数据。
40
41- **传输流**
42
43  可进行图片、视频流传输的媒体流。
44<!--DelEnd-->
45### 实现原理
46
47应用跨设备连接管理生长在分布式组件管理框架之上,在分布式组件管理框架上进行了JS对象型的封装,能通过分布式组件管理框架服务建立协同关系并进行应用间的连接,数据的交互能力由系统支持。
48
49**图1** 应用跨设备连接运行机制
50
51![how-abilityconnectmanager-works](figures/how-abilityconnectmanager-works.png)
52
53
54### 约束与限制
55
56- 设备间需要登录相同的华为账号。
57
58- 不同设备间只有相同bundleName的UIAbility应用才能进行协同。
59<!--Del-->
60- 字节流、图片以及传输流的能力仅支持系统应用。
61<!--DelEnd-->
62- 业务协同完毕后需及时结束协同状态。未申请长时任务的应用,在锁屏或退至后台5秒以上,会被结束掉协同生命周期。
63
64- 分布式组件管理框架在协同过程中不会对传输内容进行审查。涉及隐私敏感数据时,建议业务通过数据加密、弹框提醒等方式加强信息安全。
65
66
67## 环境准备
68
69### 环境要求
70
71可登录华为账号的设备A和设备B,设备间需要组网成功(双端登录同一个华为账号,并使用蓝牙连接)。
72
73
74### 搭建环境
75
761. 在PC上安装[DevEco Studio](https://developer.huawei.com/consumer/cn/download/deveco-studio),要求版本在4.1及以上。
772. 将public-SDK更新到API 18或以上,更新SDK的具体操作可参见[更新指南]( ../tools/openharmony_sdk_upgrade_assistant.md)。
783. 用USB线缆将两台调测设备(设备A和设备B)连接到PC。
794. 打开设备A和设备B的蓝牙,互相识别,实现组网。
80
81
82### 检验环境是否搭建成功
83
84PC上执行shell命令:
85
86```shell
87hdc shell
88hidumper -s 4700 -a "buscenter -l remote_device_info"
89```
90
91组网成功时可显示组网设备数量的信息,如“remote device num = 1”。
92
93
94## 开发指导
95
96应用跨设备连接管理可以通过分布式操作系统,将用户拥有的多个设备作为一个整体,设备与设备之间取长补短、相互帮助,为用户提供比单设备更加高效、沉浸的体验。
97
98
99### 接口说明
100
101应用跨设备连接管理接口如下表所示。具体API说明详见API参考:[abilityConnectionManager](../reference/apis-distributedservice-kit/js-apis-distributed-abilityConnectionManager.md)。
102
103**表1** abilityConnectionManager接口功能介绍
104
105| 接口名 | 描述 |
106| -------- | -------- |
107| createAbilityConnectionSession(serverId:&nbsp;string,&nbsp;context:&nbsp;Context,&nbsp;peerInfo:&nbsp;peerInfo,&nbsp;connectOpt:&nbsp;ConnectOption):&nbsp;number; | 创建应用间的会话。 |
108| destroyAbilityConnectionSession(sessionId:&nbsp;number):&nbsp;void; | 销毁应用间的会话。 |
109| connect(sessionId:&nbsp;number):&nbsp;Promise&lt;ConnectResult&gt;; | source侧进行ability的连接。 |
110| acceptConnect(sessionId:&nbsp;number,&nbsp;token:&nbsp;string):&nbsp;Promise&lt;void&gt;; | sink侧进行ability的连接。 |
111| disconnect(sessionId:&nbsp;number):&nbsp;void; | 断开ability的连接。 |
112| on(type:&nbsp;'connect'&nbsp;\| &nbsp;'disconnect'&nbsp;\| &nbsp;'receiveMessage'&nbsp;\| &nbsp;'receiveData'&nbsp;\| &nbsp;'receiveImage',&nbsp;sessionId:&nbsp;number,&nbsp;callback:&nbsp;Callback&lt;EventCallbackInfo&gt;):&nbsp;void | 监听<!--Del-->connect/disconnect/receiveMessage/receiveData/receiveImage<!--DelEnd-->事件。 |
113| off(type:&nbsp;'connect'&nbsp;\| &nbsp;'disconnect'&nbsp;\| &nbsp;'receiveMessage'&nbsp;\| &nbsp;'receiveData'&nbsp;\| &nbsp;'receiveImage',&nbsp;'connect',&nbsp;sessionId:&nbsp;number,&nbsp;callback?:&nbsp;Callback&lt;EventCallbackInfo&gt;):&nbsp;void | 取消<!--Del-->connect/disconnect/receiveMessage/receiveData/receiveImage<!--DelEnd-->事件的监听。 |
114| sendMessage(sessionId:&nbsp;number,&nbsp;msg:&nbsp;string):&nbsp;Promise&lt;void&gt;; | 发送文本信息。 |
115|<!--DelRow--> sendData(sessionId:&nbsp;number,&nbsp;data:&nbsp;ArrayBuffer):&nbsp;Promise&lt;void&gt;; | 发送字节流(仅支持系统应用调用)。 |
116|<!--DelRow--> sendImage(sessionId:&nbsp;number,&nbsp;image:&nbsp;image.PixelMap):&nbsp;Promise&lt;void&gt;; | 发送图片(仅支持系统应用调用)。 |
117|<!--DelRow--> createStream(sessionId:&nbsp;number,&nbsp;param:&nbsp;StreamParam):&nbsp;Promise&lt;number&gt;; | 创建传输流(仅支持系统应用调用)。 |
118|<!--DelRow--> destroyStream(sessionId:&nbsp;number):&nbsp;void; | 关闭传输流(仅支持系统应用调用)。 |
119
120
121### 开发步骤
122
123通过应用跨设备管理模块,设备A拉起并连接设备B上的应用。连接成功后,设备A和设备B通过on接口注册相应事件的回调监听。设备A或设备B通过sendMessage<!--Del-->、sendData、sendImage、createStream等<!--DelEnd-->接口发送消息<!--Del-->、字节流、传输流<!--DelEnd-->。对端通过监听到的回调信息进行后续协同业务。
124
125#### 导入AbilityConnectionManager模块文件
126
127   ```ts
128   import { abilityConnectionManager } from '@kit.DistributedServiceKit';
129   ```
130
131
132#### 发现设备
133
134设备A上的应用,需要发现并选择设备B的netWorkId来作为协同接口的入参。可调用分布式设备管理模块接口,进行对端设备的发现和选择,详情可参考[分布式设备管理模块](devicemanager-guidelines.md)进行开发。
135
136
137#### 应用间创建会话并进行连接
138
139设备A和设备B在创建会话和连接时要执行的操作不同,接下来的开发步骤中,以设备A作为连接发起方,设备B作为连接接收端。
140
141##### 设备A
142
143应用主动调用createAbilityConnectionSession()接口创建会话,获得sessionId。之后调用connect()方法启动ability会话连接(此时设备B上应用会被拉起)。
144
145  ```ts
146  import { abilityConnectionManager, distributedDeviceManager } from '@kit.DistributedServiceKit';
147  import { common } from '@kit.AbilityKit';
148  import { hilog } from '@kit.PerformanceAnalysisKit';
149
150  let dmClass: distributedDeviceManager.DeviceManager;
151
152  function initDmClass(): void {
153    try {
154      dmClass = distributedDeviceManager.createDeviceManager('com.example.remotephotodemo');
155    } catch (err) {
156      hilog.error(0x0000, 'testTag', 'createDeviceManager err: ' + JSON.stringify(err));
157    }
158  }
159  // 获取设备B的设备ID
160  function getRemoteDeviceId(): string | undefined {
161    initDmClass();
162    if (typeof dmClass === 'object' && dmClass !== null) {
163      hilog.info(0x0000, 'testTag', 'getRemoteDeviceId begin');
164      let list = dmClass.getAvailableDeviceListSync();
165      if (typeof (list) === 'undefined' || typeof (list.length) === 'undefined') {
166        hilog.info(0x0000, 'testTag', 'getRemoteDeviceId err: list is null');
167        return;
168      }
169      if (list.length === 0) {
170        hilog.info(0x0000, 'testTag', 'getRemoteDeviceId err: list is empty');
171        return;
172      }
173      return list[0].networkId;
174    } else {
175      hilog.info(0x0000, 'testTag', 'getRemoteDeviceId err: dmClass is null');
176      return;
177    }
178  }
179  // 定义设备B的协同信息
180  const peerInfo: abilityConnectionManager.PeerInfo = {
181    deviceId: getRemoteDeviceId(),
182    bundleName: 'com.example.remotephotodemo',
183    moduleName: 'entry',
184    abilityName: 'EntryAbility',
185    serverId: 'collabTest'
186  };
187  const myRecord: Record<string, string> = {
188    "newKey1": "value1",
189  };
190
191  const options: Record<string, string> = {
192    'ohos.collabrate.key.start.option': 'ohos.collabrate.value.foreground',
193  };
194  // 定义连接选项
195  const connectOption: abilityConnectionManager.ConnectOption = {
196    needSendBigData: true,
197    needSendStream: false,
198    needReceiveStream: true,
199    options: options,
200    parameters: myRecord
201  };
202  let context = this.getUIContext().getHostContext();
203  try {
204    this.sessionId = abilityConnectionManager.createAbilityConnectionSession("collabTest", context, peerInfo, connectOption);
205    hilog.info(0x0000, 'testTag', 'createSession sessionId is', this.sessionId);
206
207    abilityConnectionManager.connect(this.sessionId).then((ConnectResult) => {
208      if (!ConnectResult.isConnected) {
209        hilog.info(0x0000, 'testTag', 'connect failed');
210        return;
211      }
212    }).catch(() => {
213      hilog.error(0x0000, 'testTag', "connect failed");
214    })
215
216  } catch (error) {
217    hilog.error(0x0000, 'testTag', error);
218  }
219  ```
220
221##### 设备B
222
223设备A的应用调用connect()后,设备B的应用会通过协同的方式被拉起,拉起时会触发协同生命周期函数onCollaborate(),可在该接口中配置createAbilityConnectionSession()接口以及acceptConnect()接口的调用。
224
225  ```ts
226  import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
227  import { abilityConnectionManager } from '@kit.DistributedServiceKit';
228  import { hilog } from '@kit.PerformanceAnalysisKit';
229
230  export default class EntryAbility extends UIAbility {
231    onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
232      hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
233    }
234
235    onCollaborate(wantParam: Record<string, Object>): AbilityConstant.OnCollaborateResult {
236      hilog.info(0x0000, 'testTag', '%{public}s', 'on collaborate');
237      let param = wantParam["ohos.extra.param.key.supportCollaborateIndex"] as Record<string, Object>
238      this.onCollab(param);
239      return 0;
240    }
241
242    onCollab(collabParam: Record<string, Object>) {
243      const sessionId = this.createSessionFromWant(collabParam);
244      if (sessionId == -1) {
245        hilog.info(0x0000, 'testTag', 'Invalid session ID.');
246        return;
247      }
248      const collabToken = collabParam["ohos.dms.collabToken"] as string;
249      abilityConnectionManager.acceptConnect(sessionId, collabToken).then(() => {
250        hilog.info(0x0000, 'testTag', 'acceptConnect success');
251      }).catch(() => {
252        hilog.error("failed");
253      })
254    }
255
256    createSessionFromWant(collabParam: Record<string, Object>): number {
257      let sessionId = -1;
258      const peerInfo = collabParam["PeerInfo"] as abilityConnectionManager.PeerInfo;
259      if (peerInfo == undefined) {
260        return sessionId;
261      }
262
263      const options = collabParam["ConnectOption"] as abilityConnectionManager.ConnectOption;
264      options.needSendBigData = true;
265      options.needSendStream = true;
266      options.needReceiveStream = false;
267      try {
268        sessionId = abilityConnectionManager.createAbilityConnectionSession("collabTest", this.context, peerInfo, options);
269        AppStorage.setOrCreate('sessionId', sessionId);
270        hilog.info(0x0000, 'testTag', 'createSession sessionId is' + sessionId);
271      } catch (error) {
272        hilog.error(0x0000, 'testTag', error);
273      }
274      return sessionId;
275    }
276  }
277  ```
278
279#### 注册事件监听
280
281在应用创建会话成功并获得sessionId后,开发者可调用on()方法进行对应事件的监听,通过触发回调函数的方式通知监听者,以便执行对应业务。
282<!--RP1-->
283  ```ts
284  import { abilityConnectionManager } from '@kit.DistributedServiceKit';
285  import { hilog } from '@kit.PerformanceAnalysisKit';
286
287  abilityConnectionManager.on("connect", this.sessionId,(callbackInfo) => {
288    hilog.info(0x0000, 'testTag', 'session connect, sessionId is', callbackInfo.sessionId);
289  });
290  abilityConnectionManager.on("disconnect", this.sessionId,(callbackInfo) => {
291    hilog.info(0x0000, 'testTag', 'session disconnect, sessionId is', callbackInfo.sessionId);
292  });
293  abilityConnectionManager.on("receiveMessage", this.sessionId,(callbackInfo) => {
294    hilog.info(0x0000, 'testTag', 'session receiveMessage, sessionId is', callbackInfo.sessionId);
295  });
296  abilityConnectionManager.on("receiveData", this.sessionId,(callbackInfo) => {
297    hilog.info(0x0000, 'testTag', 'session receiveData, sessionId is', callbackInfo.sessionId);
298  });
299  abilityConnectionManager.on("receiveImage", this.sessionId,(callbackInfo) => {
300    hilog.info(0x0000, 'testTag', 'session receiveImage, sessionId is', callbackInfo.sessionId);
301  });
302<!--RP1End-->  ```
303
304#### 发送数据
305
306##### 发送消息
307应用连接成功后,开发者可在设备A或者设备B上调用sendMessage()方法给对端应用发送文本信息。
308
309  ```ts
310  import { abilityConnectionManager } from '@kit.DistributedServiceKit';
311  import { hilog } from '@kit.PerformanceAnalysisKit';
312
313  abilityConnectionManager.sendMessage(this.sessionId, "message send success").then(() => {
314    hilog.info(0x0000, 'testTag', "sendMessage success");
315  }).catch(() => {
316    hilog.error(0x0000, 'testTag', "connect failed");
317  })
318  ```
319<!--Del-->
320##### 发送字节流数据
321
322应用连接成功后,开发者可在设备A或者设备B上调用sendData()方法给对端应用发送字节数据(仅支持系统应用调用)。
323
324  ```ts
325  import { abilityConnectionManager } from '@kit.DistributedServiceKit';
326  import { hilog } from '@kit.PerformanceAnalysisKit';
327
328  let textEncoder = util.TextEncoder.create("utf-8");
329  const arrayBuffer  = textEncoder.encodeInto("data send success");
330
331  abilityConnectionManager.sendData(this.sessionId, arrayBuffer.buffer).then(() => {
332    hilog.info(0x0000, 'testTag', "sendMessage success");
333  }).catch(() => {
334    hilog.info(0x0000, 'testTag', "sendMessage failed");
335  })
336  ```
337
338##### 发送图片
339
340应用连接成功后,开发者可在设备A或者设备B上调用sendImage()方法给对端应用发送图片(仅支持系统应用调用)。
341
342  ```ts
343  import { abilityConnectionManager } from '@kit.DistributedServiceKit';
344  import { hilog } from '@kit.PerformanceAnalysisKit';
345  import CameraService from '../model/CameraService';
346  import { photoAccessHelper } from '@kit.MediaLibraryKit';
347  import { image } from '@kit.ImageKit';
348  import { fileIo as fs } from '@kit.CoreFileKit';
349
350  try {
351    let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
352    photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
353    photoSelectOptions.maxSelectNumber = 5;
354    let photoPicker = new photoAccessHelper.PhotoViewPicker();
355    photoPicker.select(photoSelectOptions).then((photoSelectResult) => {
356      if (!photoSelectResult) {
357        hilog.error(0x0000, 'testTag', 'photoSelectResult = null');
358      return;
359      }
360
361      let file = fs.openSync(photoSelectResult.photoUris[0], fs.OpenMode.READ_ONLY);
362      hilog.info(0x0000, 'testTag', 'file.fd:' + file.fd);
363
364      let imageSourceApi: image.ImageSource = image.createImageSource(file.fd);
365      if (imageSourceApi) {
366        imageSourceApi.createPixelMap().then((pixelMap) => {
367          abilityConnectionManager.sendImage(this.sessionId, pixelMap)
368        });
369      } else {
370        hilog.info(0x0000, 'testTag', 'imageSourceApi is undefined');
371      }
372    })
373  } catch (error) {
374    hilog.error(0x0000, 'testTag', 'photoPicker failed with error: ' + JSON.stringify(error));
375  }
376  ```
377
378##### 发送传输流
379
380应用连接成功后,开发者可在设备A或者设备B上调用createStream()方法创建传输流(仅支持系统应用调用),之后调用startStream()方法传输流给对端设备。
381
382  ```ts
383  import { abilityConnectionManager } from '@kit.DistributedServiceKit';
384  import { hilog } from '@kit.PerformanceAnalysisKit';
385
386  hilog.info(0x0000, 'testTag', 'startStream');
387  abilityConnectionManager.createStream(sessionId ,{name: 'receive', role: 0}).then(async (streamId) => {
388    let surfaceParam: abilityConnectionManager.SurfaceParam = {
389      width: 640,
390      height: 480,
391      format: 1
392    }
393    let surfaceId = abilityConnectionManager.getSurfaceId(streamId, surfaceParam);
394    hilog.info(0x0000, 'testTag', 'surfaceId is'+surfaceId);
395    AppStorage.setOrCreate<string>('surfaceId', surfaceId);
396    await CameraService.initCamera(surfaceId, 0);
397    abilityConnectionManager.startStream(streamId);
398  })
399  ```
400<!--DelEnd-->
401#### 结束协同
402
403业务协同完毕后需及时结束协同状态。若是后续短期内还有协同需要,可调用disconnect()方法断开应用间的连接,保留sessionId,以便下次继续使用该sessionId进行连接。若是短期无需使用协同业务,可直接调用destroyAbilityConnectionSession()接口销毁会话,此时会自动断开连接。
404
405  ```ts
406  import { abilityConnectionManager } from '@kit.DistributedServiceKit';
407  import { hilog } from '@kit.PerformanceAnalysisKit';
408
409  hilog.info(0x0000, 'testTag', 'disconnectRemoteAbility begin');
410  if (this.sessionId == -1) {
411    hilog.info(0x0000, 'testTag', 'Invalid session ID.');
412  return;
413  }
414  abilityConnectionManager.disconnect(this.sessionId);
415
416  hilog.info(0x0000, 'testTag', 'destroyAbilityConnectionSession called');
417  abilityConnectionManager.destroyAbilityConnectionSession(this.sessionId);
418  ```
419
420
421### 调测验证
422
423应用侧开发完成后,可在设备A和设备B上安装应用,测试步骤如下:
424
4251. 点击设备A应用的“连接”按钮,此时设备B上的应用被拉起。
4262. 点击设备A应用的“sendMessage”按钮,此时设备B上的应用会触发on()方法的回调,接受该字符串。
427<!--Del-->
4283. 点击设备A应用的“sendData”按钮,此时设备B上的应用会触发on()方法的回调,接受该字节流。
4294. 点击设备A应用的“sendImage”按钮,此时设备B上的应用会触发on()方法的回调,接受该图片。
4305. 点击设备A应用的“启动传输流”按钮,此时设备B上的应用会触发on()方法的回调,接受传输流内容。
431<!--DelEnd-->
4326. 点击设备A或设备B应用的“disconnect”按钮,此时双端会断开连接,触发connect()接口的回调,将断连信息上报给双端应用。
433
434## 常见问题
435
436### 设备A应用无法拉起设备B应用
437
438**可能原因**
439
440- 【原因1】:设备间没有相互组网,导致设备A发起连接时,createAbilityConnectionSession()接口中的peerInfo.deviceId属性未设置正确。
441
442- 【原因2】:有多台设备相互组网,设备A发起连接时,createAbilityConnectionSession()接口中的peerInfo.deviceId属性设置为其他设备的deviceId,未正确指定到B设备上。
443
444**解决措施**
445
446- 针对原因1,设备A和设备B开启USB调试功能,用USB线连接设备和PC。执行shell命令:
447
448  ```shell
449  hdc shell
450  hidumper -s 4700 -a "buscenter -l remote_device_info"
451  ```
452  回显信息为“remote device num = 0”即为组网失败,请确保登录同一华为账号并使用蓝牙连接。组网成功时可显示组网设备数量的信息,如“remote device num = 1”。
453
454- 针对原因2,查询并选择指定设备时,添加设备选择列表,确保指定到期望的设备。
455
456### 应用锁屏或者退后台一段时间后,正在执行的协同业务被断开
457
458**可能原因**
459
460应用在协同过程中,DMS会对应用的生命周期进行监听。发生锁屏、退后台操作持续五秒后,未申请长时任务的应用会被结束协同状态。
461
462**解决措施**
463
464应用[申请长时任务](../task-management/continuous-task.md),消除此限制。