hop-multi-device-collaboration.md 23.3 KB
Newer Older
G
Gloria 已提交
1
# Multi-device Collaboration (for System Applications Only)
G
Gloria 已提交
2 3 4 5


## When to Use

6
Multi-device coordination involves the following scenarios:
G
Gloria 已提交
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95

- [Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-and-serviceextensionability-across-devices-no-data-returned)

- [Starting UIAbility Across Devices (Data Returned)](#starting-uiability-across-devices-data-returned)

- [Connecting to ServiceExtensionAbility Across Devices](#connecting-to-serviceextensionability-across-devices)

- [Using Cross-Device Ability Call](#using-cross-device-ability-call)


## Multi-Device Collaboration Process

The figure below shows the multi-device collaboration process.

**Figure 1** Multi-device collaboration process 
![hop-multi-device-collaboration](figures/hop-multi-device-collaboration.png)


## Constraints

- Since multi-device collaboration task management is not available, you can obtain the device list by developing system applications. Access to third-party applications is not supported.

- Multi-device collaboration must comply with [Inter-Device Component Startup Rules](component-startup-rules.md#inter-device-component-startup-rules).

- For better user experience, you are advised to use the **want** parameter to transmit data smaller than 100 KB.


## Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)

On device A, touch the **Start** button provided by the initiator application to start a specified UIAbility on device B.


### Available APIs

**Table 1** Cross-device startup APIs

| **API**| **Description**|
| -------- | -------- |
| startAbility(want: Want, callback: AsyncCallback<void>): void; | Starts UIAbility and ServiceExtensionAbility. This API uses an asynchronous callback to return the result.|


### How to Develop

1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).

2. Request the data synchronization permission. The sample code for displaying a dialog box to request the permission is as follows:
   
   ```ts
   requestPermission() {   
       let context = this.context;
       let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC'];
       context.requestPermissionsFromUser(permissions).then((data) => {
           console.info("Succeed to request permission from user with data: "+ JSON.stringify(data));
       }).catch((error) => {
           console.info("Failed to request permission from user with error: "+ JSON.stringify(error));
       })
   }
   ```

3. Obtain the device ID of the target device.
   
   ```ts
   import deviceManager from '@ohos.distributedHardware.deviceManager';
   
   let dmClass;
   function initDmClass() {
       // createDeviceManager is a system API.
       deviceManager.createDeviceManager('ohos.samples.demo', (err, dm) => {
           if (err) {
               // ...
               return
           }
           dmClass = dm
       })
   }
   function getRemoteDeviceId() {
       if (typeof dmClass === 'object' && dmClass !== null) {
           let list = dmClass.getTrustedDeviceListSync()
           if (typeof (list) === 'undefined' || typeof (list.length) === 'undefined') {
               console.info('EntryAbility onButtonClick getRemoteDeviceId err: list is null')
               return;
           }
           return list[0].deviceId
       } else {
           console.info('EntryAbility onButtonClick getRemoteDeviceId err: dmClass is null')
       }
   }
   ```

G
Gloria 已提交
96
4. Set the target component parameters, and call [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to start UIAbility or ServiceExtensionAbility.
G
Gloria 已提交
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
   
   ```ts
   let want = {
       deviceId: getRemoteDeviceId(), 
       bundleName: 'com.example.myapplication',
       abilityName: 'FuncAbility',
       moduleName: 'module1', // moduleName is optional.
   }
   // context is the ability-level context of the initiator UIAbility.
   this.context.startAbility(want).then(() => {
       // ...
   }).catch((err) => {
       // ...
   })
   ```


## Starting UIAbility Across Devices (Data Returned)

On device A, touch the **Start** button provided by the initiator application to start a specified UIAbility on device B. When the UIAbility on device B exits, a value is sent back to the initiator application.


### Available APIs

**Table 2** APIs for starting an ability across devices and returning the result data

| API| Description|
| -------- | -------- |
| startAbilityForResult(want: Want, callback: AsyncCallback&lt;AbilityResult&gt;): void; | Starts a UIAbility. This API uses an asynchronous callback to return the result when the UIAbility is terminated.|
| terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback&lt;void&gt;): void;| Terminates this UIAbility. This API uses an asynchronous callback to return the ability result information. It is used together with **startAbilityForResult**.|
| terminateSelfWithResult(parameter: AbilityResult): Promise&lt;void&gt;; | Terminates this UIAbility. This API uses a promise to return the ability result information. It is used together with **startAbilityForResult**.|


### How to Develop

1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).

2. Request the data synchronization permission. The sample code for displaying a dialog box to request the permission is as follows:
   
   ```ts
   requestPermission() {   
       let context = this.context;
       let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC'];
       context.requestPermissionsFromUser(permissions).then((data) => {
           console.info("Succeed to request permission from user with data: "+ JSON.stringify(data));
       }).catch((error) => {
           console.info("Failed to request permission from user with error: "+ JSON.stringify(error));
       })
   }
   ```

3. Set the target component parameters on the initiator, and call **startAbilityForResult()** to start the target UIAbility. **data** in the asynchronous callback is used to receive the information returned by the target UIAbility to the initiator UIAbility after the target UIAbility terminates itself. For details about how to implement **getRemoteDeviceId()**, see [Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-and-serviceextensionability-across-devices-no-data-returned).
   
   ```ts
   let want = {
       deviceId: getRemoteDeviceId(), 
       bundleName: 'com.example.myapplication',
       abilityName: 'FuncAbility',
       moduleName: 'module1', // moduleName is optional.
   }
   // context is the ability-level context of the initiator UIAbility.
   this.context.startAbilityForResult(want).then((data) => {
       // ...
   }).catch((err) => {
       // ...
   })
   ```

4. After the UIAbility task at the target device is complete, call **terminateSelfWithResult()** to return the data to the initiator UIAbility.
   
   ```ts
   const RESULT_CODE: number = 1001;
   let abilityResult = {
       resultCode: RESULT_CODE,
       want: {
           bundleName: 'com.example.myapplication',
           abilityName: 'FuncAbility',
           moduleName: 'module1',
       },
   }
   // context is the ability-level context of the target UIAbility.
   this.context.terminateSelfWithResult(abilityResult, (err) => {
       // ...
   });
   ```

5. The initiator UIAbility receives the information returned by the target UIAbility and processes the information.
   
   ```ts
   const RESULT_CODE: number = 1001;
   
   // ...
   
   // context is the ability-level context of the initiator UIAbility.
   this.context.startAbilityForResult(want).then((data) => {
       if (data?.resultCode === RESULT_CODE) {
           // Parse the information returned by the target UIAbility.
           let info = data.want?.parameters?.info
           // ...
       }
   }).catch((err) => {
       // ...
   })
   ```


## Connecting to ServiceExtensionAbility Across Devices

A system application can connect to a service on another device by calling [connectServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextconnectserviceextensionability). For example, in the distributed game scenario, a tablet is used as the remote control and a smart TV is used as the display.


### Available APIs

**Table 3** APIs for cross-device connection

| API| Description|
| -------- | -------- |
| connectServiceExtensionAbility(want: Want, options: ConnectOptions): number; | Connects to a ServiceExtensionAbility.|
| disconnectServiceExtensionAbility(connection: number, callback: AsyncCallback&lt;void&gt;): void; | Disconnects a connection. This API uses an asynchronous callback to return the result.|
| disconnectServiceExtensionAbility(connection: number): Promise&lt;void&gt;; | Disconnects a connection. This API uses a promise to return the result.|


### How to Develop

1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
   
2. Request the data synchronization permission. The sample code for displaying a dialog box to request the permission is as follows:
   
   ```ts
   requestPermission() {   
       let context = this.context;
       let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC'];
       context.requestPermissionsFromUser(permissions).then((data) => {
           console.info("Succeed to request permission from user with data: "+ JSON.stringify(data));
       }).catch((error) => {
           console.info("Failed to request permission from user with error: "+ JSON.stringify(error));
       })
   }
   ```

3. (Optional) [Implement a background service](serviceextensionability.md#implementing-a-background-service). Perform this operation only if no background service is available.

4. Connect to the background service.
   - Implement the **IAbilityConnection** class. **IAbilityConnection** provides the following callbacks that you should implement: **onConnect()**, **onDisconnect()**, and **onFailed()**. The **onConnect()** callback is invoked when a service is connected, **onDisconnect()** is invoked when a service is unexpectedly disconnected, and **onFailed()** is invoked when the connection to a service fails.
   - Set the target component parameters, including the target device ID, bundle name, and ability name.
   - Call **connectServiceExtensionAbility** to initiate a connection.
   - Receive the service handle returned by the target device when the connection is successful.
   - Perform cross-device invoking and obtain the result returned by the target service.
     
      ```ts
      import rpc from '@ohos.rpc';
      
      const REQUEST_CODE = 99;
      let want = {
          "deviceId": getRemoteDeviceId(), 
          "bundleName": "com.example.myapplication",
          "abilityName": "ServiceExtAbility"
      };
      let options = {
          onConnect(elementName, remote) {
              console.info('onConnect callback');
              if (remote === null) {
                  console.info(`onConnect remote is null`);
                  return;
              }
              let option = new rpc.MessageOption();
              let data = new rpc.MessageParcel();
              let reply = new rpc.MessageParcel();
              data.writeInt(1);
              data.writeInt(99); // You can send data to the target application for corresponding operations.
      
              // @param code Indicates the service request code sent by the client.
              // @param data Indicates the {@link MessageParcel} object sent by the client.
              // @param reply Indicates the response message object sent by the remote service.
              // @param options Specifies whether the operation is synchronous or asynchronous.
              // 
              // @return Returns {@code true} if the operation is successful; returns {@code false} otherwise.
              remote.sendRequest(REQUEST_CODE, data, reply, option).then((ret) => {
                  let msg = reply.readInt();   // Receive the information (100) returned by the target device if the connection is successful.
                  console.info(`sendRequest ret:${ret} msg:${msg}`);
              }).catch((error) => {
                  console.info('sendRequest failed');
              });
          },
          onDisconnect(elementName) {
              console.info('onDisconnect callback');
          },
          onFailed(code) {
              console.info('onFailed callback');
          }
      }
      // The ID returned after the connection is set up must be saved. The ID will be passed for service disconnection.
      let connectionId = this.context.connectServiceExtensionAbility(want, options);
      ```

      For details about how to implement **getRemoteDeviceId()**, see [Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-and-serviceextensionability-across-devices-no-data-returned).

5. Disconnect the connection. Use **disconnectServiceExtensionAbility()** to disconnect from the background service.
   
   ```ts
   let connectionId = 1 // ID returned when the service is connected through connectServiceExtensionAbility.
   this.context.disconnectServiceExtensionAbility(connectionId).then((data) => {
       console.info('disconnectServiceExtensionAbility success');
   }).catch((error) => {
       console.error('disconnectServiceExtensionAbility failed');
   })
   ```


## Using Cross-Device Ability Call

G
Gloria 已提交
308
The basic principle of cross-device ability call is the same as that of intra-device ability call. For details, see [Using Ability Call to Implement UIAbility Interaction (for System Applications Only)](uiability-intra-device-interaction.md#using-ability-call-to-implement-uiability-interaction-for-system-applications-only).
G
Gloria 已提交
309 310 311 312 313 314 315 316 317 318 319 320 321

The following describes how to implement multi-device collaboration through cross-device ability call.


### Available APIs

**Table 4** Ability call APIs

| API| Description|
| -------- | -------- |
| startAbilityByCall(want: Want): Promise&lt;Caller&gt;; | Starts a UIAbility in the foreground or background and obtains the caller object for communicating with the UIAbility.|
| on(method: string, callback: CalleeCallBack): void | Callback invoked when the callee ability registers a method.|
| off(method: string): void | Callback invoked when the callee ability deregisters a method.|
G
Gloria 已提交
322 323
| call(method: string, data: rpc.Parcelable): Promise&lt;void&gt; | Sends agreed parcelable data to the callee ability.|
| callWithResult(method: string, data: rpc.Parcelable): Promise&lt;rpc.MessageSequence&gt;| Sends agreed parcelable data to the callee ability and obtains the agreed parcelable data returned by the callee ability.|
G
Gloria 已提交
324
| release(): void | Releases the caller object.|
G
Gloria 已提交
325
| on(type: "release", callback: OnReleaseCallback): void | Callback invoked when the caller object is released.|
G
Gloria 已提交
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347


### How to Develop

1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
   
2. Request the data synchronization permission. The sample code for displaying a dialog box to request the permission is as follows:
   
   ```ts
   requestPermission() {   
       let context = this.context;
       let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC'];
       context.requestPermissionsFromUser(permissions).then((data) => {
           console.info("Succeed to request permission from user with data: "+ JSON.stringify(data));
       }).catch((error) => {
           console.info("Failed to request permission from user with error: "+ JSON.stringify(error));
       })
   }
   ```

3. Create the callee ability.
   
G
Gloria 已提交
348
   For the callee ability, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use **on()** to register a listener. When data does not need to be received, use **off()** to deregister the listener.
G
Gloria 已提交
349 350

   1. Configure the launch type of the UIAbility.
G
Gloria 已提交
351
       Set **launchType** of the callee ability to **singleton** in the **module.json5** file.
G
Gloria 已提交
352

G
Gloria 已提交
353 354 355
       | JSON Field| Description|
       | -------- | -------- |
       | "launchType"| Ability launch type. Set this parameter to **singleton**.|
G
Gloria 已提交
356

G
Gloria 已提交
357
       An example of the UIAbility configuration is as follows:
G
Gloria 已提交
358

G
Gloria 已提交
359
       
G
Gloria 已提交
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
       ```json
       "abilities":[{
           "name": ".CalleeAbility",
           "srcEntrance": "./ets/CalleeAbility/CalleeAbility.ts",
           "launchType": "singleton",
           "description": "$string:CalleeAbility_desc",
           "icon": "$media:icon",
           "label": "$string:CalleeAbility_label",
           "visible": true
       }]
       ```
   2. Import the **UIAbility** module.
      
       ```ts
       import Ability from '@ohos.app.ability.UIAbility';
       ```
G
Gloria 已提交
376 377 378 379 380
   3. Define the agreed parcelable data.

       The data formats sent and received by the caller and callee abilities must be consistent. In the following example, the data formats are number and string.

       
G
Gloria 已提交
381
       ```ts
G
Gloria 已提交
382
       export default class MyParcelable {
G
Gloria 已提交
383 384
           num: number = 0;
           str: string = "";
G
Gloria 已提交
385 386
       
           constructor(num, string) {
G
Gloria 已提交
387 388
               this.num = num;
               this.str = string;
G
Gloria 已提交
389 390
           }
       
G
Gloria 已提交
391 392 393
           marshalling(messageSequence) {
               messageSequence.writeInt(this.num);
               messageSequence.writeString(this.str);
G
Gloria 已提交
394
               return true;
G
Gloria 已提交
395 396
           }
       
G
Gloria 已提交
397 398 399
           unmarshalling(messageSequence) {
               this.num = messageSequence.readInt();
               this.str = messageSequence.readString();
G
Gloria 已提交
400
               return true;
G
Gloria 已提交
401 402 403 404
           }
       }
       ```
   4. Implement **Callee.on** and **Callee.off**.
G
Gloria 已提交
405 406

         In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate()** of the ability and deregistered in **onDestroy()**. After receiving parcelable data, the application processes the data and returns the data result. You need to implement processing based on service requirements.
G
Gloria 已提交
407
         
G
Gloria 已提交
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
       ```ts
       const TAG: string = '[CalleeAbility]';
       const MSG_SEND_METHOD: string = 'CallSendMsg';
       
       function sendMsgCallback(data) {
           console.info('CalleeSortFunc called');
       
           // Obtain the parcelable data sent by the caller ability.
           let receivedData = new MyParcelable(0, '');
           data.readParcelable(receivedData);
           console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`);
       
           // Process the data.
           // Return the parcelable data result to the caller ability.
           return new MyParcelable(receivedData.num + 1, `send ${receivedData.str} succeed`);
       }
       
       export default class CalleeAbility extends Ability {
           onCreate(want, launchParam) {
               try {
                   this.callee.on(MSG_SEND_METHOD, sendMsgCallback);
               } catch (error) {
                   console.info(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`);
               }
           }
       
           onDestroy() {
               try {
                   this.callee.off(MSG_SEND_METHOD);
               } catch (error) {
                   console.error(TAG, `${MSG_SEND_METHOD} unregister failed with error ${JSON.stringify(error)}`);
               }
           }
       }
       ```

G
Gloria 已提交
444 445 446 447 448 449 450
4. Obtain the caller object and access the callee ability.
   1. Import the **UIAbility** module.
      
       ```ts
       import Ability from '@ohos.app.ability.UIAbility';
       ```
   2. Obtain the caller object.
G
Gloria 已提交
451

G
Gloria 已提交
452
       The **context** attribute of the ability implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **context** attribute of the ability, uses **startAbilityByCall** to start the callee ability, obtain the caller object, and register the **onRelease** listener of the caller ability. You need to implement processing based on service requirements.
G
Gloria 已提交
453

G
Gloria 已提交
454 455 456
       
       ```ts
       async onButtonGetRemoteCaller() {
G
Gloria 已提交
457 458
           var caller = undefined;
           var context = this.context;
G
Gloria 已提交
459 460 461 462 463 464 465
       
           context.startAbilityByCall({
               deviceId: getRemoteDeviceId(),
               bundleName: 'com.samples.CallApplication',
               abilityName: 'CalleeAbility'
           }).then((data) => {
               if (data != null) {
G
Gloria 已提交
466 467
                   caller = data;
                   console.info('get remote caller success');
G
Gloria 已提交
468 469
                   // Register the onRelease() listener of the caller ability.
                   caller.onRelease((msg) => {
G
Gloria 已提交
470
                       console.info(`remote caller onRelease is called ${msg}`);
G
Gloria 已提交
471
                   })
G
Gloria 已提交
472
                   console.info('remote caller register OnRelease succeed');
G
Gloria 已提交
473 474
               }
           }).catch((error) => {
G
Gloria 已提交
475
               console.error(`get remote caller failed with ${error}`);
G
Gloria 已提交
476 477
           })
       }
G
Gloria 已提交
478 479 480 481
       ```

       For details about how to implement **getRemoteDeviceId()**, see [Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-and-serviceextensionability-across-devices-no-data-returned).

G
Gloria 已提交
482 483
5. Sends agreed parcelable data to the callee ability.
   1. The parcelable data can be sent to the callee ability with or without a return value. The method and parcelable data must be consistent with those of the callee ability. The following example describes how to send data to the callee ability.
G
Gloria 已提交
484 485 486 487 488
      
       ```ts
       const MSG_SEND_METHOD: string = 'CallSendMsg';
       async onButtonCall() {
           try {
G
Gloria 已提交
489
               let msg = new MyParcelable(1, 'origin_Msg');
G
Gloria 已提交
490 491 492 493 494 495 496 497 498 499 500 501 502 503
               await this.caller.call(MSG_SEND_METHOD, msg);
           } catch (error) {
               console.info(`caller call failed with ${error}`);
           }
       }
       ```
   2. In the following, **CallWithResult** is used to send data **originMsg** to the callee ability and assign the data processed by the **CallSendMsg** method to **backMsg**.
      
       ```ts
       const MSG_SEND_METHOD: string = 'CallSendMsg';
       originMsg: string = '';
       backMsg: string = '';
       async onButtonCallWithResult(originMsg, backMsg) {
           try {
G
Gloria 已提交
504
               let msg = new MyParcelable(1, originMsg);
G
Gloria 已提交
505 506 507
               const data = await this.caller.callWithResult(MSG_SEND_METHOD, msg);
               console.info('caller callWithResult succeed');
       
G
Gloria 已提交
508 509
               let result = new MyParcelable(0, '');
               data.readParcelable(result);
G
Gloria 已提交
510 511 512 513 514 515 516 517 518 519
               backMsg(result.str);
               console.info(`caller result is [${result.num}, ${result.str}]`);
           } catch (error) {
               console.info(`caller callWithResult failed with ${error}`);
           }
       }
       ```

6. Release the caller object.

G
Gloria 已提交
520 521
     When the caller object is no longer required, use **release()** to release it.
     
G
Gloria 已提交
522 523 524 525 526 527 528 529 530 531 532
   ```ts
   releaseCall() {
       try {
           this.caller.release();
           this.caller = undefined
           console.info('caller release succeed');
       } catch (error) {
           console.info(`caller release failed with ${error}`);
       }
   }
   ```