1# UIAbilityContext 2 3<!--Kit: Ability Kit--> 4<!--Subsystem: Ability--> 5<!--Owner: @zhu-feimo--> 6<!--Designer: @ccllee1--> 7<!--Tester: @lixueqing513--> 8<!--Adviser: @huipeizi--> 9 10UIAbilityContext provides the context environment for a [UIAbility](./js-apis-app-ability-uiAbility.md). It inherits from [Context](./js-apis-inner-application-context.md). For details about the relationships and differences between various types of contexts, see [Context](../../application-models/application-context-stage.md). 11 12When a UIAbility component is instantiated, the system automatically creates the corresponding UIAbilityContext. You can use the APIs provided by UIAbilityContext to obtain the ability information (AbilityInfo), application information (ApplicationInfo), and other information, start another UIAbility, connect to system services, and destroy a UIAbility. 13 14> **NOTE** 15> 16> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. 17> - The APIs of this module can be used only in the stage model. 18> - In the sample code provided in this topic, **this.context** is used to obtain UIAbilityContext, where **this** indicates an instance that inherits from UIAbility. 19 20## Modules to Import 21 22```ts 23import { common } from '@kit.AbilityKit'; 24``` 25 26## UIAbilityContext 27 28### Properties 29 30**System capability**: SystemCapability.Ability.AbilityRuntime.Core 31 32| Name| Type| Read-Only| Optional| Description| 33| -------- | -------- | -------- | -------- | -------- | 34| abilityInfo | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | No| No| UIAbility information.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 35| currentHapModuleInfo | [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) | No| No| Information about the HAP to which the UIAbility belongs.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 36| config | [Configuration](js-apis-app-ability-configuration.md) | No| No| UIAbility configuration, such as the language and color mode.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 37| windowStage<sup>12+</sup> | [window.WindowStage](../apis-arkui/arkts-apis-window-WindowStage.md) | No| No| WindowStage object. It can be called only by the main thread.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 38 39### startAbility 40 41startAbility(want: Want, callback: AsyncCallback<void>): void 42 43Starts an ability. This API uses an asynchronous callback to return the result. It can be called only by the main thread. 44 45> **NOTE** 46> 47> For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). 48 49**Atomic service API**: This API can be used in atomic services since API version 11. 50 51**System capability**: SystemCapability.Ability.AbilityRuntime.Core 52 53**Parameters** 54 55| Name| Type| Mandatory| Description| 56| -------- | -------- | -------- | -------- | 57| want | [Want](js-apis-app-ability-want.md) | Yes| Mandatory information for starting the ability.| 58| callback | AsyncCallback<void> | Yes| Callback used to return the result.| 59 60**Error codes** 61 62For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 63 64| ID| Error Message| 65| ------- | -------------------------------- | 66| 201 | The application does not have permission to call the interface. | 67| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 68| 16000001 | The specified ability does not exist. | 69| 16000002 | Incorrect ability type. | 70| 16000004 | Cannot start an invisible component. | 71| 16000005 | The specified process does not have the permission. | 72| 16000006 | Cross-user operations are not allowed. | 73| 16000008 | The crowdtesting application expires. | 74| 16000009 | An ability cannot be started or stopped in Wukong mode. | 75| 16000010 | The call with the continuation and prepare continuation flag is forbidden. | 76| 16000011 | The context does not exist. | 77| 16000012 | The application is controlled. | 78| 16000013 | The application is controlled by EDM. | 79| 16000018 | Redirection to a third-party application is not allowed in API version greater than 11. | 80| 16000019 | No matching ability is found. | 81| 16000050 | Internal error. | 82| 16000053 | The ability is not on the top of the UI. | 83| 16000055 | Installation-free timed out. | 84| 16000071 | App clone is not supported. | 85| 16000072 | App clone or multi-instance is not supported. | 86| 16000073 | The app clone index is invalid. | 87| 16000076 | The app instance key is invalid. | 88| 16000077 | The number of app instances reaches the limit. | 89| 16000078 | The multi-instance is not supported. | 90| 16000079 | The APP_INSTANCE_KEY cannot be specified. | 91| 16000080 | Creating a new instance is not supported. | 92| 16200001 | The caller has been released. | 93 94**Example** 95 96```ts 97import { UIAbility, Want } from '@kit.AbilityKit'; 98import { BusinessError } from '@kit.BasicServicesKit'; 99 100export default class EntryAbility extends UIAbility { 101 onForeground() { 102 let want: Want = { 103 bundleName: 'com.example.myapplication', 104 abilityName: 'EntryAbility' 105 }; 106 107 try { 108 this.context.startAbility(want, (err: BusinessError) => { 109 if (err.code) { 110 // Process service logic errors. 111 console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); 112 return; 113 } 114 // Carry out normal service processing. 115 console.info('startAbility succeed'); 116 }); 117 } catch (err) { 118 // Process input parameter errors. 119 let code = (err as BusinessError).code; 120 let message = (err as BusinessError).message; 121 console.error(`startAbility failed, code is ${code}, message is ${message}`); 122 } 123 } 124} 125``` 126 127### startAbility 128 129startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void 130 131Starts an ability. This API uses an asynchronous callback to return the result. It can be called only by the main thread. 132 133> **NOTE** 134> 135> For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). 136 137**Atomic service API**: This API can be used in atomic services since API version 11. 138 139**System capability**: SystemCapability.Ability.AbilityRuntime.Core 140 141**Parameters** 142 143| Name| Type| Mandatory| Description| 144| -------- | -------- | -------- | -------- | 145| want | [Want](js-apis-app-ability-want.md) | Yes| Mandatory information for starting the ability.| 146| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.| 147| callback | AsyncCallback<void> | Yes| Callback used to return the result.| 148 149**Error codes** 150 151For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 152 153| ID| Error Message| 154| ------- | -------------------------------- | 155| 201 | The application does not have permission to call the interface. | 156| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 157| 801 | Capability not support. | 158| 16000001 | The specified ability does not exist. | 159| 16000004 | Cannot start an invisible component. | 160| 16000005 | The specified process does not have the permission. | 161| 16000006 | Cross-user operations are not allowed. | 162| 16000008 | The crowdtesting application expires. | 163| 16000009 | An ability cannot be started or stopped in Wukong mode. | 164| 16000011 | The context does not exist. | 165| 16000012 | The application is controlled. | 166| 16000013 | The application is controlled by EDM. | 167| 16000018 | Redirection to a third-party application is not allowed in API version greater than 11. | 168| 16000019 | No matching ability is found. | 169| 16000050 | Internal error. | 170| 16000053 | The ability is not on the top of the UI. | 171| 16000055 | Installation-free timed out. | 172| 16000067 | The StartOptions check failed. | 173| 16000068 | The ability is already running. | 174| 16300003 | The target application is not the current application. | 175| 16000071 | App clone is not supported. | 176| 16000072 | App clone or multi-instance is not supported. | 177| 16000073 | The app clone index is invalid. | 178| 16000076 | The app instance key is invalid. | 179| 16000077 | The number of app instances reaches the limit. | 180| 16000078 | The multi-instance is not supported. | 181| 16000079 | The APP_INSTANCE_KEY cannot be specified. | 182| 16000080 | Creating a new instance is not supported. | 183| 16200001 | The caller has been released. | 184 185**Example** 186 187```ts 188import { UIAbility, Want, StartOptions } from '@kit.AbilityKit'; 189import { BusinessError } from '@kit.BasicServicesKit'; 190 191export default class EntryAbility extends UIAbility { 192 onForeground() { 193 let want: Want = { 194 deviceId: '', 195 bundleName: 'com.example.myapplication', 196 abilityName: 'EntryAbility' 197 }; 198 let options: StartOptions = { 199 displayId: 0 200 }; 201 202 try { 203 this.context.startAbility(want, options, (err: BusinessError) => { 204 if (err.code) { 205 // Process service logic errors. 206 console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); 207 return; 208 } 209 // Carry out normal service processing. 210 console.info('startAbility succeed'); 211 }); 212 } catch (err) { 213 // Process input parameter errors. 214 let code = (err as BusinessError).code; 215 let message = (err as BusinessError).message; 216 console.error(`startAbility failed, code is ${code}, message is ${message}`); 217 } 218 } 219} 220``` 221 222### startAbility 223 224startAbility(want: Want, options?: StartOptions): Promise<void> 225 226Starts an ability. This API uses a promise to return the result. It can be called only by the main thread. 227 228> **NOTE** 229> 230> For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). 231 232**Atomic service API**: This API can be used in atomic services since API version 11. 233 234**System capability**: SystemCapability.Ability.AbilityRuntime.Core 235 236**Parameters** 237 238| Name| Type| Mandatory| Description| 239| -------- | -------- | -------- | -------- | 240| want | [Want](js-apis-app-ability-want.md) | Yes| Mandatory information for starting the ability.| 241| options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.| 242 243**Return value** 244 245| Type| Description| 246| -------- | -------- | 247| Promise<void> | Promise that returns no value.| 248 249**Error codes** 250 251For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 252 253| ID| Error Message| 254| ------- | -------------------------------- | 255| 201 | The application does not have permission to call the interface. | 256| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 257| 801 | Capability not support. | 258| 16000001 | The specified ability does not exist. | 259| 16000002 | Incorrect ability type. | 260| 16000004 | Cannot start an invisible component. | 261| 16000005 | The specified process does not have the permission. | 262| 16000006 | Cross-user operations are not allowed. | 263| 16000008 | The crowdtesting application expires. | 264| 16000009 | An ability cannot be started or stopped in Wukong mode. | 265| 16000010 | The call with the continuation and prepare continuation flag is forbidden. | 266| 16000011 | The context does not exist. | 267| 16000012 | The application is controlled. | 268| 16000013 | The application is controlled by EDM. | 269| 16000018 | Redirection to a third-party application is not allowed in API version greater than 11. | 270| 16000019 | No matching ability is found. | 271| 16000050 | Internal error. | 272| 16000053 | The ability is not on the top of the UI. | 273| 16000055 | Installation-free timed out. | 274| 16000067 | The StartOptions check failed. | 275| 16000068 | The ability is already running. | 276| 16300003 | The target application is not the current application. | 277| 16000071 | App clone is not supported. | 278| 16000072 | App clone or multi-instance is not supported. | 279| 16000073 | The app clone index is invalid. | 280| 16000076 | The app instance key is invalid. | 281| 16000077 | The number of app instances reaches the limit. | 282| 16000078 | The multi-instance is not supported. | 283| 16000079 | The APP_INSTANCE_KEY cannot be specified. | 284| 16000080 | Creating a new instance is not supported. | 285| 16200001 | The caller has been released. | 286 287**Example** 288 289```ts 290import { UIAbility, Want, StartOptions } from '@kit.AbilityKit'; 291import { BusinessError } from '@kit.BasicServicesKit'; 292 293export default class EntryAbility extends UIAbility { 294 onForeground() { 295 let want: Want = { 296 bundleName: 'com.example.myapplication', 297 abilityName: 'EntryAbility' 298 }; 299 let options: StartOptions = { 300 displayId: 0 301 }; 302 303 try { 304 this.context.startAbility(want, options) 305 .then(() => { 306 // Carry out normal service processing. 307 console.info('startAbility succeed'); 308 }) 309 .catch((err: BusinessError) => { 310 // Process service logic errors. 311 console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); 312 }); 313 } catch (err) { 314 // Process input parameter errors. 315 let code = (err as BusinessError).code; 316 let message = (err as BusinessError).message; 317 console.error(`startAbility failed, code is ${code}, message is ${message}`); 318 } 319 } 320} 321``` 322 323### startAbilityForResult 324 325startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void 326 327Starts a UIAbility and returns the exit result of the launched UIAbility via a callback. This API uses an asynchronous callback to return the result. It can be called only by the main thread. 328 329The following situations may be possible for a started UIAbility: 330 - Normally, you can call [terminateSelfWithResult](#terminateselfwithresult) to terminate the UIAbility. The result is returned to the caller. 331 - If an exception occurs, for example, the UIAbility is killed, an error message, in which **resultCode** is **-1**, is returned to the initiator UIAbility. 332 - If different applications call this API to start a UIAbility that uses the singleton mode and then call [terminateSelfWithResult](#terminateselfwithresult) to terminate the UIAbility, the normal result is returned to the last initiator UIAbility, and an error message, in which **resultCode** is **-1**, is returned to others. 333 334> **NOTE** 335> 336> For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). 337 338**Atomic service API**: This API can be used in atomic services since API version 11. 339 340**System capability**: SystemCapability.Ability.AbilityRuntime.Core 341 342**Parameters** 343 344| Name| Type| Mandatory| Description| 345| -------- | -------- | -------- | -------- | 346| want |[Want](js-apis-app-ability-want.md) | Yes| Mandatory information for starting the ability.| 347| callback | AsyncCallback<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Yes| Callback used to return the result.| 348 349**Error codes** 350 351For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 352 353| ID| Error Message| 354| ------- | -------------------------------- | 355| 201 | The application does not have permission to call the interface. | 356| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 357| 16000001 | The specified ability does not exist. | 358| 16000002 | Incorrect ability type. | 359| 16000004 | Cannot start an invisible component. | 360| 16000005 | The specified process does not have the permission. | 361| 16000006 | Cross-user operations are not allowed. | 362| 16000008 | The crowdtesting application expires. | 363| 16000009 | An ability cannot be started or stopped in Wukong mode. | 364| 16000010 | The call with the continuation and prepare continuation flag is forbidden. | 365| 16000011 | The context does not exist. | 366| 16000012 | The application is controlled. | 367| 16000013 | The application is controlled by EDM. | 368| 16000018 | Redirection to a third-party application is not allowed in API version greater than 11. | 369| 16000019 | No matching ability is found. | 370| 16000050 | Internal error. | 371| 16000053 | The ability is not on the top of the UI. | 372| 16000055 | Installation-free timed out. | 373| 16000071 | App clone is not supported. | 374| 16000072 | App clone or multi-instance is not supported. | 375| 16000073 | The app clone index is invalid. | 376| 16000076 | The app instance key is invalid. | 377| 16000077 | The number of app instances reaches the limit. | 378| 16000078 | The multi-instance is not supported. | 379| 16000079 | The APP_INSTANCE_KEY cannot be specified. | 380| 16000080 | Creating a new instance is not supported. | 381| 16200001 | The caller has been released. | 382 383**Example** 384 385```ts 386import { UIAbility, Want, common } from '@kit.AbilityKit'; 387import { BusinessError } from '@kit.BasicServicesKit'; 388 389export default class EntryAbility extends UIAbility { 390 onForeground() { 391 let want: Want = { 392 deviceId: '', 393 bundleName: 'com.example.myapplication', 394 abilityName: 'EntryAbility' 395 }; 396 397 try { 398 this.context.startAbilityForResult(want, (err: BusinessError, result: common.AbilityResult) => { 399 if (err.code) { 400 // Process service logic errors. 401 console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`); 402 return; 403 } 404 // Carry out normal service processing. 405 console.info('startAbilityForResult succeed'); 406 }); 407 } catch (err) { 408 // Process input parameter errors. 409 let code = (err as BusinessError).code; 410 let message = (err as BusinessError).message; 411 console.error(`startAbilityForResult failed, code is ${code}, message is ${message}`); 412 } 413 } 414} 415``` 416 417### startAbilityForResult 418 419startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>): void 420 421Starts a UIAbility and returns the exit result of the launched UIAbility via a callback. This API uses an asynchronous callback to return the result. It can be called only by the main thread. 422 423The following situations may be possible for a started UIAbility: 424 - Normally, you can call [terminateSelfWithResult](#terminateselfwithresult) to terminate the UIAbility. The result is returned to the caller. 425 - If an exception occurs, for example, the UIAbility is killed, an error message, in which **resultCode** is **-1**, is returned to the initiator UIAbility. 426 - If different applications call this API to start a UIAbility that uses the singleton mode and then call [terminateSelfWithResult](#terminateselfwithresult) to terminate the UIAbility, the normal result is returned to the last initiator UIAbility, and an error message, in which **resultCode** is **-1**, is returned to others. 427 428> **NOTE** 429> 430> For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). 431 432**Atomic service API**: This API can be used in atomic services since API version 11. 433 434**System capability**: SystemCapability.Ability.AbilityRuntime.Core 435 436**Parameters** 437 438| Name| Type| Mandatory| Description| 439| -------- | -------- | -------- | -------- | 440| want |[Want](js-apis-app-ability-want.md) | Yes| Mandatory information for starting the ability.| 441| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.| 442| callback | AsyncCallback<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Yes| Callback used to return the result.| 443 444**Error codes** 445 446For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 447 448| ID| Error Message| 449| ------- | -------------------------------- | 450| 201 | The application does not have permission to call the interface. | 451| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 452| 16000001 | The specified ability does not exist. | 453| 16000004 | Cannot start an invisible component. | 454| 16000005 | The specified process does not have the permission. | 455| 16000006 | Cross-user operations are not allowed. | 456| 16000008 | The crowdtesting application expires. | 457| 16000009 | An ability cannot be started or stopped in Wukong mode. | 458| 16000011 | The context does not exist. | 459| 16000012 | The application is controlled. | 460| 16000013 | The application is controlled by EDM. | 461| 16000018 | Redirection to a third-party application is not allowed in API version greater than 11. | 462| 16000019 | No matching ability is found. | 463| 16000050 | Internal error. | 464| 16000053 | The ability is not on the top of the UI. | 465| 16000055 | Installation-free timed out. | 466| 16000071 | App clone is not supported. | 467| 16000072 | App clone or multi-instance is not supported. | 468| 16000073 | The app clone index is invalid. | 469| 16000076 | The app instance key is invalid. | 470| 16000077 | The number of app instances reaches the limit. | 471| 16000078 | The multi-instance is not supported. | 472| 16000079 | The APP_INSTANCE_KEY cannot be specified. | 473| 16000080 | Creating a new instance is not supported. | 474| 16200001 | The caller has been released. | 475 476**Example** 477 478```ts 479import { UIAbility, Want, common, StartOptions } from '@kit.AbilityKit'; 480import { BusinessError } from '@kit.BasicServicesKit'; 481 482export default class EntryAbility extends UIAbility { 483 onForeground() { 484 let want: Want = { 485 deviceId: '', 486 bundleName: 'com.example.myapplication', 487 abilityName: 'EntryAbility' 488 }; 489 let options: StartOptions = { 490 displayId: 0 491 }; 492 493 try { 494 this.context.startAbilityForResult(want, options, (err: BusinessError, result: common.AbilityResult) => { 495 if (err.code) { 496 // Process service logic errors. 497 console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`); 498 return; 499 } 500 // Carry out normal service processing. 501 console.info('startAbilityForResult succeed'); 502 }); 503 } catch (err) { 504 // Process input parameter errors. 505 let code = (err as BusinessError).code; 506 let message = (err as BusinessError).message; 507 console.error(`startAbilityForResult failed, code is ${code}, message is ${message}`); 508 } 509 } 510} 511``` 512 513 514### startAbilityForResult 515 516startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityResult> 517 518Starts a UIAbility and returns the exit result of the launched UIAbility via a callback. This API uses a promise to return the result. It can be called only by the main thread. 519 520The following situations may be possible for a started UIAbility: 521 - Normally, you can call [terminateSelfWithResult](#terminateselfwithresult) to terminate the UIAbility. The result is returned to the caller. 522 - If an exception occurs, for example, the UIAbility is killed, an error message, in which **resultCode** is **-1**, is returned to the initiator UIAbility. 523 - If different applications call this API to start a UIAbility that uses the singleton mode and then call [terminateSelfWithResult](#terminateselfwithresult) to terminate the UIAbility, the normal result is returned to the last initiator UIAbility, and an error message, in which **resultCode** is **-1**, is returned to others. 524 525> **NOTE** 526> 527> For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). 528 529**Atomic service API**: This API can be used in atomic services since API version 11. 530 531**System capability**: SystemCapability.Ability.AbilityRuntime.Core 532 533**Parameters** 534 535| Name| Type| Mandatory| Description| 536| -------- | -------- | -------- | -------- | 537| want | [Want](js-apis-app-ability-want.md) | Yes| Mandatory information for starting the ability.| 538| options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.| 539 540 541**Return value** 542 543| Type| Description| 544| -------- | -------- | 545| Promise<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Promise used to return the result.| 546 547**Error codes** 548 549For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 550 551| ID| Error Message| 552| ------- | -------------------------------- | 553| 201 | The application does not have permission to call the interface. | 554| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 555| 16000001 | The specified ability does not exist. | 556| 16000002 | Incorrect ability type. | 557| 16000004 | Cannot start an invisible component. | 558| 16000005 | The specified process does not have the permission. | 559| 16000006 | Cross-user operations are not allowed. | 560| 16000008 | The crowdtesting application expires. | 561| 16000009 | An ability cannot be started or stopped in Wukong mode. | 562| 16000010 | The call with the continuation and prepare continuation flag is forbidden. | 563| 16000011 | The context does not exist. | 564| 16000012 | The application is controlled. | 565| 16000013 | The application is controlled by EDM. | 566| 16000018 | Redirection to a third-party application is not allowed in API version greater than 11. | 567| 16000019 | No matching ability is found. | 568| 16000050 | Internal error. | 569| 16000053 | The ability is not on the top of the UI. | 570| 16000055 | Installation-free timed out. | 571| 16000071 | App clone is not supported. | 572| 16000072 | App clone or multi-instance is not supported. | 573| 16000073 | The app clone index is invalid. | 574| 16000076 | The app instance key is invalid. | 575| 16000077 | The number of app instances reaches the limit. | 576| 16000078 | The multi-instance is not supported. | 577| 16000079 | The APP_INSTANCE_KEY cannot be specified. | 578| 16000080 | Creating a new instance is not supported. | 579| 16200001 | The caller has been released. | 580 581**Example** 582 583```ts 584import { UIAbility, Want, common, StartOptions } from '@kit.AbilityKit'; 585import { BusinessError } from '@kit.BasicServicesKit'; 586 587export default class EntryAbility extends UIAbility { 588 onForeground() { 589 let want: Want = { 590 bundleName: 'com.example.myapplication', 591 abilityName: 'EntryAbility' 592 }; 593 let options: StartOptions = { 594 displayId: 0 595 }; 596 597 try { 598 this.context.startAbilityForResult(want, options) 599 .then((result: common.AbilityResult) => { 600 // Carry out normal service processing. 601 console.info('startAbilityForResult succeed'); 602 }) 603 .catch((err: BusinessError) => { 604 // Process service logic errors. 605 console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`); 606 }); 607 } catch (err) { 608 // Process input parameter errors. 609 let code = (err as BusinessError).code; 610 let message = (err as BusinessError).message; 611 console.error(`startAbilityForResult failed, code is ${code}, message is ${message}`); 612 } 613 } 614} 615``` 616 617### terminateSelf 618 619terminateSelf(callback: AsyncCallback<void>): void 620 621Terminates this UIAbility. This API uses an asynchronous callback to return the result. It can be called only by the main thread. 622 623> **NOTE** 624> 625> After this API is called, missions in the task center are not cleared by default. To clear missions, set [removeMissionAfterTerminate](../../quick-start/module-configuration-file.md#abilities) to **true**. 626 627**Atomic service API**: This API can be used in atomic services since API version 11. 628 629**System capability**: SystemCapability.Ability.AbilityRuntime.Core 630 631**Parameters** 632 633| Name| Type| Mandatory| Description| 634| -------- | -------- | -------- | -------- | 635| callback | AsyncCallback<void> | Yes| Callback used to return the result.| 636 637**Error codes** 638 639For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 640 641| ID| Error Message| 642| ------- | -------------------------------- | 643| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 644| 16000009 | An ability cannot be started or stopped in Wukong mode. | 645| 16000011 | The context does not exist. | 646| 16000050 | Internal error. | 647 648**Example** 649 6501. The following is an example of calling **terminateSelf** to terminate a UIAbility. By default, the application retains the snapshot in the recent tasks list. 651 652 ```ts 653 import { UIAbility } from '@kit.AbilityKit'; 654 import { BusinessError } from '@kit.BasicServicesKit'; 655 656 export default class EntryAbility extends UIAbility { 657 onForeground() { 658 try { 659 this.context.terminateSelf((err: BusinessError) => { 660 if (err.code) { 661 // Process service logic errors. 662 console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`); 663 return; 664 } 665 // Carry out normal service processing. 666 console.info('terminateSelf succeed'); 667 }); 668 } catch (err) { 669 // Capture the synchronization parameter error. 670 let code = (err as BusinessError).code; 671 let message = (err as BusinessError).message; 672 console.error(`terminateSelf failed, code is ${code}, message is ${message}`); 673 } 674 } 675 } 676 ``` 677 6782. (Optional) To remove the mission from the task center (that is, not to retain the snapshot in the recent tasks list) when terminating the UIAbility, set the **removeMissionAfterTerminate** field to **true** in the [module.json5](../../quick-start/module-configuration-file.md) file. 679 680 ```json 681 { 682 "module": { 683 // ... 684 "abilities": [ 685 { 686 // ... 687 "removeMissionAfterTerminate": true 688 } 689 ] 690 } 691 } 692 ``` 693 694### terminateSelf 695 696terminateSelf(): Promise<void> 697 698Terminates this UIAbility. This API uses a promise to return the result. It can be called only by the main thread. 699 700> **NOTE** 701> 702> After this API is called, missions in the task center are not cleared by default. To clear missions, set [removeMissionAfterTerminate](../../quick-start/module-configuration-file.md#abilities) to **true**. 703 704**Atomic service API**: This API can be used in atomic services since API version 11. 705 706**System capability**: SystemCapability.Ability.AbilityRuntime.Core 707 708**Return value** 709 710| Type| Description| 711| -------- | -------- | 712| Promise<void> | Promise that returns no value.| 713 714**Error codes** 715 716For details about the error codes, see [Ability Error Codes](errorcode-ability.md). 717 718| ID| Error Message| 719| ------- | -------------------------------- | 720| 16000009 | An ability cannot be started or stopped in Wukong mode. | 721| 16000011 | The context does not exist. | 722| 16000050 | Internal error. | 723 724 725**Example** 726 7271. The following is an example of calling **terminateSelf** to terminate a UIAbility. By default, the application retains the snapshot in the recent tasks list. 728 729 ```ts 730 import { UIAbility } from '@kit.AbilityKit'; 731 import { BusinessError } from '@kit.BasicServicesKit'; 732 733 export default class EntryAbility extends UIAbility { 734 onForeground() { 735 try { 736 this.context.terminateSelf() 737 .then(() => { 738 // Carry out normal service processing. 739 console.info('terminateSelf succeed'); 740 }) 741 .catch((err: BusinessError) => { 742 // Process service logic errors. 743 console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`); 744 }); 745 } catch (err) { 746 // Capture the synchronization parameter error. 747 let code = (err as BusinessError).code; 748 let message = (err as BusinessError).message; 749 console.error(`terminateSelf failed, code is ${code}, message is ${message}`); 750 } 751 } 752 } 753 ``` 754 7552. (Optional) To remove the mission from the task center (that is, not to retain the snapshot in the recent tasks list) when terminating the UIAbility, set the **removeMissionAfterTerminate** field to **true** in the [module.json5](../../quick-start/module-configuration-file.md) file. 756 757 ```json 758 { 759 "module": { 760 // ... 761 "abilities": [ 762 { 763 // ... 764 "removeMissionAfterTerminate": true 765 } 766 ] 767 } 768 } 769 ``` 770 771### terminateSelfWithResult 772 773terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>): void 774 775Terminates this UIAbility. This API uses an asynchronous callback to return the result. It can be called only by the main thread. 776 777The result is returned to the caller when **terminateSelfWithResult** is called to terminate the UIAbility that is started by calling [startAbilityForResult](#startabilityforresult). 778 779> **NOTE** 780> 781> After this API is called, missions in the task center are not cleared by default. To clear missions, set [removeMissionAfterTerminate](../../quick-start/module-configuration-file.md#abilities) to **true**. 782 783**Atomic service API**: This API can be used in atomic services since API version 11. 784 785**System capability**: SystemCapability.Ability.AbilityRuntime.Core 786 787**Parameters** 788 789| Name| Type| Mandatory| Description| 790| -------- | -------- | -------- | -------- | 791| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes| Information returned to the caller.| 792| callback | AsyncCallback<void> | Yes| Callback used to return the result.| 793 794**Error codes** 795 796For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 797 798| ID| Error Message| 799| ------- | -------------------------------- | 800| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 801| 16000009 | An ability cannot be started or stopped in Wukong mode. | 802| 16000011 | The context does not exist. | 803| 16000050 | Internal error. | 804 805 806**Example** 807 808```ts 809import { UIAbility, Want, common } from '@kit.AbilityKit'; 810import { BusinessError } from '@kit.BasicServicesKit'; 811 812export default class EntryAbility extends UIAbility { 813 onForeground() { 814 let want: Want = { 815 bundleName: 'com.example.myapplication', 816 abilityName: 'EntryAbility' 817 }; 818 let resultCode = 100; 819 // AbilityResult information returned to the caller. 820 let abilityResult: common.AbilityResult = { 821 want, 822 resultCode 823 }; 824 825 try { 826 this.context.terminateSelfWithResult(abilityResult, (err: BusinessError) => { 827 if (err.code) { 828 // Process service logic errors. 829 console.error(`terminateSelfWithResult failed, code is ${err.code}, message is ${err.message}`); 830 return; 831 } 832 // Carry out normal service processing. 833 console.info('terminateSelfWithResult succeed'); 834 }); 835 } catch (err) { 836 // Process input parameter errors. 837 let code = (err as BusinessError).code; 838 let message = (err as BusinessError).message; 839 console.error(`terminateSelfWithResult failed, code is ${code}, message is ${message}`); 840 } 841 } 842} 843``` 844 845 846### terminateSelfWithResult 847 848terminateSelfWithResult(parameter: AbilityResult): Promise<void> 849 850Terminates this UIAbility. This API uses a promise to return the result. It can be called only by the main thread. 851 852The result is returned to the caller when **terminateSelfWithResult** is called to terminate the UIAbility that is started by calling [startAbilityForResult](#startabilityforresult). 853 854> **NOTE** 855> 856> After this API is called, missions in the task center are not cleared by default. To clear missions, set [removeMissionAfterTerminate](../../quick-start/module-configuration-file.md#abilities) to **true**. 857 858**Atomic service API**: This API can be used in atomic services since API version 11. 859 860**System capability**: SystemCapability.Ability.AbilityRuntime.Core 861 862**Parameters** 863 864| Name| Type| Mandatory| Description| 865| -------- | -------- | -------- | -------- | 866| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes| Information returned to the caller.| 867 868**Return value** 869 870| Type| Description| 871| -------- | -------- | 872| Promise<void> | Promise that returns no value.| 873 874**Error codes** 875 876For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 877 878| ID| Error Message| 879| ------- | -------------------------------- | 880| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 881| 16000009 | An ability cannot be started or stopped in Wukong mode. | 882| 16000011 | The context does not exist. | 883| 16000050 | Internal error. | 884 885 886**Example** 887 888```ts 889import { UIAbility, Want, common } from '@kit.AbilityKit'; 890import { BusinessError } from '@kit.BasicServicesKit'; 891 892export default class EntryAbility extends UIAbility { 893 onForeground() { 894 let want: Want = { 895 bundleName: 'com.example.myapplication', 896 abilityName: 'EntryAbility' 897 }; 898 let resultCode = 100; 899 // AbilityResult information returned to the caller. 900 let abilityResult: common.AbilityResult = { 901 want, 902 resultCode 903 }; 904 905 try { 906 this.context.terminateSelfWithResult(abilityResult) 907 .then(() => { 908 // Carry out normal service processing. 909 console.info('terminateSelfWithResult succeed'); 910 }) 911 .catch((err: BusinessError) => { 912 // Process service logic errors. 913 console.error(`terminateSelfWithResult failed, code is ${err.code}, message is ${err.message}`); 914 }); 915 } catch (err) { 916 // Process input parameter errors. 917 let code = (err as BusinessError).code; 918 let message = (err as BusinessError).message; 919 console.error(`terminateSelfWithResult failed, code is ${code}, message is ${message}`); 920 } 921 } 922} 923``` 924 925### connectServiceExtensionAbility 926 927connectServiceExtensionAbility(want: Want, options: ConnectOptions): number 928 929Connects this UIAbility to a [ServiceExtensionAbility](../../application-models/extensionability-overview.md). It enables communication with the ServiceExtensionAbility via a proxy, allowing access to the capabilities exposed by the ServiceExtensionAbility. It can be called only by the main thread. 930 931> **NOTE** 932> 933> For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). 934 935**System capability**: SystemCapability.Ability.AbilityRuntime.Core 936 937**Parameters** 938 939| Name| Type| Mandatory| Description| 940| -------- | -------- | -------- | -------- | 941| want | [Want](js-apis-app-ability-want.md) | Yes| Want information for connecting to the ServiceExtensionAbility.| 942| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes| Callback used to return the information indicating that the connection is successful, failed, or interrupted.| 943 944**Return value** 945 946| Type| Description| 947| -------- | -------- | 948| number | Connection ID. A caller can call [disconnectServiceExtensionAbility](#disconnectserviceextensionability) with this ID for disconnection.| 949 950**Error codes** 951 952For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 953 954| ID| Error Message| 955| ------- | -------------------------------- | 956| 201 | The application does not have permission to call the interface. | 957| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 958| 16000001 | The specified ability does not exist. | 959| 16000002 | Incorrect ability type. | 960| 16000004 | Cannot start an invisible component. | 961| 16000005 | The specified process does not have the permission. | 962| 16000006 | Cross-user operations are not allowed. | 963| 16000008 | The crowdtesting application expires. | 964| 16000011 | The context does not exist. | 965| 16000050 | Internal error. | 966| 16000053 | The ability is not on the top of the UI. | 967| 16000055 | Installation-free timed out. | 968 969**Example** 970 971```ts 972import { UIAbility, Want, common } from '@kit.AbilityKit'; 973import { rpc } from '@kit.IPCKit'; 974import { BusinessError } from '@kit.BasicServicesKit'; 975 976export default class EntryAbility extends UIAbility { 977 onForeground() { 978 let want: Want = { 979 deviceId: '', 980 bundleName: 'com.example.myapplication', 981 abilityName: 'ServiceExtensionAbility' 982 }; 983 let commRemote: rpc.IRemoteObject; 984 let options: common.ConnectOptions = { 985 onConnect(elementName, remote) { 986 commRemote = remote; 987 console.info('onConnect...'); 988 }, 989 onDisconnect(elementName) { 990 console.info('onDisconnect...'); 991 }, 992 onFailed(code) { 993 console.info('onFailed...'); 994 } 995 }; 996 let connection: number; 997 998 try { 999 connection = this.context.connectServiceExtensionAbility(want, options); 1000 } catch (err) { 1001 // Process input parameter errors. 1002 let code = (err as BusinessError).code; 1003 let message = (err as BusinessError).message; 1004 console.error(`connectServiceExtensionAbility failed, code is ${code}, message is ${message}`); 1005 } 1006 } 1007} 1008``` 1009 1010### disconnectServiceExtensionAbility 1011 1012disconnectServiceExtensionAbility(connection: number): Promise\<void> 1013 1014Disconnects from a [ServiceExtensionAbility](../../application-models/extensionability-overview.md). Once the connection is terminated, set the remote object, which is returned when the connection is established, to null. This API uses a promise to return the result. It can be called only by the main thread. 1015 1016**System capability**: SystemCapability.Ability.AbilityRuntime.Core 1017 1018**Parameters** 1019 1020| Name| Type| Mandatory| Description| 1021| -------- | -------- | -------- | -------- | 1022| connection | number | Yes| ID of the connected ServiceExtensionAbility, that is, **connectionId** returned by [connectServiceExtensionAbility](#connectserviceextensionability).| 1023 1024**Return value** 1025 1026| Type| Description| 1027| -------- | -------- | 1028| Promise\<void> | Promise that returns no value.| 1029 1030**Error codes** 1031 1032For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 1033 1034| ID| Error Message| 1035| ------- | -------------------------------- | 1036| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 1037| 16000011 | The context does not exist. | 1038| 16000050 | Internal error. | 1039 1040**Example** 1041 1042```ts 1043import { UIAbility } from '@kit.AbilityKit'; 1044import { rpc } from '@kit.IPCKit'; 1045import { BusinessError } from '@kit.BasicServicesKit'; 1046 1047export default class EntryAbility extends UIAbility { 1048 onForeground() { 1049 // connection is the return value of connectServiceExtensionAbility. 1050 let connection = 1; 1051 let commRemote: rpc.IRemoteObject | null; 1052 1053 try { 1054 this.context.disconnectServiceExtensionAbility(connection).then(() => { 1055 commRemote = null; 1056 // Carry out normal service processing. 1057 console.info('disconnectServiceExtensionAbility succeed'); 1058 }).catch((err: BusinessError) => { 1059 // Process service logic errors. 1060 console.error(`disconnectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); 1061 }); 1062 } catch (err) { 1063 commRemote = null; 1064 // Process input parameter errors. 1065 let code = (err as BusinessError).code; 1066 let message = (err as BusinessError).message; 1067 console.error(`disconnectServiceExtensionAbility failed, code is ${code}, message is ${message}`); 1068 } 1069 } 1070} 1071``` 1072 1073### disconnectServiceExtensionAbility 1074 1075disconnectServiceExtensionAbility(connection: number, callback: AsyncCallback\<void>): void 1076 1077Disconnects from a [ServiceExtensionAbility](../../application-models/extensionability-overview.md). Once the connection is terminated, set the remote object, which is returned when the connection is established, to null. This API uses an asynchronous callback to return the result. It can be called only by the main thread. 1078 1079**System capability**: SystemCapability.Ability.AbilityRuntime.Core 1080 1081**Parameters** 1082 1083| Name| Type| Mandatory| Description| 1084| -------- | -------- | -------- | -------- | 1085| connection | number | Yes| ID of the connected ServiceExtensionAbility, that is, **connectionId** returned by [connectServiceExtensionAbility](#connectserviceextensionability).| 1086| callback | AsyncCallback\<void> | Yes| Callback used to return the result.| 1087 1088**Error codes** 1089 1090For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 1091 1092| ID| Error Message| 1093| ------- | -------------------------------- | 1094| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 1095| 16000011 | The context does not exist. | 1096| 16000050 | Internal error. | 1097 1098**Example** 1099 1100```ts 1101import { UIAbility } from '@kit.AbilityKit'; 1102import { rpc } from '@kit.IPCKit'; 1103import { BusinessError } from '@kit.BasicServicesKit'; 1104 1105export default class EntryAbility extends UIAbility { 1106 onForeground() { 1107 // connection is the return value of connectServiceExtensionAbility. 1108 let connection = 1; 1109 let commRemote: rpc.IRemoteObject | null; 1110 1111 try { 1112 this.context.disconnectServiceExtensionAbility(connection, (err: BusinessError) => { 1113 commRemote = null; 1114 if (err.code) { 1115 // Process service logic errors. 1116 console.error(`disconnectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); 1117 return; 1118 } 1119 // Carry out normal service processing. 1120 console.info('disconnectServiceExtensionAbility succeed'); 1121 }); 1122 } catch (err) { 1123 commRemote = null; 1124 // Process input parameter errors. 1125 let code = (err as BusinessError).code; 1126 let message = (err as BusinessError).message; 1127 console.error(`disconnectServiceExtensionAbility failed, code is ${code}, message is ${message}`); 1128 } 1129 } 1130} 1131``` 1132 1133### startAbilityByCall 1134 1135startAbilityByCall(want: Want): Promise<Caller> 1136 1137Obtains a [Caller](./js-apis-app-ability-uiAbility.md#caller) object for communicating with a [Callee](./js-apis-app-ability-uiAbility.md#callee) object. If the specified UIAbility is not started, the UIAbility will be started in the foreground or background. This API uses a promise to return the result. It can be called only by the main thread. 1138 1139This API cannot be used to start the UIAbility with the launch type set to [specified](../../application-models/uiability-launch-type.md#specified). 1140 1141> **NOTE** 1142> 1143> - For a successful launch in cross-device scenarios, the caller and target must be the same application and have the ohos.permission.DISTRIBUTED_DATASYNC permission. 1144> 1145> - For a successful launch in the same device scenario, the caller and target must be different applications and have the ohos.permission.ABILITY_BACKGROUND_COMMUNICATION permission (available only for system applications). 1146> 1147> - If the caller is running in the background, the ohos.permission.START_ABILITIES_FROM_BACKGROUND permission is required (available only for system applications). For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). 1148 1149**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC 1150 1151> **NOTE** 1152> 1153> In versions earlier than API version 11, this API requires the ohos.permission.ABILITY_BACKGROUND_COMMUNICATION permission, which is available only for system applications. Starting from API version 11, this API requires the ohos.permission.DISTRIBUTED_DATASYNC permission. 1154 1155**System capability**: SystemCapability.Ability.AbilityRuntime.Core 1156 1157**Parameters** 1158 1159| Name| Type| Mandatory| Description| 1160| -------- | -------- | -------- | -------- | 1161| want | [Want](js-apis-app-ability-want.md) | Yes| Information about the UIAbility to start, including the ability name, module name, bundle name, device ID, and parameters (optional). If **'ohos.aafwk.param.callAbilityToForeground'** in **parameters** is set to **true**, the UIAbility is brought to the foreground. Otherwise, the UIAbility is brought to the background.| 1162 1163**Return value** 1164 1165| Type| Description| 1166| -------- | -------- | 1167| Promise<[Caller](js-apis-app-ability-uiAbility.md#caller)> | Promise used to return the Caller object.| 1168 1169**Error codes** 1170 1171For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 1172 1173| ID| Error Message| 1174| ------- | -------------------------------- | 1175| 201 | The application does not have permission to call the interface. | 1176| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 1177| 16000001 | The specified ability does not exist. | 1178| 16000002 | Incorrect ability type. | 1179| 16000004 | Cannot start an invisible component. | 1180| 16000006 | Cross-user operations are not allowed. | 1181| 16000008 | The crowdtesting application expires. | 1182| 16000011 | The context does not exist. | 1183| 16000012 | The application is controlled. | 1184| 16000013 | The application is controlled by EDM. | 1185| 16000018 | Redirection to a third-party application is not allowed in API version greater than 11. | 1186| 16000050 | Internal error. | 1187| 16000071 | App clone is not supported. | 1188| 16000072 | App clone or multi-instance is not supported. | 1189| 16000073 | The app clone index is invalid. | 1190| 16000076 | The app instance key is invalid. | 1191| 16000077 | The number of app instances reaches the limit. | 1192| 16000078 | The multi-instance is not supported. | 1193| 16000079 | The APP_INSTANCE_KEY cannot be specified. | 1194| 16000080 | Creating a new instance is not supported. | 1195 1196**Example** 1197 1198Start an ability in the background. 1199 1200```ts 1201import { UIAbility, Caller, Want } from '@kit.AbilityKit'; 1202import { BusinessError } from '@kit.BasicServicesKit'; 1203 1204export default class EntryAbility extends UIAbility { 1205 onForeground() { 1206 let caller: Caller; 1207 // Start an ability in the background by not passing parameters. 1208 let wantBackground: Want = { 1209 bundleName: 'com.example.myapplication', 1210 moduleName: 'entry', 1211 abilityName: 'EntryAbility', 1212 deviceId: '' 1213 }; 1214 1215 try { 1216 this.context.startAbilityByCall(wantBackground) 1217 .then((obj: Caller) => { 1218 // Carry out normal service processing. 1219 caller = obj; 1220 console.info('startAbilityByCall succeed'); 1221 }).catch((err: BusinessError) => { 1222 // Process service logic errors. 1223 console.error(`startAbilityByCall failed, code is ${err.code}, message is ${err.message}`); 1224 }); 1225 } catch (err) { 1226 // Process input parameter errors. 1227 let code = (err as BusinessError).code; 1228 let message = (err as BusinessError).message; 1229 console.error(`startAbilityByCall failed, code is ${code}, message is ${message}`); 1230 } 1231 } 1232} 1233``` 1234 1235Start an ability in the foreground. 1236 1237```ts 1238import { UIAbility, Caller, Want } from '@kit.AbilityKit'; 1239import { BusinessError } from '@kit.BasicServicesKit'; 1240 1241export default class EntryAbility extends UIAbility { 1242 onForeground() { 1243 let caller: Caller; 1244 // Start an ability in the foreground with 'ohos.aafwk.param.callAbilityToForeground' in parameters set to true. 1245 let wantForeground: Want = { 1246 bundleName: 'com.example.myapplication', 1247 moduleName: 'entry', 1248 abilityName: 'EntryAbility', 1249 deviceId: '', 1250 parameters: { 1251 'ohos.aafwk.param.callAbilityToForeground': true 1252 } 1253 }; 1254 1255 try { 1256 this.context.startAbilityByCall(wantForeground) 1257 .then((obj: Caller) => { 1258 // Carry out normal service processing. 1259 caller = obj; 1260 console.info('startAbilityByCall succeed'); 1261 }).catch((err: BusinessError) => { 1262 // Process service logic errors. 1263 console.error(`startAbilityByCall failed, code is ${err.code}, message is ${err.message}`); 1264 }); 1265 } catch (err) { 1266 // Process input parameter errors. 1267 let code = (err as BusinessError).code; 1268 let message = (err as BusinessError).message; 1269 console.error(`startAbilityByCall failed, code is ${code}, message is ${message}`); 1270 } 1271 } 1272} 1273``` 1274 1275### setMissionLabel 1276 1277setMissionLabel(label: string, callback: AsyncCallback<void>): void 1278 1279Sets a mission label for this UIAbility on the multitasking screen. This API uses an asynchronous callback to return the result. 1280 1281**Atomic service API**: This API can be used in atomic services since API version 11. 1282 1283**System capability**: SystemCapability.Ability.AbilityRuntime.Core 1284 1285**Parameters** 1286 1287| Name| Type| Mandatory| Description| 1288| -------- | -------- | -------- | -------- | 1289| label | string | Yes| Mission label.| 1290| callback | AsyncCallback<void> | Yes| Callback used to return the result.| 1291 1292**Error codes** 1293 1294For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 1295 1296| ID| Error Message| 1297| ------- | -------------------------------- | 1298| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 1299| 16000011 | The context does not exist. | 1300| 16000050 | Internal error. | 1301 1302**Example** 1303 1304```ts 1305import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit'; 1306import { BusinessError } from '@kit.BasicServicesKit'; 1307 1308export default class EntryAbility extends UIAbility { 1309 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 1310 this.context.setMissionLabel('test', (result: BusinessError) => { 1311 console.info(`setMissionLabel: ${JSON.stringify(result)}`); 1312 }); 1313 } 1314} 1315``` 1316 1317### setMissionLabel 1318 1319setMissionLabel(label: string): Promise<void> 1320 1321Sets a mission label for this UIAbility on the multitasking screen. This API uses a promise to return the result. 1322 1323**Atomic service API**: This API can be used in atomic services since API version 11. 1324 1325**System capability**: SystemCapability.Ability.AbilityRuntime.Core 1326 1327**Parameters** 1328 1329| Name| Type| Mandatory| Description| 1330| -------- | -------- | -------- | -------- | 1331| label | string | Yes| Mission label.| 1332 1333**Return value** 1334 1335| Type| Description| 1336| -------- | -------- | 1337| Promise<void> | Promise that returns no value.| 1338 1339**Error codes** 1340 1341For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 1342 1343| ID| Error Message| 1344| ------- | -------------------------------- | 1345| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 1346| 16000011 | The context does not exist. | 1347| 16000050 | Internal error. | 1348 1349**Example** 1350 1351```ts 1352import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit'; 1353import { BusinessError } from '@kit.BasicServicesKit'; 1354 1355export default class EntryAbility extends UIAbility { 1356 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 1357 this.context.setMissionLabel('test').then(() => { 1358 console.info('success'); 1359 }).catch((err: BusinessError) => { 1360 let code = (err as BusinessError).code; 1361 let message = (err as BusinessError).message; 1362 console.error(`setMissionLabel failed, code is ${code}, message is ${message}`); 1363 }); 1364 } 1365} 1366``` 1367 1368### setMissionContinueState<sup>10+</sup> 1369 1370setMissionContinueState(state: AbilityConstant.ContinueState, callback: AsyncCallback<void>): void 1371 1372Sets the mission continuation state of this UIAbility. This API uses an asynchronous callback to return the result. 1373 1374**Atomic service API**: This API can be used in atomic services since API version 11. 1375 1376**System capability**: SystemCapability.Ability.AbilityRuntime.Core 1377 1378**Parameters** 1379 1380| Name| Type| Mandatory| Description| 1381| -------- | -------- | -------- | -------- | 1382| state | [AbilityConstant.ContinueState](js-apis-app-ability-abilityConstant.md#continuestate10) | Yes| Mission continuation state.| 1383| callback | AsyncCallback<void> | Yes| Callback used to return the result.| 1384 1385**Error codes** 1386 1387For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 1388 1389| ID| Error Message| 1390| ------- | -------------------------------- | 1391| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 1392| 16000011 | The context does not exist. | 1393| 16000050 | Internal error. | 1394 1395**Example** 1396 1397```ts 1398import { UIAbility, AbilityConstant } from '@kit.AbilityKit'; 1399import { BusinessError } from '@kit.BasicServicesKit'; 1400 1401export default class EntryAbility extends UIAbility { 1402 onForeground() { 1403 this.context.setMissionContinueState(AbilityConstant.ContinueState.INACTIVE, (result: BusinessError) => { 1404 console.info(`setMissionContinueState: ${JSON.stringify(result)}`); 1405 }); 1406 } 1407} 1408``` 1409 1410### setMissionContinueState<sup>10+</sup> 1411 1412setMissionContinueState(state: AbilityConstant.ContinueState): Promise<void> 1413 1414Sets the mission continuation state of this UIAbility. This API uses a promise to return the result. 1415 1416**Atomic service API**: This API can be used in atomic services since API version 11. 1417 1418**System capability**: SystemCapability.Ability.AbilityRuntime.Core 1419 1420**Parameters** 1421 1422| Name| Type| Mandatory| Description| 1423| -------- | -------- | -------- | -------- | 1424| state | [AbilityConstant.ContinueState](js-apis-app-ability-abilityConstant.md#continuestate10) | Yes| Mission continuation state.| 1425 1426**Return value** 1427 1428| Type| Description| 1429| -------- | -------- | 1430| Promise<void> | Promise that returns no value.| 1431 1432**Error codes** 1433 1434For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 1435 1436| ID| Error Message| 1437| ------- | -------------------------------- | 1438| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 1439| 16000011 | The context does not exist. | 1440| 16000050 | Internal error. | 1441 1442**Example** 1443 1444```ts 1445import { UIAbility, AbilityConstant } from '@kit.AbilityKit'; 1446import { BusinessError } from '@kit.BasicServicesKit'; 1447 1448export default class EntryAbility extends UIAbility { 1449 onForeground() { 1450 this.context.setMissionContinueState(AbilityConstant.ContinueState.INACTIVE).then(() => { 1451 console.info('success'); 1452 }).catch((err: BusinessError) => { 1453 console.error(`setMissionContinueState failed, code is ${err.code}, message is ${err.message}`); 1454 }); 1455 } 1456} 1457``` 1458 1459### restoreWindowStage 1460 1461restoreWindowStage(localStorage: LocalStorage): void 1462 1463Restores the WindowStage data in the UIAbility. It can be called only by the main thread. 1464 1465**Atomic service API**: This API can be used in atomic services since API version 11. 1466 1467**System capability**: SystemCapability.Ability.AbilityRuntime.Core 1468 1469**Parameters** 1470 1471| Name| Type| Mandatory| Description| 1472| -------- | -------- | -------- | -------- | 1473| localStorage | LocalStorage | Yes| Storage used to store the restored window stage.| 1474 1475**Error codes** 1476 1477For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 1478 1479| ID| Error Message| 1480| ------- | -------------------------------- | 1481| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 1482| 16000011 | The context does not exist. | 1483| 16000050 | Internal error. | 1484 1485**Example** 1486 1487```ts 1488import { UIAbility } from '@kit.AbilityKit'; 1489 1490export default class EntryAbility extends UIAbility { 1491 onForeground() { 1492 let storage = new LocalStorage(); 1493 this.context.restoreWindowStage(storage); 1494 } 1495} 1496``` 1497 1498### isTerminating 1499 1500isTerminating(): boolean 1501 1502Checks whether this UIAbility is in the terminating state. 1503 1504**Atomic service API**: This API can be used in atomic services since API version 11. 1505 1506**System capability**: SystemCapability.Ability.AbilityRuntime.Core 1507 1508**Return value** 1509 1510| Type| Description| 1511| -------- | -------- | 1512| boolean | Check result for whether the UIAbility is in the terminating state. **true** if in the terminating state, **false** otherwise.| 1513 1514**Error codes** 1515 1516For details about the error codes, see [Ability Error Codes](errorcode-ability.md). 1517 1518| ID| Error Message| 1519| ------- | -------------------------------- | 1520| 16000011 | The context does not exist. | 1521 1522**Example** 1523 1524```ts 1525import { UIAbility } from '@kit.AbilityKit'; 1526 1527export default class EntryAbility extends UIAbility { 1528 onForeground() { 1529 let isTerminating: boolean = this.context.isTerminating(); 1530 console.info(`ability state is ${isTerminating}`); 1531 } 1532} 1533``` 1534 1535### requestDialogService 1536 1537requestDialogService(want: Want, result: AsyncCallback<dialogRequest.RequestResult>): void 1538 1539Starts a ServiceExtensionAbility that supports modal dialog boxes. After the ServiceExtensionAbility is started, the application displays a modal dialog box. You can call [setRequestResult](js-apis-app-ability-dialogRequest.md#requestcallbacksetrequestresult) to obtain the result. This API uses an asynchronous callback to return the result. It can be called only by the main thread. 1540 1541> **NOTE** 1542> 1543> For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). 1544 1545**System capability**: SystemCapability.Ability.AbilityRuntime.Core 1546 1547**Parameters** 1548 1549| Name| Type| Mandatory| Description| 1550| -------- | -------- | -------- | -------- | 1551| want |[Want](js-apis-app-ability-want.md) | Yes| Want information for starting the ServiceExtensionAbility.| 1552| result | AsyncCallback<[dialogRequest.RequestResult](js-apis-app-ability-dialogRequest.md#requestresult)> | Yes| Callback used to return the result.| 1553 1554**Error codes** 1555 1556For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 1557 1558| ID| Error Message| 1559| ------- | -------------------------------- | 1560| 201 | The application does not have permission to call the interface. | 1561| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 1562| 16000001 | The specified ability does not exist. | 1563| 16000002 | Incorrect ability type. | 1564| 16000004 | Cannot start an invisible component. | 1565| 16000005 | The specified process does not have the permission. | 1566| 16000006 | Cross-user operations are not allowed. | 1567| 16000008 | The crowdtesting application expires. | 1568| 16000009 | An ability cannot be started or stopped in Wukong mode. | 1569| 16000010 | The call with the continuation and prepare continuation flag is forbidden. | 1570| 16000011 | The context does not exist. | 1571| 16000012 | The application is controlled. | 1572| 16000013 | The application is controlled by EDM. | 1573| 16000050 | Internal error. | 1574| 16000053 | The ability is not on the top of the UI. | 1575| 16000055 | Installation-free timed out. | 1576| 16200001 | The caller has been released. | 1577 1578**Example** 1579 1580```ts 1581import { UIAbility, Want, dialogRequest } from '@kit.AbilityKit'; 1582import { BusinessError } from '@kit.BasicServicesKit'; 1583 1584export default class EntryAbility extends UIAbility { 1585 onForeground() { 1586 let want: Want = { 1587 deviceId: '', 1588 bundleName: 'com.example.myapplication', 1589 abilityName: 'AuthAccountServiceExtension' 1590 }; 1591 1592 try { 1593 this.context.requestDialogService(want, (err: BusinessError, result: dialogRequest.RequestResult) => { 1594 if (err.code) { 1595 // Process service logic errors. 1596 console.error(`requestDialogService failed, code is ${err.code}, message is ${err.message}`); 1597 return; 1598 } 1599 // Carry out normal service processing. 1600 console.info(`requestDialogService succeed, result = ${JSON.stringify(result)}`); 1601 }); 1602 } catch (err) { 1603 // Process input parameter errors. 1604 let code = (err as BusinessError).code; 1605 let message = (err as BusinessError).message; 1606 console.error(`requestDialogService failed, code is ${code}, message is ${message}`); 1607 } 1608 } 1609} 1610``` 1611 1612### requestDialogService 1613 1614requestDialogService(want: Want): Promise<dialogRequest.RequestResult> 1615 1616Starts a ServiceExtensionAbility that supports modal dialog boxes. After the ServiceExtensionAbility is started, the application displays a modal dialog box. You can call [setRequestResult](js-apis-app-ability-dialogRequest.md#requestcallbacksetrequestresult) to obtain the result. This API uses a promise to return the result. It can be called only by the main thread. 1617 1618> **NOTE** 1619> 1620> For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). 1621 1622**System capability**: SystemCapability.Ability.AbilityRuntime.Core 1623 1624**Parameters** 1625 1626| Name| Type| Mandatory| Description| 1627| -------- | -------- | -------- | -------- | 1628| want | [Want](js-apis-app-ability-want.md) | Yes| Want information for starting the ServiceExtensionAbility.| 1629 1630 1631**Return value** 1632 1633| Type| Description| 1634| -------- | -------- | 1635| Promise<[dialogRequest.RequestResult](js-apis-app-ability-dialogRequest.md#requestresult)> | Promise that returns no value.| 1636 1637**Error codes** 1638 1639For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 1640 1641| ID| Error Message| 1642| ------- | -------------------------------- | 1643| 201 | The application does not have permission to call the interface. | 1644| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 1645| 16000001 | The specified ability does not exist. | 1646| 16000002 | Incorrect ability type. | 1647| 16000004 | Cannot start an invisible component. | 1648| 16000005 | The specified process does not have the permission. | 1649| 16000006 | Cross-user operations are not allowed. | 1650| 16000008 | The crowdtesting application expires. | 1651| 16000009 | An ability cannot be started or stopped in Wukong mode. | 1652| 16000010 | The call with the continuation and prepare continuation flag is forbidden. | 1653| 16000011 | The context does not exist. | 1654| 16000012 | The application is controlled. | 1655| 16000013 | The application is controlled by EDM. | 1656| 16000050 | Internal error. | 1657| 16000053 | The ability is not on the top of the UI. | 1658| 16000055 | Installation-free timed out. | 1659| 16200001 | The caller has been released. | 1660 1661**Example** 1662 1663```ts 1664import { UIAbility, Want, dialogRequest } from '@kit.AbilityKit'; 1665import { BusinessError } from '@kit.BasicServicesKit'; 1666 1667export default class EntryAbility extends UIAbility { 1668 onForeground() { 1669 let want: Want = { 1670 bundleName: 'com.example.myapplication', 1671 abilityName: 'AuthAccountServiceExtension' 1672 }; 1673 1674 try { 1675 this.context.requestDialogService(want) 1676 .then((result: dialogRequest.RequestResult) => { 1677 // Carry out normal service processing. 1678 console.info(`requestDialogService succeed, result = ${JSON.stringify(result)}`); 1679 }) 1680 .catch((err: BusinessError) => { 1681 // Process service logic errors. 1682 console.error(`requestDialogService failed, code is ${err.code}, message is ${err.message}`); 1683 }); 1684 } catch (err) { 1685 // Process input parameter errors. 1686 let code = (err as BusinessError).code; 1687 let message = (err as BusinessError).message; 1688 console.error(`requestDialogService failed, code is ${code}, message is ${message}`); 1689 } 1690 } 1691} 1692``` 1693 1694### reportDrawnCompleted<sup>10+</sup> 1695 1696reportDrawnCompleted(callback: AsyncCallback\<void>): void 1697 1698Called when the window content associated with the UIAbility finishes drawing. This API uses an asynchronous callback to return the result. 1699 1700**Atomic service API**: This API can be used in atomic services since API version 11. 1701 1702**System capability**: SystemCapability.Ability.AbilityRuntime.Core 1703 1704**Parameters** 1705 1706| Name| Type| Mandatory| Description| 1707| -------- | -------- | -------- | -------- | 1708| callback | AsyncCallback<void> | Yes| Callback used to return the result.| 1709 1710**Error codes** 1711 1712For details about the error codes, see [Ability Error Codes](errorcode-ability.md). 1713 1714| ID| Error Message| 1715| ------- | -------------------------------- | 1716| 16000011 | The context does not exist. | 1717| 16000050 | Internal error. | 1718 1719**Example** 1720 1721```ts 1722import { UIAbility } from '@kit.AbilityKit'; 1723import { window } from '@kit.ArkUI'; 1724import { BusinessError } from '@kit.BasicServicesKit'; 1725 1726export default class EntryAbility extends UIAbility { 1727 onWindowStageCreate(windowStage: window.WindowStage) { 1728 windowStage.loadContent('pages/Index', (err, data) => { 1729 if (err.code) { 1730 return; 1731 } 1732 1733 try { 1734 this.context.reportDrawnCompleted((err) => { 1735 if (err.code) { 1736 // Process service logic errors. 1737 console.error(`reportDrawnCompleted failed, code is ${err.code}, message is ${err.message}`); 1738 return; 1739 } 1740 // Carry out normal service processing. 1741 console.info('reportDrawnCompleted succeed'); 1742 }); 1743 } catch (err) { 1744 // Capture the synchronization parameter error. 1745 let code = (err as BusinessError).code; 1746 let message = (err as BusinessError).message; 1747 console.error(`reportDrawnCompleted failed, code is ${code}, message is ${message}`); 1748 } 1749 }); 1750 console.info("MainAbility onWindowStageCreate"); 1751 } 1752}; 1753``` 1754 1755### startAbilityByType<sup>11+</sup> 1756 1757startAbilityByType(type: string, wantParam: Record<string, Object>, 1758 abilityStartCallback: AbilityStartCallback, callback: AsyncCallback\<void>) : void 1759 1760Implicitly starts a given type of UIExtensionAbility. This API uses an asynchronous callback to return the result. It can be called only in the main thread and by applications running in the foreground. 1761 1762**Atomic service API**: This API can be used in atomic services since API version 11. 1763 1764**System capability**: SystemCapability.Ability.AbilityRuntime.Core 1765 1766**Parameters** 1767 1768| Name| Type| Mandatory| Description| 1769| -------- | -------- | -------- | -------- | 1770| type | string | Yes| Type of the UIExtensionAbility to start. For details, see [Starting an Application of the Specified Type](../../application-models/start-intent-panel.md#matching-rules).| 1771| wantParam | Record<string, Object> | Yes| Extended parameter.| 1772| abilityStartCallback | [AbilityStartCallback](js-apis-inner-application-abilityStartCallback.md) | Yes| Callback used to return the detailed error information if the startup fails.| 1773| callback | AsyncCallback<void> | Yes| Callback used to return the result.| 1774 1775**Error codes** 1776 1777For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 1778 1779| ID| Error Message| 1780| ------- | -------------------------------- | 1781| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 1782| 16000050 | Internal error. | 1783 1784**Example** 1785 1786```ts 1787import { UIAbility, common } from '@kit.AbilityKit'; 1788 1789export default class EntryAbility extends UIAbility { 1790 onForeground() { 1791 let wantParam: Record<string, Object> = { 1792 'time': '2023-10-23 20:45' 1793 }; 1794 let abilityStartCallback: common.AbilityStartCallback = { 1795 onError: (code: number, name: string, message: string) => { 1796 console.info(`code:` + code + `name:` + name + `message:` + message); 1797 }, 1798 onResult: (abilityResult: common.AbilityResult) => { 1799 console.info(`resultCode:` + abilityResult.resultCode + `bundleName:` + abilityResult.want?.bundleName); 1800 } 1801 }; 1802 1803 this.context.startAbilityByType("photoEditor", wantParam, abilityStartCallback, (err) => { 1804 if (err) { 1805 console.error(`startAbilityByType fail, err: ${JSON.stringify(err)}`); 1806 } else { 1807 console.info(`success`); 1808 } 1809 }); 1810 } 1811} 1812``` 1813 1814### startAbilityByType<sup>11+</sup> 1815 1816startAbilityByType(type: string, wantParam: Record<string, Object>, 1817 abilityStartCallback: AbilityStartCallback) : Promise\<void> 1818 1819Implicitly starts a given type of UIExtensionAbility. This API uses a promise to return the result. It can be called only in the main thread and by applications running in the foreground. 1820 1821**Atomic service API**: This API can be used in atomic services since API version 11. 1822 1823**System capability**: SystemCapability.Ability.AbilityRuntime.Core 1824 1825**Parameters** 1826 1827| Name| Type| Mandatory| Description| 1828| -------- | -------- | -------- | -------- | 1829| type | string | Yes| Type of the UIExtensionAbility to start. For details, see [Starting an Application of the Specified Type](../../application-models/start-intent-panel.md#matching-rules).| 1830| wantParam | Record<string, Object> | Yes| Extended parameter.| 1831| abilityStartCallback | [AbilityStartCallback](js-apis-inner-application-abilityStartCallback.md) | Yes| Callback used to return the detailed error information if the startup fails.| 1832 1833**Return value** 1834 1835| Type| Description| 1836| -------- | -------- | 1837| Promise<void> | Promise that returns no value.| 1838 1839**Error codes** 1840 1841For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 1842 1843| ID| Error Message| 1844| ------- | -------------------------------- | 1845| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 1846| 16000050 | Internal error. | 1847 1848**Example** 1849 1850```ts 1851import { UIAbility, common } from '@kit.AbilityKit'; 1852import { BusinessError } from '@kit.BasicServicesKit'; 1853 1854export default class EntryAbility extends UIAbility { 1855 onForeground() { 1856 let wantParam: Record<string, Object> = { 1857 'time': '2023-10-23 20:45' 1858 }; 1859 let abilityStartCallback: common.AbilityStartCallback = { 1860 onError: (code: number, name: string, message: string) => { 1861 console.info(`code:` + code + `name:` + name + `message:` + message); 1862 }, 1863 onResult: (abilityResult: common.AbilityResult) => { 1864 console.info(`resultCode:` + abilityResult.resultCode + `bundleName:` + abilityResult.want?.bundleName); 1865 } 1866 }; 1867 1868 this.context.startAbilityByType("photoEditor", wantParam, abilityStartCallback).then(() => { 1869 console.info(`startAbilityByType success`); 1870 }).catch((err: BusinessError) => { 1871 console.error(`startAbilityByType fail, err: ${JSON.stringify(err)}`); 1872 }); 1873 } 1874} 1875``` 1876 1877### showAbility<sup>12+</sup> 1878 1879showAbility(): Promise\<void> 1880 1881Shows this UIAbility. This API uses a promise to return the result. It can be called only by the main thread. 1882 1883Before calling this API, ensure that the application has been added to the status bar. 1884 1885**System capability**: SystemCapability.Ability.AbilityRuntime.Core 1886 1887**Device behavior differences**: This API can be properly called only on 2-in-1 devices and tablets. If it is called on other device types, error code 801 is returned. 1888 1889**Return value** 1890 1891| Type| Description| 1892| -------- | -------- | 1893| Promise<void> | Promise that returns no value.| 1894 1895**Error codes** 1896 1897For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 1898 1899| ID| Error Message| 1900| ------- | -------------------------------- | 1901| 801 | Capability not support. | 1902| 16000050 | Internal error. | 1903| 16000067 | The StartOptions check failed. | 1904 1905**Example** 1906 1907```ts 1908// Index.ets 1909import { common } from '@kit.AbilityKit'; 1910import { BusinessError } from '@kit.BasicServicesKit'; 1911 1912@Entry 1913@Component 1914struct Index { 1915 @State showAbility: string = 'showAbility' 1916 1917 build() { 1918 Row() { 1919 Column() { 1920 Text(this.showAbility) 1921 .fontSize(30) 1922 .fontWeight(FontWeight.Bold) 1923 .onClick(() => { 1924 let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 1925 1926 context.showAbility().then(() => { 1927 console.info(`showAbility success`); 1928 }).catch((err: BusinessError) => { 1929 console.error(`showAbility fail, err: ${JSON.stringify(err)}`); 1930 }); 1931 }); 1932 } 1933 .width('100%') 1934 } 1935 .height('100%') 1936 } 1937} 1938``` 1939```ts 1940// EntryAbility.ts 1941import { UIAbility, Want, StartOptions, contextConstant } from '@kit.AbilityKit'; 1942import { BusinessError } from '@kit.BasicServicesKit'; 1943 1944export default class EntryAbility extends UIAbility { 1945 onForeground() { 1946 let want: Want = { 1947 deviceId: '', 1948 bundleName: 'com.example.myapplication', 1949 abilityName: 'EntryAbility' 1950 }; 1951 let options: StartOptions = { 1952 displayId: 0, 1953 processMode: contextConstant.ProcessMode.NEW_PROCESS_ATTACH_TO_STATUS_BAR_ITEM, 1954 startupVisibility: contextConstant.StartupVisibility.STARTUP_SHOW 1955 }; 1956 1957 try { 1958 this.context.startAbility(want, options, (err: BusinessError) => { 1959 if (err.code) { 1960 // Process service logic errors. 1961 console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); 1962 return; 1963 } 1964 // Carry out normal service processing. 1965 console.info('startAbility succeed'); 1966 }); 1967 } catch (err) { 1968 // Process input parameter errors. 1969 let code = (err as BusinessError).code; 1970 let message = (err as BusinessError).message; 1971 console.error(`startAbility failed, code is ${code}, message is ${message}`); 1972 } 1973 } 1974} 1975``` 1976 1977### hideAbility<sup>12+</sup> 1978 1979hideAbility(): Promise\<void> 1980 1981Hides this UIAbility. This API uses a promise to return the result. It can be called only by the main thread. 1982 1983Before calling this API, ensure that the application has been added to the status bar. 1984 1985**System capability**: SystemCapability.Ability.AbilityRuntime.Core 1986 1987**Device behavior differences**: This API can be properly called only on 2-in-1 devices and tablets. If it is called on other device types, error code 801 is returned. 1988 1989**Return value** 1990 1991| Type| Description| 1992| -------- | -------- | 1993| Promise<void> | Promise that returns no value.| 1994 1995**Error codes** 1996 1997For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 1998 1999| ID| Error Message| 2000| ------- | -------------------------------- | 2001| 801 | Capability not support. | 2002| 16000050 | Internal error. | 2003| 16000067 | The StartOptions check failed. | 2004 2005**Example** 2006 2007```ts 2008// Index.ets 2009import { common } from '@kit.AbilityKit'; 2010import { BusinessError } from '@kit.BasicServicesKit'; 2011 2012@Entry 2013@Component 2014struct Index { 2015 @State hideAbility: string = 'hideAbility' 2016 2017 build() { 2018 Row() { 2019 Column() { 2020 Text(this.hideAbility) 2021 .fontSize(30) 2022 .fontWeight(FontWeight.Bold) 2023 .onClick(() => { 2024 let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 2025 2026 context.hideAbility().then(() => { 2027 console.info(`hideAbility success`); 2028 }).catch((err: BusinessError) => { 2029 console.error(`hideAbility fail, err: ${JSON.stringify(err)}`); 2030 }); 2031 }); 2032 } 2033 .width('100%') 2034 } 2035 .height('100%') 2036 } 2037} 2038``` 2039```ts 2040// EntryAbility.ts 2041import { UIAbility, Want, StartOptions, contextConstant } from '@kit.AbilityKit'; 2042import { BusinessError } from '@kit.BasicServicesKit'; 2043 2044export default class EntryAbility extends UIAbility { 2045 onForeground() { 2046 let want: Want = { 2047 deviceId: '', 2048 bundleName: 'com.example.myapplication', 2049 abilityName: 'EntryAbility' 2050 }; 2051 let options: StartOptions = { 2052 displayId: 0, 2053 processMode: contextConstant.ProcessMode.NEW_PROCESS_ATTACH_TO_STATUS_BAR_ITEM, 2054 startupVisibility: contextConstant.StartupVisibility.STARTUP_HIDE 2055 }; 2056 2057 try { 2058 this.context.startAbility(want, options, (err: BusinessError) => { 2059 if (err.code) { 2060 // Process service logic errors. 2061 console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); 2062 return; 2063 } 2064 // Carry out normal service processing. 2065 console.info('startAbility succeed'); 2066 }); 2067 } catch (err) { 2068 // Process input parameter errors. 2069 let code = (err as BusinessError).code; 2070 let message = (err as BusinessError).message; 2071 console.error(`startAbility failed, code is ${code}, message is ${message}`); 2072 } 2073 } 2074} 2075``` 2076 2077### moveAbilityToBackground<sup>12+<sup> 2078 2079moveAbilityToBackground(): Promise\<void> 2080 2081Moves this UIAbility from the foreground to the background. This API uses a promise to return the result. It can be called only by the main thread.<br><!--RP1--><!--RP1End--> 2082 2083**Atomic service API**: This API can be used in atomic services since API version 12. 2084 2085**System capability**: SystemCapability.Ability.AbilityRuntime.Core 2086 2087 2088**Return value** 2089 2090| Type| Description| 2091| -------- | -------- | 2092| Promise<void> | Promise that returns no value.| 2093 2094**Error codes** 2095 2096For details about the error codes, see [Ability Error Codes](errorcode-ability.md). 2097 2098| ID| Error Message| 2099| ------- | -------------------------------- | 2100| 16000011 | The context does not exist. | 2101| 16000050 | Internal error. | 2102| 16000061 | Operation not supported. | 2103| 16000065 | The API can be called only when the ability is running in the foreground. | 2104| 16000066 | An ability cannot switch to the foreground or background in Wukong mode. | 2105 2106**Example** 2107 2108```ts 2109import { common } from '@kit.AbilityKit'; 2110import { BusinessError } from '@kit.BasicServicesKit'; 2111 2112@Entry 2113@Component 2114struct Index { 2115 @State moveAbilityToBackground: string = 'Move To Background' 2116 2117 build() { 2118 Row() { 2119 Column() { 2120 Text(this.moveAbilityToBackground) 2121 .fontSize(30) 2122 .fontWeight(FontWeight.Bold) 2123 .onClick(() => { 2124 let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 2125 2126 context.moveAbilityToBackground().then(() => { 2127 console.info(`moveAbilityToBackground success.`); 2128 }).catch((err: BusinessError) => { 2129 console.info(`moveAbilityToBackground error: ${JSON.stringify(err)}.`); 2130 }); 2131 }); 2132 } 2133 .width('100%') 2134 } 2135 .height('100%') 2136 } 2137} 2138``` 2139 2140### openAtomicService<sup>12+<sup> 2141 2142openAtomicService(appId: string, options?: AtomicServiceOptions): Promise<AbilityResult> 2143 2144Opens an atomic service in an independent window and returns the result. This API uses a promise to return the result. It can be called only by the main thread. 2145 2146After an atomic service is started, the following situations may occur: 2147 - Normally, you can call [terminateSelfWithResult](#terminateselfwithresult) to terminate the atomic service. The result is returned to the caller. 2148 - If an exception occurs, for example, the atomic service is killed, an error message, in which **resultCode** is **-1**, is returned to the caller. 2149 - If different applications call this API to start an atomic service and then call [terminateSelfWithResult](#terminateselfwithresult) to terminate the atomic service, the normal result is returned to the last caller, and an exception message, in which **resultCode** is **-1**, is returned to others. 2150 2151> **NOTE** 2152> 2153> For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). 2154 2155**Atomic service API**: This API can be used in atomic services since API version 12. 2156 2157**System capability**: SystemCapability.Ability.AbilityRuntime.Core 2158 2159**Parameters** 2160 2161| Name| Type| Mandatory| Description| 2162| -------- | -------- | -------- | -------- | 2163| appId | string | Yes| Unique ID of the application, which is allocated by the cloud.| 2164| options | [AtomicServiceOptions](js-apis-app-ability-atomicServiceOptions.md) | No| Parameter carried in the request for starting the atomic service.| 2165 2166 2167**Return value** 2168 2169| Type| Description| 2170| -------- | -------- | 2171| Promise<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Promise used to return the result.| 2172 2173**Error codes** 2174 2175For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 2176 2177| ID| Error Message| 2178| ------- | -------------------------------- | 2179| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 2180| 16000002 | Incorrect ability type. | 2181| 16000003 | The specified ID does not exist. | 2182| 16000004 | Cannot start an invisible component. | 2183| 16000011 | The context does not exist. | 2184| 16000012 | The application is controlled. | 2185| 16000050 | Internal error. | 2186| 16000053 | The ability is not on the top of the UI. | 2187| 16000055 | Installation-free timed out. | 2188| 16200001 | The caller has been released. | 2189 2190**Example** 2191 2192```ts 2193import { UIAbility, common, AtomicServiceOptions } from '@kit.AbilityKit'; 2194import { BusinessError } from '@kit.BasicServicesKit'; 2195 2196export default class EntryAbility extends UIAbility { 2197 onForeground() { 2198 let appId: string = '6918661953712445909'; 2199 let options: AtomicServiceOptions = { 2200 displayId: 0 2201 }; 2202 2203 try { 2204 this.context.openAtomicService(appId, options) 2205 .then((result: common.AbilityResult) => { 2206 // Carry out normal service processing. 2207 console.info('openAtomicService succeed'); 2208 }) 2209 .catch((err: BusinessError) => { 2210 // Process service logic errors. 2211 console.error(`openAtomicService failed, code is ${err.code}, message is ${err.message}`); 2212 }); 2213 } catch (err) { 2214 // Process input parameter errors. 2215 let code = (err as BusinessError).code; 2216 let message = (err as BusinessError).message; 2217 console.error(`openAtomicService failed, code is ${code}, message is ${message}`); 2218 } 2219 } 2220} 2221``` 2222 2223### openLink<sup>12+<sup> 2224 2225openLink(link: string, options?: OpenLinkOptions, callback?: AsyncCallback<AbilityResult>): Promise<void> 2226 2227Starts a UIAbility by using <!--RP2-->[App Linking](../../application-models/app-linking-startup.md)<!--RP2End--> or [Deep Linking](../../application-models/deep-linking-startup.md), and returns the exit result of the launched UIAbility via a callback. This API uses a promise to return the result. It can be called only by the main thread. 2228 2229A URL in the standard format is passed in to the **link** field to start the target UIAbility based on the implicit Want matching rules. The target UIAbility must have the following filter characteristics to process links of App Linking: 2230- The **actions** field contains **ohos.want.action.viewData**. 2231- The **entities** field contains **entity.system.browsable**. 2232- The **uris** field contains elements whose **scheme** is **https** and **domainVerify** is **true**. 2233 2234If you want to obtain the result after the started UIAbility is terminated, set the **callback** parameter. For details about how to use this parameter, see [startAbilityForResult](#startabilityforresult). 2235If an input parameter is invalid, for example, a mandatory parameter is not set or the URL set in **link** is not in the standard format, an exception is thrown. If the parameter verification is successful but an error occurs when starting the target UIAbility, the error information is returned through promise. 2236 2237> **NOTE** 2238> 2239> For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). 2240 2241**Atomic service API**: This API can be used in atomic services since API version 12. 2242 2243**System capability**: SystemCapability.Ability.AbilityRuntime.Core 2244 2245**Parameters** 2246 2247| Name| Type| Mandatory| Description| 2248| -------- | -------- | -------- | -------- | 2249| link | string | Yes| URL to open, which must be in the standard format.| 2250| options | [OpenLinkOptions](js-apis-app-ability-openLinkOptions.md) | No| Options of the URL.| 2251| callback | AsyncCallback<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | No| Callback used to return the result.| 2252 2253**Return value** 2254 2255| Type| Description| 2256| -------- | -------- | 2257| Promise<void> | Promise that returns no value.| 2258 2259**Error codes** 2260 2261For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 2262 2263| ID| Error Message| 2264| ------- | -------------------------------- | 2265| 201 | The application does not have permission to call the interface. | 2266| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 2267| 16000001 | The specified ability does not exist. | 2268| 16000002 | Incorrect ability type. | 2269| 16000004 | Cannot start an invisible component. | 2270| 16000005 | The specified process does not have the permission. | 2271| 16000006 | Cross-user operations are not allowed. | 2272| 16000008 | The crowdtesting application expires. | 2273| 16000009 | An ability cannot be started or stopped in Wukong mode. | 2274| 16000010 | The call with the continuation and prepare continuation flag is forbidden. | 2275| 16000011 | The context does not exist. | 2276| 16000012 | The application is controlled. | 2277| 16000013 | The application is controlled by EDM. | 2278| 16000019 | No matching ability is found. | 2279| 16200001 | The caller has been released. | 2280| 16000053 | The ability is not on the top of the UI. | 2281 2282**Example** 2283 2284```ts 2285import { common, OpenLinkOptions } from '@kit.AbilityKit'; 2286import { hilog } from '@kit.PerformanceAnalysisKit'; 2287import { BusinessError } from '@kit.BasicServicesKit'; 2288 2289const DOMAIN = 0xeeee; 2290const TAG: string = '[openLinkDemo]'; 2291 2292@Entry 2293@Component 2294struct Index { 2295 build() { 2296 RelativeContainer() { 2297 Button("Call StartAbilityForResult") 2298 .onClick(() => { 2299 let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 2300 let link: string = 'https://www.example.com'; 2301 let openLinkOptions: OpenLinkOptions = { 2302 appLinkingOnly: true, 2303 parameters: { demo_key: 'demo_value' } 2304 }; 2305 2306 try { 2307 context.openLink( 2308 link, 2309 openLinkOptions, 2310 (err, result) => { 2311 hilog.error(DOMAIN, TAG, `openLink callback error.code: ${JSON.stringify(err)}`); 2312 hilog.info(DOMAIN, TAG, `openLink callback result: ${JSON.stringify(result.resultCode)}`); 2313 hilog.info(DOMAIN, TAG, `openLink callback result data: ${JSON.stringify(result.want)}`); 2314 } 2315 ).then(() => { 2316 hilog.info(DOMAIN, TAG, `open link success.`); 2317 }).catch((err: BusinessError) => { 2318 hilog.error(DOMAIN, TAG, `open link failed, errCode ${JSON.stringify(err.code)}`); 2319 }); 2320 } 2321 catch (e) { 2322 hilog.error(DOMAIN, TAG, `exception occured, errCode ${JSON.stringify(e.code)}`); 2323 } 2324 }) 2325 } 2326 .height('100%') 2327 .width('100%') 2328 } 2329} 2330``` 2331 2332### backToCallerAbilityWithResult<sup>12+<sup> 2333 2334backToCallerAbilityWithResult(abilityResult: AbilityResult, requestCode: string): Promise<void> 2335 2336Returns the startup result to the caller of [startAbilityForResult](#startabilityforresult) or [openLink](#openlink12). Different from [terminateSelfWithResult](#terminateselfwithresult), this API does not destroy the current UIAbility when it returns the result. This API uses a promise to return the result. 2337 2338**Atomic service API**: This API can be used in atomic services since API version 12. 2339 2340**System capability**: SystemCapability.Ability.AbilityRuntime.Core 2341 2342**Parameters** 2343 2344| Name| Type| Mandatory| Description| 2345| -------- | -------- | -------- | -------- | 2346| abilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes| Result returned to the caller.| 2347| requestCode | string | Yes| Request code generated by the system when the target ability is started using [startAbilityForResult](#startabilityforresult) or [openLink](#openlink12). The value can be obtained from the [CALLER_REQUEST_CODE](js-apis-app-ability-wantConstant.md) field in **want**.| 2348 2349**Return value** 2350 2351| Type| Description| 2352| -------- | -------- | 2353| Promise<void> | Promise that returns no value.| 2354 2355**Error codes** 2356 2357For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 2358 2359| ID| Error Message| 2360| ------- | -------------------------------- | 2361| 201 | The application does not have permission to call the interface. | 2362| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 2363| 16000009 | An ability cannot be started or stopped in Wukong mode. | 2364| 16000011 | The context does not exist. | 2365| 16000050 | Internal error. | 2366| 16000074 | The caller does not exist. | 2367| 16000075 | BackToCaller is not supported. | 2368 2369**Example** 2370The caller uses **startAbilityForResult** to start an ability, and the target ability calls **backToCallerAbilityWithResult** to return the result to the caller. 2371 2372```ts 2373// Caller 2374// index.ets 2375import { common, Want } from '@kit.AbilityKit'; 2376import { BusinessError } from '@ohos.base'; 2377import { hilog } from '@kit.PerformanceAnalysisKit'; 2378 2379@Entry 2380@Component 2381struct Index { 2382 @State message: string = 'Hello World'; 2383 2384 build() { 2385 Row() { 2386 Column() { 2387 Text(this.message) 2388 .fontSize(30) 2389 .fontWeight(FontWeight.Bold) 2390 2391 Button("Call StartAbilityForResult") 2392 .onClick(() => { 2393 let context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext; 2394 let want: Want = { 2395 bundleName: 'com.example.demo2', 2396 abilityName: 'EntryAbility' 2397 }; 2398 2399 try { 2400 // Use startAbilityForResult to start the target ability. 2401 context.startAbilityForResult(want, (err: BusinessError, result: common.AbilityResult) => { 2402 if (err.code) { 2403 // Process service logic errors. 2404 hilog.error(0x0000, 'testTag', `startAbilityForResult failed, code is ${err.code}, message is ${err.message}`); 2405 this.message = `startAbilityForResult failed: code is ${err.code}, message is ${err.message}` 2406 return; 2407 } 2408 // Carry out normal service processing. 2409 hilog.info(0x0000, 'testTag', `startAbilityForResult succeed`); 2410 hilog.info(0x0000, 'testTag', `AbilityResult is ${JSON.stringify(result)}`); 2411 this.message = `AbilityResult.resultCode: ${JSON.stringify(result.resultCode)}` 2412 }); 2413 } catch (err) { 2414 // Process input parameter errors. 2415 let code = (err as BusinessError).code; 2416 let message = (err as BusinessError).message; 2417 hilog.error(0x0000, 'testTag', `startAbilityForResult failed, code is ${code}, message is ${message}`); 2418 this.message = `startAbilityForResult failed, code is ${code}, message is ${message}`; 2419 } 2420 }) 2421 } 2422 .width('100%') 2423 } 2424 .height('100%') 2425 } 2426} 2427``` 2428 2429```ts 2430// Target ability 2431// EntryAbility.ets 2432import { AbilityConstant, common, UIAbility, Want, wantConstant } from '@kit.AbilityKit'; 2433import { hilog } from '@kit.PerformanceAnalysisKit'; 2434import { BusinessError } from '@kit.BasicServicesKit'; 2435 2436export default class EntryAbility extends UIAbility { 2437 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 2438 // Obtain the CALLER_REQUEST_CODE of the caller from want and save it. 2439 let callerRequestCode: string = want?.parameters?.[wantConstant.Params.CALLER_REQUEST_CODE] as string; 2440 AppStorage.setOrCreate<string>("callerRequestCode", callerRequestCode) 2441 } 2442 2443 onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void { 2444 let callerRequestCode: string = want?.parameters?.[wantConstant.Params.CALLER_REQUEST_CODE] as string; 2445 AppStorage.setOrCreate<string>("callerRequestCode", callerRequestCode) 2446 } 2447 2448 onForeground(): void { 2449 // Obtain the saved CALLER_REQUEST_CODE. 2450 let callerRequestCode: string = AppStorage.get<string>("callerRequestCode") as string; 2451 hilog.info(0x0000, 'testTag', `callerRequestCode is ${callerRequestCode}`); 2452 let want: Want = {}; 2453 let resultCode = 100; 2454 let abilityResult: common.AbilityResult = { 2455 want, 2456 resultCode 2457 }; 2458 try { 2459 // Return the result to the caller. 2460 this.context.backToCallerAbilityWithResult(abilityResult, callerRequestCode) 2461 .then(() => { 2462 // Carry out normal service processing. 2463 hilog.info(0x0000, 'testTag', 'backToCallerAbilityWithResult succeed'); 2464 }) 2465 .catch((err: BusinessError) => { 2466 // Process service logic errors. 2467 hilog.error(0x0000, 'testTag', `backToCallerAbilityWithResult failed, code is ${err.code}, message is ${err.message}`); 2468 }); 2469 } catch (err) { 2470 // Capture the synchronization parameter error. 2471 let code = (err as BusinessError).code; 2472 let message = (err as BusinessError).message; 2473 hilog.error(0x0000, 'testTag', `backToCallerAbilityWithResult failed, code is ${code}, message is ${message}`); 2474 } 2475 } 2476} 2477``` 2478 2479### setRestoreEnabled<sup>14+</sup> 2480 2481setRestoreEnabled(enabled: boolean): void 2482 2483Sets whether to enable backup and restore for this UIAbility. 2484 2485**Atomic service API**: This API can be used in atomic services since API version 14. 2486 2487**System capability**: SystemCapability.Ability.AbilityRuntime.Core 2488 2489**Parameters** 2490 2491| Name| Type| Mandatory| Description| 2492| -------- | -------- | -------- | -------- | 2493| enabled | boolean | Yes| Whether to enable backup and restore. **true** to enable, **false** otherwise.| 2494 2495**Error codes** 2496 2497For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 2498 2499| ID| Error Message| 2500| ------- | -------------------------------- | 2501| 401 | If the input parameter is not valid parameter. | 2502| 16000011 | The context does not exist. | 2503 2504**Example** 2505 2506```ts 2507import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit'; 2508import { BusinessError } from '@kit.BasicServicesKit'; 2509 2510export default class EntryAbility extends UIAbility { 2511 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 2512 let enabled = true; 2513 try { 2514 this.context.setRestoreEnabled(enabled); 2515 } catch (paramError) { 2516 let code = (paramError as BusinessError).code; 2517 let message = (paramError as BusinessError).message; 2518 console.error(`setRestoreEnabled failed, err code: ${code}, err msg: ${message}`); 2519 } 2520 } 2521} 2522``` 2523 2524### startUIServiceExtensionAbility<sup>14+<sup> 2525 2526startUIServiceExtensionAbility(want: Want): Promise<void> 2527 2528Starts a UIServiceExtensionAbility. This API uses a promise to return the result. 2529 2530> **NOTE** 2531> 2532> For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). 2533 2534**Atomic service API**: This API can be used in atomic services since API version 14. 2535 2536**System capability**: SystemCapability.Ability.AbilityRuntime.Core 2537 2538**Parameters** 2539 2540| Name | Type | Mandatory| Description | 2541| -------- | --------------------------------------- | ---- | ------------------------ | 2542| want | [Want](js-apis-app-ability-want.md) | Yes| Mandatory information for starting the UIServiceExtensionAbility.| 2543 2544**Return value** 2545 2546| Type | Description | 2547| ------------------- | -------------------------------------- | 2548| Promise<void> | Promise that returns no value.| 2549 2550**Error codes** 2551 2552For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 2553 2554| ID| Error Message | 2555| -------- | ----------------------------------------------------------------------------------------------------------- | 2556| 201 | The application does not have permission to call the interface. | 2557| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 2558| 801 | Capability not supported. | 2559| 16000001 | The specified ability does not exist. | 2560| 16000002 | Incorrect ability type. | 2561| 16000004 | Cannot start an invisible component. | 2562| 16000005 | The specified process does not have the permission. | 2563| 16000008 | The crowdtesting application expires. | 2564| 16000011 | The context does not exist. | 2565| 16000012 | The application is controlled. | 2566| 16000013 | The application is controlled by EDM. | 2567| 16000019 | No matching ability is found. | 2568| 16000050 | Internal error. | 2569| 16200001 | The caller has been released. | 2570 2571**Example** 2572 2573```ts 2574import { common, Want } from '@kit.AbilityKit'; 2575import { BusinessError } from '@kit.BasicServicesKit'; 2576 2577@Entry 2578@Component 2579struct Index { 2580 build() { 2581 Column() { 2582 Row() { 2583 // Create a Start button. 2584 Button('start ability') 2585 .enabled(true) 2586 .onClick(() => { 2587 let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 2588 let startWant: Want = { 2589 bundleName: 'com.acts.uiserviceextensionability', 2590 abilityName: 'UiServiceExtAbility', 2591 }; 2592 try { 2593 // Start the UIServiceExtensionAbility. 2594 context.startUIServiceExtensionAbility(startWant).then(() => { 2595 console.info('startUIServiceExtensionAbility success'); 2596 }).catch((error: BusinessError) => { 2597 console.info('startUIServiceExtensionAbility error', JSON.stringify(error)); 2598 }) 2599 } catch (err) { 2600 console.info('startUIServiceExtensionAbility failed', JSON.stringify(err)); 2601 } 2602 }) 2603 } 2604 } 2605 } 2606} 2607``` 2608 2609### connectUIServiceExtensionAbility<sup>14+<sup> 2610 2611connectUIServiceExtensionAbility(want: Want, callback: UIServiceExtensionConnectCallback) : Promise<UIServiceProxy> 2612 2613Connects to a UIServiceExtensionAbility. This API uses a promise to return the result. 2614 2615> **NOTE** 2616> 2617> For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). 2618> 2619 2620**Atomic service API**: This API can be used in atomic services since API version 14. 2621 2622**System capability**: SystemCapability.Ability.AbilityRuntime.Core 2623 2624**Parameters** 2625 2626| Name| Type| Mandatory| Description | 2627| ------ | ---- | ---- | ---- | 2628| want |[Want](js-apis-app-ability-want.md) | Yes | Mandatory information for connecting to the UIServiceExtensionAbility.| 2629| callback | [UIServiceExtensionConnectCallback](js-apis-inner-application-uiServiceExtensionconnectcallback.md) | Yes | Callback for connecting to the UIServiceExtensionAbility.| 2630 2631**Return value** 2632 2633| Type | Description | 2634| ------------------- | -------------------------------------- | 2635| Promise<UIServiceProxy> | Promise used to return the result, which is a [UIServiceProxy](js-apis-inner-application-uiserviceproxy.md) object.| 2636 2637**Error codes** 2638 2639For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 2640 2641| ID| Error Message | 2642| -------- | ----------------------------------------------------------------------------------- | 2643| 201 | The application does not have permission to call the interface. | 2644| 801 | Capability not supported. | 2645| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 2646| 16000001 | The specified ability does not exist. | 2647| 16000002 | Incorrect ability type. | 2648| 16000004 | Cannot start an invisible component. | 2649| 16000005 | The specified process does not have the permission. | 2650| 16000008 | The crowdtesting application expires. | 2651| 16000011 | The context does not exist. | 2652| 16000013 | The application is controlled by EDM. | 2653| 16000050 | Internal error. | 2654| 16000055 | Installation-free timed out. | 2655 2656**Example** 2657 2658```ts 2659import { common, Want } from '@kit.AbilityKit'; 2660import { BusinessError } from '@kit.BasicServicesKit'; 2661 2662const TAG: string = '[Extension] '; 2663 2664@Entry 2665@Component 2666struct UIServiceExtensionAbility { 2667 dataCallBack : common.UIServiceExtensionConnectCallback = { 2668 // Receive data 2669 onData: (data: Record<string, Object>) => { 2670 console.info(`dataCallBack received data`, JSON.stringify(data)); 2671 }, 2672 // Disconnect from the UIServiceExtensionAbility. 2673 onDisconnect: () => { 2674 console.info(`dataCallBack onDisconnect`); 2675 } 2676 } 2677 2678 async myConnect() { 2679 // Obtain the context. 2680 let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 2681 let startWant: Want = { 2682 deviceId: '', 2683 bundleName: 'com.example.myapplication', 2684 abilityName: 'UiServiceExtAbility' 2685 }; 2686 2687 try { 2688 // Connect to the UIServiceExtensionAbility. 2689 context.connectUIServiceExtensionAbility(startWant, this.dataCallBack) 2690 .then((proxy: common.UIServiceProxy) => { 2691 console.info(TAG + `try to connectUIServiceExtensionAbility`, JSON.stringify(proxy)); 2692 }).catch((err: Error) => { 2693 let code = (err as BusinessError).code; 2694 let message = (err as BusinessError).message; 2695 console.info(TAG + `connectUIServiceExtensionAbility failed, code is ${code}, message is ${message}`); 2696 }); 2697 } catch (err) { 2698 let code = (err as BusinessError).code; 2699 let message = (err as BusinessError).message; 2700 console.info(TAG + `connectUIServiceExtensionAbility failed, code is ${code}, message is ${message}`); 2701 }; 2702 } 2703 2704 build() { 2705 RelativeContainer() { 2706 // Create a Connect button. 2707 Button('connectServiceExtensionAbility', { type: ButtonType.Capsule, stateEffect: true }) 2708 .alignRules({ 2709 center: { anchor: '__container__', align: VerticalAlign.Center }, 2710 middle: { anchor: '__container__', align: HorizontalAlign.Center } 2711 }) 2712 .onClick(() => { 2713 this.myConnect() 2714 }); 2715 } 2716 .height('100%') 2717 .width('100%') 2718 } 2719} 2720``` 2721 2722### disconnectUIServiceExtensionAbility<sup>14+<sup> 2723 2724disconnectUIServiceExtensionAbility(proxy: UIServiceProxy): Promise<void> 2725 2726Disconnects from a UIServiceExtensionAbility. This API uses a promise to return the result. 2727 2728> **NOTE** 2729> 2730> For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). 2731> 2732 2733**Atomic service API**: This API can be used in atomic services since API version 14. 2734 2735**System capability**: SystemCapability.Ability.AbilityRuntime.Core 2736 2737**Parameters** 2738 2739| Name| Type| Mandatory| Description | 2740| ------ | ---- | ---- | -------------------- | 2741| proxy | [UIServiceProxy](js-apis-inner-application-uiserviceproxy.md) | Yes| Proxy returned after [connectUIServiceExtensionAbility](#connectuiserviceextensionability14) is called.| 2742 2743**Return value** 2744 2745| Type | Description | 2746| ------------------- | -------------------------------------- | 2747| Promise<void> | Promise that returns no value.| 2748 2749**Error codes** 2750 2751For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 2752 2753| ID| Error Message | 2754| -------- | ------------------------------------------------------------------------------------------- | 2755| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 2756| 16000011 | The context does not exist. | 2757| 16000050 | Internal error. | 2758 2759**Example** 2760 2761```ts 2762import { common } from '@kit.AbilityKit'; 2763import { BusinessError } from '@kit.BasicServicesKit'; 2764 2765const TAG: string = '[Extension] '; 2766 2767@Entry 2768@Component 2769struct UIServiceExtensionAbility { 2770 comProxy: common.UIServiceProxy | null = null; 2771 2772 build() { 2773 Scroll() { 2774 Column() { 2775 // Create a Disconnect button. 2776 Button('disconnectUIServiceExtensionAbility', { type: ButtonType.Capsule, stateEffect: true }) 2777 .margin({ 2778 top: 5, 2779 left: 10, 2780 right: 10, 2781 bottom: 5 2782 }) 2783 .alignRules({ 2784 center: { anchor: '__container__', align: VerticalAlign.Center }, 2785 middle: { anchor: '__container__', align: HorizontalAlign.Center } 2786 }) 2787 .onClick(() => { 2788 this.myDisconnectUIServiceExtensionAbility() 2789 }); 2790 } 2791 .width('100%') 2792 } 2793 .height('100%') 2794 } 2795 2796 myDisconnectUIServiceExtensionAbility() { 2797 let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 2798 2799 try { 2800 // Disconnect from the UIServiceExtensionAbility. 2801 context.disconnectUIServiceExtensionAbility(this.comProxy) 2802 .then(() => { 2803 console.info(TAG + `disconnectUIServiceExtensionAbility succeed ${this.comProxy}`); 2804 }).catch((err: Error) => { 2805 let code = (err as BusinessError).code; 2806 let message = (err as BusinessError).message; 2807 console.info(TAG + `disconnectUIServiceExtensionAbility failed, code is ${code}, message is ${message}`); 2808 }); 2809 } catch (err) { 2810 let code = (err as BusinessError).code; 2811 let message = (err as BusinessError).message; 2812 console.info(TAG + `disconnectUIServiceExtensionAbility failed, code is ${code}, message is ${message}`); 2813 } 2814 } 2815} 2816``` 2817 2818### setAbilityInstanceInfo<sup>15+<sup> 2819 2820setAbilityInstanceInfo(label: string, icon: image.PixelMap) : Promise<void> 2821 2822Sets the icon and label for this UIAbility. The icon and label can be displayed in the task center and the shortcut bar. This API uses a promise to return the result. 2823 2824**Required permissions**: ohos.permission.SET_ABILITY_INSTANCE_INFO 2825 2826**System capability**: SystemCapability.Ability.AbilityRuntime.Core 2827 2828**Device behavior differences**: This API can be properly called only on 2-in-1 devices. If it is called on other device types, error code 801 is returned. 2829 2830**Parameters** 2831 2832| Name| Type | Mandatory| Description | 2833| ------ | -------------------------------------------------------------- | ---- | -------------------------------------------------- | 2834| label |string | Yes | Label. The label cannot be an empty string, and can contain a maximum of 1024 bytes. | 2835| icon | [image.PixelMap](../apis-image-kit/arkts-apis-image-PixelMap.md) | Yes | Icon. The recommended icon size is 512 px * 512 px. | 2836 2837**Return value** 2838 2839| Type | Description | 2840| ------------------- | -------------------------------------- | 2841| Promise<void> | Promise that returns no value.| 2842 2843**Error codes** 2844 2845For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 2846 2847| ID| Error Message | 2848| -------- | ----------------------------------------------------------------------------------- | 2849| 201 | The application does not have permission to call the interface. | 2850| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 2851| 801 | Capability not supported. | 2852| 16000011 | The context does not exist. | 2853| 16000050 | Internal error. | 2854 2855**Example** 2856 2857```ts 2858import { UIAbility } from '@kit.AbilityKit'; 2859import { image } from '@kit.ImageKit'; 2860import { BusinessError } from '@kit.BasicServicesKit'; 2861import { window } from '@kit.ArkUI'; 2862 2863export default class EntryAbility extends UIAbility { 2864 onWindowStageCreate(windowStage: window.WindowStage): void { 2865 windowStage.loadContent('pages/Index', async (err, data) => { 2866 if (err.code) { 2867 console.error(`loadContent failed, code is ${err.code}`); 2868 return; 2869 } 2870 2871 let newLabel: string = 'instance label'; 2872 let color = new ArrayBuffer(512 * 512 * 4); // Create an ArrayBuffer object to store image pixels. The size of the object is (height * width * 4) bytes. 2873 let bufferArr = new Uint8Array(color); 2874 for (let i = 0; i < bufferArr.length; i += 4) { 2875 bufferArr[i] = 255; 2876 bufferArr[i+1] = 0; 2877 bufferArr[i+2] = 122; 2878 bufferArr[i+3] = 255; 2879 } 2880 let opts: image.InitializationOptions = { 2881 editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 512, width: 512 } 2882 }; 2883 let imagePixelMap: image.PixelMap = await image.createPixelMap(color, opts); 2884 this.context.setAbilityInstanceInfo(newLabel, imagePixelMap) 2885 .then(() => { 2886 console.info('setAbilityInstanceInfo success'); 2887 }).catch((err: BusinessError) => { 2888 console.error(`setAbilityInstanceInfo failed, code is ${err.code}, message is ${err.message}`); 2889 }); 2890 }); 2891 } 2892} 2893``` 2894 2895### revokeDelegator<sup>17+</sup> 2896 2897revokeDelegator() : Promise<void> 2898 2899When the first UIAbility launched under a module needs to redirect to another UIAbility, the target UIAbility is known as the DelegatorAbility. For details about how to set up the DelegatorAbility, see step 1 in the example provided for this API. 2900 2901Once the DelegatorAbility has completed its specific operations, you can use this API to revert to the first UIAbility. This API uses a promise to return the result. 2902 2903> **NOTE** 2904> 2905> After the API is successfully called, the [Window](../apis-arkui/arkts-apis-window.md) API within the DelegatorAbility becomes invalid. 2906 2907**System capability**: SystemCapability.Ability.AbilityRuntime.Core 2908 2909**Return value** 2910 2911| Type | Description | 2912| ------------------- | -------------------------------------- | 2913| Promise<void> | Promise that returns no value.| 2914 2915**Error codes** 2916 2917For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 2918 2919| ID| Error Message| 2920| ------- | -------- | 2921| 801 | Capability not support. | 2922| 16000011 | The context does not exist. | 2923| 16000050 | Internal error. | 2924| 16000065 | The API can be called only when the ability is running in the foreground. | 2925| 16000084 | Only DelegatorAbility is allowed to call this API, and only once. | 2926| 16000085 | An error occurred during the interaction between the ability and window. | 2927 2928**Example** 2929 29301. Set a DelegatorAbility. 2931 2932 Configure **abilitySrcEntryDelegator** and **abilityStageSrcEntryDelegator** in the [module.json5](../../quick-start/module-configuration-file.md) file. When the first UIAbility of the module is cold started, the system preferentially starts the UIAbility specified by **abilitySrcEntryDelegator**. 2933 > **NOTE** 2934 > 2935 > - If the UIAbility is started by calling [startAbilityByCall](#startabilitybycall), the system ignores **abilitySrcEntryDelegator** and **abilityStageSrcEntryDelegator** configured in the [module.json5](../../quick-start/module-configuration-file.md) file. 2936 > - The module name specified by **abilityStageSrcEntryDelegator** must be different from the current module name. 2937 ```json 2938 { 2939 "module": { 2940 // ... 2941 "abilityStageSrcEntryDelegator": "xxxModuleName", 2942 "abilitySrcEntryDelegator": "xxxAbilityName", 2943 // ... 2944 } 2945 } 2946 ``` 2947 29482. Revoke the DelegatorAbility. 2949 2950 ```ts 2951 import { UIAbility } from '@kit.AbilityKit'; 2952 import { BusinessError } from '@kit.BasicServicesKit'; 2953 2954 export default class DelegatorAbility extends UIAbility { 2955 onForeground() { 2956 // After the DelegatorAbility completes the specific operation, call revokeDelegator to revert to the first UIAbility. 2957 this.context.revokeDelegator().then(() => { 2958 console.info('revokeDelegator success'); 2959 }).catch((err: BusinessError) => { 2960 console.error(`revokeDelegator failed, code is ${err.code}, message is ${err.message}`); 2961 }); 2962 } 2963 } 2964 ``` 2965 2966### setColorMode<sup>18+</sup> 2967 2968setColorMode(colorMode: ConfigurationConstant.ColorMode): void 2969 2970Sets the dark/light color mode for this UIAbility. Before calling this API, ensure that the page corresponding to the UIAbility has been loaded. This API can be called only by the main thread. 2971 2972> **NOTE** 2973> - Before calling this API, ensure that the window has been created and the page corresponding to the UIAbility has been loaded (using the [loadContent](../apis-arkui/arkts-apis-window-WindowStage.md#loadcontent9) API in the [onWindowStageCreate()](js-apis-app-ability-uiAbility.md#onwindowstagecreate) lifecycle). 2974> - After this API is called, a new resource manager object is created. If a resource manager was previously cached, it should be updated accordingly. 2975> - The priority of the dark/light color mode is as follows: UIAbility dark/light color mode > Application dark/light color mode (set via [ApplicationContext.setColorMode](js-apis-inner-application-applicationContext.md#applicationcontextsetcolormode11)) > System dark/light color mode. 2976 2977**Atomic service API**: This API can be used in atomic services since API version 18. 2978 2979**System capability**: SystemCapability.Ability.AbilityRuntime.Core 2980 2981**Parameters** 2982 2983| Name| Type | Mandatory| Description | 2984| ------ | ------------- | ---- | -------------------- | 2985| colorMode | [ConfigurationConstant.ColorMode](js-apis-app-ability-configurationConstant.md) | Yes | Color mode. The options are as follows:<br> - **COLOR_MODE_DARK**: dark mode.<br> - **COLOR_MODE_LIGHT**: light mode.<br> - **COLOR_MODE_NOT_SET**: not set (following the system or application).| 2986 2987**Error codes** 2988 2989For details about the error codes, see [Ability Error Codes](errorcode-ability.md). 2990 2991| ID| Error Message| 2992| ------- | -------- | 2993| 16000011 | The context does not exist. | 2994 2995**Example** 2996 2997```ts 2998import { UIAbility, ConfigurationConstant } from '@kit.AbilityKit'; 2999import { hilog } from '@kit.PerformanceAnalysisKit'; 3000import { window } from '@kit.ArkUI'; 3001 3002export default class MyAbility extends UIAbility { 3003 onWindowStageCreate(windowStage: window.WindowStage) { 3004 windowStage.loadContent('pages/Index', (err, data) => { 3005 if (err.code) { 3006 hilog.error(0x0000, 'testTag', 'Failed to load the content.'); 3007 return; 3008 } 3009 let uiAbilityContext = this.context; 3010 uiAbilityContext.setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_DARK); 3011 }); 3012 } 3013} 3014``` 3015 3016### startAppServiceExtensionAbility<sup>20+</sup> 3017 3018startAppServiceExtensionAbility(want: Want): Promise\<void> 3019 3020Starts an [AppServiceExtensionAbility](js-apis-app-ability-appServiceExtensionAbility.md) instance. This API uses a promise to return the result. 3021 3022> **NOTE** 3023> 3024> The caller of this API must be the application to which the [AppServiceExtensionAbility](js-apis-app-ability-appServiceExtensionAbility.md) instance belongs or an application in the application list supported by the AppServiceExtensionAbility instance (configured in the **appIdentifierAllowList** property of [extensionAbilities](../../quick-start/module-configuration-file.md#extensionabilities)). 3025 3026**System capability**: SystemCapability.Ability.AbilityRuntime.Core 3027 3028**Device behavior differences**: This API can be properly called only on 2-in-1 devices. If it is called on other device types, error code 801 is returned. 3029 3030**Parameters** 3031 3032| Name| Type| Mandatory| Description| 3033| -------- | -------- | -------- | -------- | 3034| want | [Want](js-apis-app-ability-want.md) | Yes| Want information for starting the [AppServiceExtensionAbility](js-apis-app-ability-appServiceExtensionAbility.md).| 3035 3036**Return value** 3037 3038| Type | Description | 3039| ------------------- | -------------------------------------- | 3040| Promise\<void> | Promise that returns no value.| 3041 3042**Error codes** 3043 3044For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 3045 3046| ID| Error Message| 3047| ------- | -------------------------------- | 3048| 801 | Capability not supported. | 3049| 16000001 | The specified ability does not exist. | 3050| 16000002 | Incorrect ability type. | 3051| 16000004 | Cannot start an invisible component. | 3052| 16000005 | The specified process does not have the permission. | 3053| 16000006 | Cross-user operations are not allowed. | 3054| 16000008 | The crowdtesting application expires. | 3055| 16000011 | The context does not exist. | 3056| 16000012 | The application is controlled. | 3057| 16000013 | The application is controlled by EDM. | 3058| 16000019 | No matching ability is found. | 3059| 16000050 | Internal error. | 3060| 16000200 | The caller is not in the appIdentifierAllowList of the target application. | 3061 3062**Example** 3063 3064```ts 3065import { UIAbility, Want } from '@kit.AbilityKit'; 3066import { BusinessError } from '@kit.BasicServicesKit'; 3067 3068export default class EntryAbility extends UIAbility { 3069 onForeground() { 3070 let want: Want = { 3071 deviceId: '', 3072 bundleName: 'com.example.myapplication', 3073 abilityName: 'AppServiceExtensionAbility' 3074 }; 3075 3076 try { 3077 this.context.startAppServiceExtensionAbility(want) 3078 .then(() => { 3079 // Carry out normal service processing. 3080 console.info('startAppServiceExtensionAbility succeed'); 3081 }) 3082 .catch((err: BusinessError) => { 3083 // Process service logic errors. 3084 console.error(`startAppServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); 3085 }); 3086 } catch (err) { 3087 // Process input parameter errors. 3088 let code = (err as BusinessError).code; 3089 let message = (err as BusinessError).message; 3090 console.error(`startAppServiceExtensionAbility failed, code is ${code}, message is ${message}`); 3091 } 3092 } 3093} 3094``` 3095 3096### stopAppServiceExtensionAbility<sup>20+</sup> 3097 3098stopAppServiceExtensionAbility(want: Want): Promise\<void> 3099 3100Stops an [AppServiceExtensionAbility](js-apis-app-ability-appServiceExtensionAbility.md) instance. This API uses a promise to return the result. 3101 3102> **NOTE** 3103> 3104> The caller of this API must be the application to which the [AppServiceExtensionAbility](js-apis-app-ability-appServiceExtensionAbility.md) instance belongs or an application in the application list supported by the AppServiceExtensionAbility instance (configured in the **appIdentifierAllowList** property of [extensionAbilities](../../quick-start/module-configuration-file.md#extensionabilities)). 3105 3106**System capability**: SystemCapability.Ability.AbilityRuntime.Core 3107 3108**Device behavior differences**: This API can be properly called only on 2-in-1 devices. If it is called on other device types, error code 801 is returned. 3109 3110**Parameters** 3111 3112| Name| Type| Mandatory| Description| 3113| -------- | -------- | -------- | -------- | 3114| want | [Want](js-apis-app-ability-want.md) | Yes| Want information for stoping the [AppServiceExtensionAbility](js-apis-app-ability-appServiceExtensionAbility.md).| 3115 3116**Return value** 3117 3118| Type | Description | 3119| ------------------- | -------------------------------------- | 3120| Promise\<void> | Promise that returns no value.| 3121 3122**Error codes** 3123 3124For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 3125 3126| ID| Error Message| 3127| ------- | -------------------------------- | 3128| 801 | Capability not supported. | 3129| 16000001 | The specified ability does not exist. | 3130| 16000002 | Incorrect ability type. | 3131| 16000004 | Cannot start an invisible component. | 3132| 16000005 | The specified process does not have the permission. | 3133| 16000006 | Cross-user operations are not allowed. | 3134| 16000011 | The context does not exist. | 3135| 16000050 | Internal error. | 3136| 16000200 | The caller is not in the appIdentifierAllowList of the target application. | 3137 3138**Example** 3139 3140```ts 3141import { UIAbility, Want } from '@kit.AbilityKit'; 3142import { BusinessError } from '@kit.BasicServicesKit'; 3143 3144export default class EntryAbility extends UIAbility { 3145 onForeground() { 3146 let want: Want = { 3147 deviceId: '', 3148 bundleName: 'com.example.myapplication', 3149 abilityName: 'AppServiceExtensionAbility' 3150 }; 3151 3152 try { 3153 this.context.stopAppServiceExtensionAbility(want) 3154 .then(() => { 3155 // Carry out normal service processing. 3156 console.info('stopAppServiceExtensionAbility succeed'); 3157 }) 3158 .catch((err: BusinessError) => { 3159 // Process service logic errors. 3160 console.error(`stopAppServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); 3161 }); 3162 } catch (err) { 3163 // Process input parameter errors. 3164 let code = (err as BusinessError).code; 3165 let message = (err as BusinessError).message; 3166 console.error(`stopAppServiceExtensionAbility failed, code is ${code}, message is ${message}`); 3167 } 3168 } 3169} 3170``` 3171 3172### connectAppServiceExtensionAbility<sup>20+</sup> 3173 3174connectAppServiceExtensionAbility(want: Want, callback: ConnectOptions): number 3175 3176Connects this UIAbility to an [AppServiceExtensionAbility](js-apis-app-ability-appServiceExtensionAbility.md). It enables communication with the AppServiceExtensionAbility via a proxy, allowing access to the capabilities exposed by the AppServiceExtensionAbility. It can be called only by the main thread. 3177 3178> **NOTE** 3179> 3180> If the [AppServiceExtensionAbility](js-apis-app-ability-appServiceExtensionAbility.md) instance is not started, the caller of this API must be the application to which the [AppServiceExtensionAbility](js-apis-app-ability-appServiceExtensionAbility.md) instance belongs or an application in the application list supported by the AppServiceExtensionAbility instance (configured in the **appIdentifierAllowList** property of [extensionAbilities](../../quick-start/module-configuration-file.md#extensionabilities)). 3181 3182**System capability**: SystemCapability.Ability.AbilityRuntime.Core 3183 3184**Device behavior differences**: This API can be properly called only on 2-in-1 devices. If it is called on other device types, error code 801 is returned. 3185 3186**Parameters** 3187 3188| Name| Type| Mandatory| Description| 3189| -------- | -------- | -------- | -------- | 3190| want | [Want](js-apis-app-ability-want.md) | Yes| Want information for connecting to the [AppServiceExtensionAbility](js-apis-app-ability-appServiceExtensionAbility.md).| 3191| callback | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes| Callback used to return the information indicating that the connection is successful, failed, or interrupted.| 3192 3193**Return value** 3194 3195| Type| Description| 3196| -------- | -------- | 3197| number | Connection ID. A caller can call [disconnectAppServiceExtensionAbility](#disconnectappserviceextensionability20) with this ID for disconnection.| 3198 3199**Error codes** 3200 3201For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 3202 3203| ID| Error Message| 3204| ------- | -------------------------------- | 3205| 801 | Capability not supported. | 3206| 16000001 | The specified ability does not exist. | 3207| 16000002 | Incorrect ability type. | 3208| 16000004 | Cannot start an invisible component. | 3209| 16000005 | The specified process does not have the permission. | 3210| 16000006 | Cross-user operations are not allowed. | 3211| 16000008 | The crowdtesting application expires. | 3212| 16000011 | The context does not exist. | 3213| 16000050 | Internal error. | 3214| 16000201 | The target service has not been started yet. | 3215 3216**Example** 3217 3218```ts 3219import { UIAbility, Want, common } from '@kit.AbilityKit'; 3220import { rpc } from '@kit.IPCKit'; 3221import { BusinessError } from '@kit.BasicServicesKit'; 3222 3223export default class EntryAbility extends UIAbility { 3224 onForeground() { 3225 let want: Want = { 3226 deviceId: '', 3227 bundleName: 'com.example.myapplication', 3228 abilityName: 'AppServiceExtensionAbility' 3229 }; 3230 let commRemote: rpc.IRemoteObject; 3231 let callback: common.ConnectOptions = { 3232 onConnect(elementName, remote) { 3233 commRemote = remote; 3234 console.info('onConnect...'); 3235 }, 3236 onDisconnect(elementName) { 3237 console.info('onDisconnect...'); 3238 }, 3239 onFailed(code) { 3240 console.info('onFailed...'); 3241 } 3242 }; 3243 let connection: number; 3244 3245 try { 3246 connection = this.context.connectAppServiceExtensionAbility(want, callback); 3247 } catch (err) { 3248 // Process input parameter errors. 3249 let code = (err as BusinessError).code; 3250 let message = (err as BusinessError).message; 3251 console.error(`connectAppServiceExtensionAbility failed, code is ${code}, message is ${message}`); 3252 } 3253 } 3254} 3255``` 3256 3257### disconnectAppServiceExtensionAbility<sup>20+</sup> 3258 3259disconnectAppServiceExtensionAbility(connection: number): Promise\<void> 3260 3261Disconnects from an [AppServiceExtensionAbility](js-apis-app-ability-appServiceExtensionAbility.md). It can be called only by the main thread. This API uses a promise to return the result. 3262 3263Once the connection is terminated, you are advised to set the remote object returned when the connection is established to null, so as to prevent communication using the remote object that may become invalid. 3264 3265**System capability**: SystemCapability.Ability.AbilityRuntime.Core 3266 3267**Device behavior differences**: This API can be properly called only on 2-in-1 devices. If it is called on other device types, error code 801 is returned. 3268 3269**Parameters** 3270 3271| Name| Type| Mandatory| Description| 3272| -------- | -------- | -------- | -------- | 3273| connection | number | Yes| Connection ID returned by [connectAppServiceExtensionAbility](#connectappserviceextensionability20).| 3274 3275**Return value** 3276 3277| Type| Description| 3278| -------- | -------- | 3279| Promise\<void> | Promise that returns no value.| 3280 3281**Error codes** 3282 3283For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 3284 3285| ID| Error Message| 3286| ------- | -------------------------------- | 3287| 801 | Capability not supported. | 3288| 16000011 | The context does not exist. | 3289| 16000050 | Internal error. | 3290 3291**Example** 3292 3293```ts 3294import { UIAbility } from '@kit.AbilityKit'; 3295import { rpc } from '@kit.IPCKit'; 3296import { BusinessError } from '@kit.BasicServicesKit'; 3297 3298export default class EntryAbility extends UIAbility { 3299 onForeground() { 3300 // connection is the return value of connectAppServiceExtensionAbility. 3301 let connection = 1; 3302 let commRemote: rpc.IRemoteObject | null; 3303 3304 try { 3305 this.context.disconnectAppServiceExtensionAbility(connection).then(() => { 3306 commRemote = null; 3307 // Carry out normal service processing. 3308 console.info('disconnectAppServiceExtensionAbility succeed'); 3309 }).catch((err: BusinessError) => { 3310 // Process service logic errors. 3311 console.error(`disconnectAppServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); 3312 }); 3313 } catch (err) { 3314 commRemote = null; 3315 // Process input parameter errors. 3316 let code = (err as BusinessError).code; 3317 let message = (err as BusinessError).message; 3318 console.error(`disconnectAppServiceExtensionAbility failed, code is ${code}, message is ${message}`); 3319 } 3320 } 3321} 3322``` 3323 3324### setOnNewWantSkipScenarios<sup>20+</sup> 3325 3326setOnNewWantSkipScenarios(scenarios: number): Promise\<void> 3327 3328Sets whether to trigger the [onNewWant](./js-apis-app-ability-uiAbility.md#onnewwant) lifecycle callback when a UIAbility is started in a specific scenario. It can be called only by the main thread. This API uses a promise to return the result. 3329 3330> **NOTE** 3331> 3332> This API is usually used within the [onCreate](./js-apis-app-ability-uiAbility.md#oncreate) lifecycle callback. You are advised to include all the enumerated values of [Scenarios](js-apis-app-ability-contextConstant.md#scenarios20) when specifying the **scenarios** parameter. For details, see the sample code below. 3333 3334**Atomic service API**: This API can be used in atomic services since API version 20. 3335 3336**System capability**: SystemCapability.Ability.AbilityRuntime.Core 3337 3338**Parameters** 3339 3340| Name| Type| Mandatory| Description| 3341| -------- | -------- | -------- | -------- | 3342| scenarios | number | Yes| Scenarios. For details about the available options, see [Scenarios](./js-apis-app-ability-contextConstant.md#scenarios20).| 3343 3344**Return value** 3345 3346| Type| Description| 3347| -------- | -------- | 3348| Promise\<void> | Promise that returns no value.| 3349 3350**Error codes** 3351 3352For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 3353 3354| ID| Error Message| 3355| ------- | -------------------------------- | 3356| 16000050 | Internal error. Possible causes: Connection to service failed. | 3357 3358**Example** 3359 3360```ts 3361import { AbilityConstant, contextConstant, UIAbility, Want } from '@kit.AbilityKit'; 3362import { BusinessError } from '@kit.BasicServicesKit'; 3363 3364export default class EntryAbility extends UIAbility { 3365 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 3366 let scenarios: number = contextConstant.Scenarios.SCENARIO_MOVE_MISSION_TO_FRONT | 3367 contextConstant.Scenarios.SCENARIO_SHOW_ABILITY | 3368 contextConstant.Scenarios.SCENARIO_BACK_TO_CALLER_ABILITY_WITH_RESULT; 3369 3370 try { 3371 this.context.setOnNewWantSkipScenarios(scenarios).then(() => { 3372 // Carry out normal service processing. 3373 console.info('setOnNewWantSkipScenarios succeed'); 3374 }).catch((err: BusinessError) => { 3375 // Process service logic errors. 3376 console.error(`setOnNewWantSkipScenarios failed, code is ${err.code}, message is ${err.message}`); 3377 }); 3378 } catch (err) { 3379 // Process input parameter errors. 3380 let code = (err as BusinessError).code; 3381 let message = (err as BusinessError).message; 3382 console.error(`setOnNewWantSkipScenarios failed, code is ${code}, message is ${message}`); 3383 } 3384 } 3385} 3386``` 3387