1# UIAbilityContext 2 3UIAbilityContext是需要保存状态的[UIAbility](js-apis-app-ability-uiAbility.md)所对应的context,继承自[Context](js-apis-inner-application-context.md),提供UIAbility的相关配置信息以及操作UIAbility和ServiceExtensionAbility的方法,如启动UIAbility,停止当前UIAbilityContext所属的UIAbility,启动、停止、连接、断开连接ServiceExtensionAbility等。 4 5> **说明:** 6> 7> - 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 8> - 本模块接口仅可在Stage模型下使用。 9 10## 导入模块 11 12```ts 13import { common } from '@kit.AbilityKit'; 14``` 15 16## 属性 17 18**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 19 20| 名称 | 类型 | 可读 | 可写 | 说明 | 21| -------- | -------- | -------- | -------- | -------- | 22| abilityInfo | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | 是 | 否 | UIAbility的相关信息。<br>**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 | 23| currentHapModuleInfo | [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) | 是 | 否 | 当前HAP的信息。<br>**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 | 24| config | [Configuration](js-apis-app-ability-configuration.md) | 是 | 否 | 与UIAbility相关的配置信息,如语言、颜色模式等。<br>**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 | 25| windowStage<sup>12+</sup> | [window.WindowStage](../apis-arkui/js-apis-window.md#windowstage9) | 是 | 否 | 当前WindowStage对象。仅支持在主线程调用。<br>**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。| 26 27> **关于示例代码的说明:** 28> 29> 在本文档的示例中,通过`this.context`来获取`UIAbilityContext`,其中`this`代表继承自`UIAbility`的`UIAbility`实例。如需要在页面中使用`UIAbilityContext`提供的能力,请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。 30 31## UIAbilityContext.startAbility 32 33startAbility(want: Want, callback: AsyncCallback<void>): void 34 35启动Ability。使用callback异步回调。仅支持在主线程调用。 36 37> **说明:** 38> 39> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。 40 41**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 42 43**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 44 45**参数:** 46 47| 参数名 | 类型 | 必填 | 说明 | 48| -------- | -------- | -------- | -------- | 49| want | [Want](js-apis-app-ability-want.md) | 是 | 启动Ability的want信息。 | 50| callback | AsyncCallback<void> | 是 | callback形式返回启动结果。 | 51 52**错误码:** 53 54以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 55 56| 错误码ID | 错误信息 | 57| ------- | -------------------------------- | 58| 201 | The application does not have permission to call the interface. | 59| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 60| 16000001 | The specified ability does not exist. | 61| 16000002 | Incorrect ability type. | 62| 16000004 | Failed to start the invisible ability. | 63| 16000005 | The specified process does not have the permission. | 64| 16000006 | Cross-user operations are not allowed. | 65| 16000008 | The crowdtesting application expires. | 66| 16000009 | An ability cannot be started or stopped in Wukong mode. | 67| 16000010 | The call with the continuation and prepare continuation flag is forbidden. | 68| 16000011 | The context does not exist. | 69| 16000012 | The application is controlled. | 70| 16000013 | The application is controlled by EDM. | 71| 16000018 | Redirection to a third-party application is not allowed in API version 11 or later. | 72| 16000019 | No matching ability is found. | 73| 16000050 | Internal error. | 74| 16000053 | The ability is not on the top of the UI. | 75| 16000055 | Installation-free timed out. | 76| 16000071 | App clone is not supported. | 77| 16000072 | App clone or multi-instance is not supported. | 78| 16000073 | The app clone index is invalid. | 79| 16000076 | The app instance key is invalid. | 80| 16000077 | The number of app instances reaches the limit. | 81| 16000078 | The multi-instance is not supported. | 82| 16000079 | The APP_INSTANCE_KEY cannot be specified. | 83| 16000080 | Creating a new instance is not supported. | 84| 16200001 | The caller has been released. | 85 86**示例:** 87 88```ts 89import { UIAbility, Want } from '@kit.AbilityKit'; 90import { BusinessError } from '@kit.BasicServicesKit'; 91 92export default class EntryAbility extends UIAbility { 93 onForeground() { 94 let want: Want = { 95 bundleName: 'com.example.myapplication', 96 abilityName: 'EntryAbility' 97 }; 98 99 try { 100 this.context.startAbility(want, (err: BusinessError) => { 101 if (err.code) { 102 // 处理业务逻辑错误 103 console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); 104 return; 105 } 106 // 执行正常业务 107 console.info('startAbility succeed'); 108 }); 109 } catch (err) { 110 // 处理入参错误异常 111 let code = (err as BusinessError).code; 112 let message = (err as BusinessError).message; 113 console.error(`startAbility failed, code is ${code}, message is ${message}`); 114 } 115 } 116} 117``` 118 119## UIAbilityContext.startAbility 120 121startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void 122 123启动Ability。使用callback异步回调。仅支持在主线程调用。 124 125> **说明:** 126> 127> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。 128 129**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 130 131**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 132 133**参数:** 134 135| 参数名 | 类型 | 必填 | 说明 | 136| -------- | -------- | -------- | -------- | 137| want | [Want](js-apis-app-ability-want.md) | 是 | 启动Ability的want信息。 | 138| options | [StartOptions](js-apis-app-ability-startOptions.md) | 是 | 启动Ability所携带的参数。 | 139| callback | AsyncCallback<void> | 是 | callback形式返回启动结果。 | 140 141**错误码:** 142 143以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 144 145| 错误码ID | 错误信息 | 146| ------- | -------------------------------- | 147| 201 | The application does not have permission to call the interface. | 148| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 149| 801 | Capability not support. | 150| 16000001 | The specified ability does not exist. | 151| 16000004 | Failed to start the invisible ability. | 152| 16000005 | The specified process does not have the permission. | 153| 16000006 | Cross-user operations are not allowed. | 154| 16000008 | The crowdtesting application expires. | 155| 16000009 | An ability cannot be started or stopped in Wukong mode. | 156| 16000011 | The context does not exist. | 157| 16000012 | The application is controlled. | 158| 16000013 | The application is controlled by EDM. | 159| 16000018 | Redirection to a third-party application is not allowed in API version 11 or later. | 160| 16000019 | No matching ability is found. | 161| 16000050 | Internal error. | 162| 16000053 | The ability is not on the top of the UI. | 163| 16000055 | Installation-free timed out. | 164| 16000067 | The StartOptions check failed. | 165| 16000068 | The ability is already running. | 166| 16300003 | The target application is not self application. | 167| 16000071 | App clone is not supported. | 168| 16000072 | App clone or multi-instance is not supported. | 169| 16000073 | The app clone index is invalid. | 170| 16000076 | The app instance key is invalid. | 171| 16000077 | The number of app instances reaches the limit. | 172| 16000078 | The multi-instance is not supported. | 173| 16000079 | The APP_INSTANCE_KEY cannot be specified. | 174| 16000080 | Creating a new instance is not supported. | 175| 16200001 | The caller has been released. | 176 177**示例:** 178 179```ts 180import { UIAbility, Want, StartOptions } from '@kit.AbilityKit'; 181import { BusinessError } from '@kit.BasicServicesKit'; 182 183export default class EntryAbility extends UIAbility { 184 onForeground() { 185 let want: Want = { 186 deviceId: '', 187 bundleName: 'com.example.myapplication', 188 abilityName: 'EntryAbility' 189 }; 190 let options: StartOptions = { 191 displayId: 0 192 }; 193 194 try { 195 this.context.startAbility(want, options, (err: BusinessError) => { 196 if (err.code) { 197 // 处理业务逻辑错误 198 console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); 199 return; 200 } 201 // 执行正常业务 202 console.info('startAbility succeed'); 203 }); 204 } catch (err) { 205 // 处理入参错误异常 206 let code = (err as BusinessError).code; 207 let message = (err as BusinessError).message; 208 console.error(`startAbility failed, code is ${code}, message is ${message}`); 209 } 210 } 211} 212``` 213 214## UIAbilityContext.startAbility 215 216startAbility(want: Want, options?: StartOptions): Promise<void> 217 218启动Ability。使用Promise异步回调。仅支持在主线程调用。 219 220> **说明:** 221> 222> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。 223 224**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 225 226**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 227 228**参数:** 229 230| 参数名 | 类型 | 必填 | 说明 | 231| -------- | -------- | -------- | -------- | 232| want | [Want](js-apis-app-ability-want.md) | 是 | 启动Ability的want信息。 | 233| options | [StartOptions](js-apis-app-ability-startOptions.md) | 否 | 启动Ability所携带的参数。 | 234 235**返回值:** 236 237| 类型 | 说明 | 238| -------- | -------- | 239| Promise<void> | Promise形式返回启动结果。 | 240 241**错误码:** 242 243以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 244 245| 错误码ID | 错误信息 | 246| ------- | -------------------------------- | 247| 201 | The application does not have permission to call the interface. | 248| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 249| 801 | Capability not support. | 250| 16000001 | The specified ability does not exist. | 251| 16000002 | Incorrect ability type. | 252| 16000004 | Failed to start the invisible ability. | 253| 16000005 | The specified process does not have the permission. | 254| 16000006 | Cross-user operations are not allowed. | 255| 16000008 | The crowdtesting application expires. | 256| 16000009 | An ability cannot be started or stopped in Wukong mode. | 257| 16000010 | The call with the continuation and prepare continuation flag is forbidden. | 258| 16000011 | The context does not exist. | 259| 16000012 | The application is controlled. | 260| 16000013 | The application is controlled by EDM. | 261| 16000018 | Redirection to a third-party application is not allowed in API version 11 or later. | 262| 16000019 | No matching ability is found. | 263| 16000050 | Internal error. | 264| 16000053 | The ability is not on the top of the UI. | 265| 16000055 | Installation-free timed out. | 266| 16000067 | The StartOptions check failed. | 267| 16000068 | The ability is already running. | 268| 16300003 | The target application is not self application. | 269| 16000071 | App clone is not supported. | 270| 16000072 | App clone or multi-instance is not supported. | 271| 16000073 | The app clone index is invalid. | 272| 16000076 | The app instance key is invalid. | 273| 16000077 | The number of app instances reaches the limit. | 274| 16000078 | The multi-instance is not supported. | 275| 16000079 | The APP_INSTANCE_KEY cannot be specified. | 276| 16000080 | Creating a new instance is not supported. | 277| 16200001 | The caller has been released. | 278 279**示例:** 280 281```ts 282import { UIAbility, Want, StartOptions } from '@kit.AbilityKit'; 283import { BusinessError } from '@kit.BasicServicesKit'; 284 285export default class EntryAbility extends UIAbility { 286 onForeground() { 287 let want: Want = { 288 bundleName: 'com.example.myapplication', 289 abilityName: 'EntryAbility' 290 }; 291 let options: StartOptions = { 292 displayId: 0 293 }; 294 295 try { 296 this.context.startAbility(want, options) 297 .then(() => { 298 // 执行正常业务 299 console.info('startAbility succeed'); 300 }) 301 .catch((err: BusinessError) => { 302 // 处理业务逻辑错误 303 console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); 304 }); 305 } catch (err) { 306 // 处理入参错误异常 307 let code = (err as BusinessError).code; 308 let message = (err as BusinessError).message; 309 console.error(`startAbility failed, code is ${code}, message is ${message}`); 310 } 311 } 312} 313``` 314 315## UIAbilityContext.startAbilityForResult 316 317startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void 318 319启动一个Ability。使用callback异步回调。仅支持在主线程调用。 320 321Ability被启动后,有如下情况: 322 - 正常情况下可通过调用[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)接口使之终止并且返回结果给调用方。 323 - 异常情况下比如杀死Ability会返回异常信息给调用方, 异常信息中resultCode为-1。 324 - 如果被启动的Ability模式是单实例模式, 不同应用多次调用该接口启动这个Ability,当这个Ability调用[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)接口使之终止时,只将正常结果返回给最后一个调用方, 其它调用方返回异常信息, 异常信息中resultCode为-1。 325 326> **说明:** 327> 328> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。 329 330**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 331 332**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 333 334**参数:** 335 336| 参数名 | 类型 | 必填 | 说明 | 337| -------- | -------- | -------- | -------- | 338| want |[Want](js-apis-app-ability-want.md) | 是 | 启动Ability的want信息。 | 339| callback | AsyncCallback<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | 是 | 执行结果回调函数。 | 340 341**错误码:** 342 343以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 344 345| 错误码ID | 错误信息 | 346| ------- | -------------------------------- | 347| 201 | The application does not have permission to call the interface. | 348| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 349| 16000001 | The specified ability does not exist. | 350| 16000002 | Incorrect ability type. | 351| 16000004 | Failed to start the invisible ability. | 352| 16000005 | The specified process does not have the permission. | 353| 16000006 | Cross-user operations are not allowed. | 354| 16000008 | The crowdtesting application expires. | 355| 16000009 | An ability cannot be started or stopped in Wukong mode. | 356| 16000010 | The call with the continuation and prepare continuation flag is forbidden. | 357| 16000011 | The context does not exist. | 358| 16000012 | The application is controlled. | 359| 16000013 | The application is controlled by EDM. | 360| 16000018 | Redirection to a third-party application is not allowed in API version 11 or later. | 361| 16000019 | No matching ability is found. | 362| 16000050 | Internal error. | 363| 16000053 | The ability is not on the top of the UI. | 364| 16000055 | Installation-free timed out. | 365| 16000071 | App clone is not supported. | 366| 16000072 | App clone or multi-instance is not supported. | 367| 16000073 | The app clone index is invalid. | 368| 16000076 | The app instance key is invalid. | 369| 16000077 | The number of app instances reaches the limit. | 370| 16000078 | The multi-instance is not supported. | 371| 16000079 | The APP_INSTANCE_KEY cannot be specified. | 372| 16000080 | Creating a new instance is not supported. | 373| 16200001 | The caller has been released. | 374 375**示例:** 376 377```ts 378import { UIAbility, Want, common } from '@kit.AbilityKit'; 379import { BusinessError } from '@kit.BasicServicesKit'; 380 381export default class EntryAbility extends UIAbility { 382 onForeground() { 383 let want: Want = { 384 deviceId: '', 385 bundleName: 'com.example.myapplication', 386 abilityName: 'EntryAbility' 387 }; 388 389 try { 390 this.context.startAbilityForResult(want, (err: BusinessError, result: common.AbilityResult) => { 391 if (err.code) { 392 // 处理业务逻辑错误 393 console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`); 394 return; 395 } 396 // 执行正常业务 397 console.info('startAbilityForResult succeed'); 398 }); 399 } catch (err) { 400 // 处理入参错误异常 401 let code = (err as BusinessError).code; 402 let message = (err as BusinessError).message; 403 console.error(`startAbilityForResult failed, code is ${code}, message is ${message}`); 404 } 405 } 406} 407``` 408 409## UIAbilityContext.startAbilityForResult 410 411startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>): void 412 413启动一个Ability。使用callback异步回调。仅支持在主线程调用。 414 415Ability被启动后,有如下情况: 416 - 正常情况下可通过调用[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)接口使之终止并且返回结果给调用方。 417 - 异常情况下比如杀死Ability会返回异常信息给调用方,异常信息中resultCode为-1。 418 - 如果被启动的Ability模式是单实例模式, 不同应用多次调用该接口启动这个Ability,当这个Ability调用[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)接口使之终止时,只将正常结果返回给最后一个调用方,其它调用方返回异常信息, 异常信息中resultCode为-1。 419 420> **说明:** 421> 422> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。 423 424**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 425 426**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 427 428**参数:** 429 430| 参数名 | 类型 | 必填 | 说明 | 431| -------- | -------- | -------- | -------- | 432| want |[Want](js-apis-app-ability-want.md) | 是 | 启动Ability的want信息。 | 433| options | [StartOptions](js-apis-app-ability-startOptions.md) | 是 | 启动Ability所携带的参数。 | 434| callback | AsyncCallback<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | 是 | 执行结果回调函数。 | 435 436**错误码:** 437 438以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 439 440| 错误码ID | 错误信息 | 441| ------- | -------------------------------- | 442| 201 | The application does not have permission to call the interface. | 443| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 444| 16000001 | The specified ability does not exist. | 445| 16000004 | Failed to start the invisible ability. | 446| 16000005 | The specified process does not have the permission. | 447| 16000006 | Cross-user operations are not allowed. | 448| 16000008 | The crowdtesting application expires. | 449| 16000009 | An ability cannot be started or stopped in Wukong mode. | 450| 16000011 | The context does not exist. | 451| 16000012 | The application is controlled. | 452| 16000013 | The application is controlled by EDM. | 453| 16000018 | Redirection to a third-party application is not allowed in API version 11 or later. | 454| 16000019 | No matching ability is found. | 455| 16000050 | Internal error. | 456| 16000053 | The ability is not on the top of the UI. | 457| 16000055 | Installation-free timed out. | 458| 16000071 | App clone is not supported. | 459| 16000072 | App clone or multi-instance is not supported. | 460| 16000073 | The app clone index is invalid. | 461| 16000076 | The app instance key is invalid. | 462| 16000077 | The number of app instances reaches the limit. | 463| 16000078 | The multi-instance is not supported. | 464| 16000079 | The APP_INSTANCE_KEY cannot be specified. | 465| 16000080 | Creating a new instance is not supported. | 466| 16200001 | The caller has been released. | 467 468**示例:** 469 470```ts 471import { UIAbility, Want, common, StartOptions } from '@kit.AbilityKit'; 472import { BusinessError } from '@kit.BasicServicesKit'; 473 474export default class EntryAbility extends UIAbility { 475 onForeground() { 476 let want: Want = { 477 deviceId: '', 478 bundleName: 'com.example.myapplication', 479 abilityName: 'EntryAbility' 480 }; 481 let options: StartOptions = { 482 displayId: 0 483 }; 484 485 try { 486 this.context.startAbilityForResult(want, options, (err: BusinessError, result: common.AbilityResult) => { 487 if (err.code) { 488 // 处理业务逻辑错误 489 console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`); 490 return; 491 } 492 // 执行正常业务 493 console.info('startAbilityForResult succeed'); 494 }); 495 } catch (err) { 496 // 处理入参错误异常 497 let code = (err as BusinessError).code; 498 let message = (err as BusinessError).message; 499 console.error(`startAbilityForResult failed, code is ${code}, message is ${message}`); 500 } 501 } 502} 503``` 504 505 506## UIAbilityContext.startAbilityForResult 507 508startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityResult> 509 510启动一个Ability。使用Promise异步回调。仅支持在主线程调用。 511 512Ability被启动后,有如下情况: 513 - 正常情况下可通过调用[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)接口使之终止并且返回结果给调用方。 514 - 异常情况下比如杀死Ability会返回异常信息给调用方, 异常信息中resultCode为-1。 515 - 如果被启动的Ability模式是单实例模式, 不同应用多次调用该接口启动这个Ability,当这个Ability调用[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)接口使之终止时,只将正常结果返回给最后一个调用方, 其它调用方返回异常信息, 异常信息中resultCode为-1。 516 517> **说明:** 518> 519> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。 520 521**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 522 523**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 524 525**参数:** 526 527| 参数名 | 类型 | 必填 | 说明 | 528| -------- | -------- | -------- | -------- | 529| want | [Want](js-apis-app-ability-want.md) | 是 | 启动Ability的want信息。 | 530| options | [StartOptions](js-apis-app-ability-startOptions.md) | 否 | 启动Ability所携带的参数。 | 531 532 533**返回值:** 534 535| 类型 | 说明 | 536| -------- | -------- | 537| Promise<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Promise形式返回执行结果。 | 538 539**错误码:** 540 541以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 542 543| 错误码ID | 错误信息 | 544| ------- | -------------------------------- | 545| 201 | The application does not have permission to call the interface. | 546| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 547| 16000001 | The specified ability does not exist. | 548| 16000002 | Incorrect ability type. | 549| 16000004 | Failed to start the invisible ability. | 550| 16000005 | The specified process does not have the permission. | 551| 16000006 | Cross-user operations are not allowed. | 552| 16000008 | The crowdtesting application expires. | 553| 16000009 | An ability cannot be started or stopped in Wukong mode. | 554| 16000010 | The call with the continuation and prepare continuation flag is forbidden. | 555| 16000011 | The context does not exist. | 556| 16000012 | The application is controlled. | 557| 16000013 | The application is controlled by EDM. | 558| 16000018 | Redirection to a third-party application is not allowed in API version 11 or later. | 559| 16000019 | No matching ability is found. | 560| 16000050 | Internal error. | 561| 16000053 | The ability is not on the top of the UI. | 562| 16000055 | Installation-free timed out. | 563| 16000071 | App clone is not supported. | 564| 16000072 | App clone or multi-instance is not supported. | 565| 16000073 | The app clone index is invalid. | 566| 16000076 | The app instance key is invalid. | 567| 16000077 | The number of app instances reaches the limit. | 568| 16000078 | The multi-instance is not supported. | 569| 16000079 | The APP_INSTANCE_KEY cannot be specified. | 570| 16000080 | Creating a new instance is not supported. | 571| 16200001 | The caller has been released. | 572 573**示例:** 574 575```ts 576import { UIAbility, Want, common, StartOptions } from '@kit.AbilityKit'; 577import { BusinessError } from '@kit.BasicServicesKit'; 578 579export default class EntryAbility extends UIAbility { 580 onForeground() { 581 let want: Want = { 582 bundleName: 'com.example.myapplication', 583 abilityName: 'EntryAbility' 584 }; 585 let options: StartOptions = { 586 displayId: 0 587 }; 588 589 try { 590 this.context.startAbilityForResult(want, options) 591 .then((result: common.AbilityResult) => { 592 // 执行正常业务 593 console.info('startAbilityForResult succeed'); 594 }) 595 .catch((err: BusinessError) => { 596 // 处理业务逻辑错误 597 console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`); 598 }); 599 } catch (err) { 600 // 处理入参错误异常 601 let code = (err as BusinessError).code; 602 let message = (err as BusinessError).message; 603 console.error(`startAbilityForResult failed, code is ${code}, message is ${message}`); 604 } 605 } 606} 607``` 608 609## UIAbilityContext.terminateSelf 610 611terminateSelf(callback: AsyncCallback<void>): void 612 613停止Ability自身。使用callback异步回调。仅支持在主线程调用。 614 615> **说明:** 616> 617> 调用该接口后,任务中心的任务默认不会清理,如需清理,需要配置[removeMissionAfterTerminate](../../quick-start/module-configuration-file.md#abilities标签)为true。 618 619**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 620 621**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 622 623**参数:** 624 625| 参数名 | 类型 | 必填 | 说明 | 626| -------- | -------- | -------- | -------- | 627| callback | AsyncCallback<void> | 是 | 停止Ability自身的回调函数。 | 628 629**错误码:** 630 631以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 632 633| 错误码ID | 错误信息 | 634| ------- | -------------------------------- | 635| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 636| 16000009 | An ability cannot be started or stopped in Wukong mode. | 637| 16000011 | The context does not exist. | 638| 16000050 | Internal error. | 639 640**示例:** 641 642```ts 643import { UIAbility } from '@kit.AbilityKit'; 644import { BusinessError } from '@kit.BasicServicesKit'; 645 646export default class EntryAbility extends UIAbility { 647 onForeground() { 648 try { 649 this.context.terminateSelf((err: BusinessError) => { 650 if (err.code) { 651 // 处理业务逻辑错误 652 console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`); 653 return; 654 } 655 // 执行正常业务 656 console.info('terminateSelf succeed'); 657 }); 658 } catch (err) { 659 // 捕获同步的参数错误 660 let code = (err as BusinessError).code; 661 let message = (err as BusinessError).message; 662 console.error(`terminateSelf failed, code is ${code}, message is ${message}`); 663 } 664 } 665} 666``` 667 668 669## UIAbilityContext.terminateSelf 670 671terminateSelf(): Promise<void> 672 673停止Ability自身。使用Promise异步回调。仅支持在主线程调用。 674 675> **说明:** 676> 677> 调用该接口后,任务中心的任务默认不会清理,如需清理,需要配置[removeMissionAfterTerminate](../../quick-start/module-configuration-file.md#abilities标签)为true。 678 679**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 680 681**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 682 683**返回值:** 684 685| 类型 | 说明 | 686| -------- | -------- | 687| Promise<void> | 停止Ability自身的回调函数。 | 688 689**错误码:** 690 691以下错误码详细介绍请参考[元能力子系统错误码](errorcode-ability.md)。 692 693| 错误码ID | 错误信息 | 694| ------- | -------------------------------- | 695| 16000009 | An ability cannot be started or stopped in Wukong mode. | 696| 16000011 | The context does not exist. | 697| 16000050 | Internal error. | 698 699 700**示例:** 701 702```ts 703import { UIAbility } from '@kit.AbilityKit'; 704import { BusinessError } from '@kit.BasicServicesKit'; 705 706export default class EntryAbility extends UIAbility { 707 onForeground() { 708 try { 709 this.context.terminateSelf() 710 .then(() => { 711 // 执行正常业务 712 console.info('terminateSelf succeed'); 713 }) 714 .catch((err: BusinessError) => { 715 // 处理业务逻辑错误 716 console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`); 717 }); 718 } catch (err) { 719 // 捕获同步的参数错误 720 let code = (err as BusinessError).code; 721 let message = (err as BusinessError).message; 722 console.error(`terminateSelf failed, code is ${code}, message is ${message}`); 723 } 724 } 725} 726``` 727 728 729## UIAbilityContext.terminateSelfWithResult 730 731terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>): void 732 733停止当前的Ability。使用callback异步回调。仅支持在主线程调用。 734 735如果该Ability是通过调用[startAbilityForResult](#uiabilitycontextstartabilityforresult)接口被拉起的,调用terminateSelfWithResult接口时会将结果返回给调用者,如果该Ability不是通过调用[startAbilityForResult](#uiabilitycontextstartabilityforresult)接口被拉起的,调用terminateSelfWithResult接口时不会有结果返回给调用者。 736 737> **说明:** 738> 739> 调用该接口后,任务中心的任务默认不会清理,如需清理,需要配置[removeMissionAfterTerminate](../../quick-start/module-configuration-file.md#abilities标签)为true。 740 741**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 742 743**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 744 745**参数:** 746 747| 参数名 | 类型 | 必填 | 说明 | 748| -------- | -------- | -------- | -------- | 749| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | 是 | 返回给调用startAbilityForResult 接口调用方的相关信息。 | 750| callback | AsyncCallback<void> | 是 | callback形式返回停止结果。 | 751 752**错误码:** 753 754以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 755 756| 错误码ID | 错误信息 | 757| ------- | -------------------------------- | 758| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 759| 16000009 | An ability cannot be started or stopped in Wukong mode. | 760| 16000011 | The context does not exist. | 761| 16000050 | Internal error. | 762 763 764**示例:** 765 766```ts 767import { UIAbility, Want, common } from '@kit.AbilityKit'; 768import { BusinessError } from '@kit.BasicServicesKit'; 769 770export default class EntryAbility extends UIAbility { 771 onForeground() { 772 let want: Want = { 773 bundleName: 'com.example.myapplication', 774 abilityName: 'EntryAbility' 775 }; 776 let resultCode = 100; 777 // 返回给接口调用方AbilityResult信息 778 let abilityResult: common.AbilityResult = { 779 want, 780 resultCode 781 }; 782 783 try { 784 this.context.terminateSelfWithResult(abilityResult, (err: BusinessError) => { 785 if (err.code) { 786 // 处理业务逻辑错误 787 console.error(`terminateSelfWithResult failed, code is ${err.code}, message is ${err.message}`); 788 return; 789 } 790 // 执行正常业务 791 console.info('terminateSelfWithResult succeed'); 792 }); 793 } catch (err) { 794 // 处理入参错误异常 795 let code = (err as BusinessError).code; 796 let message = (err as BusinessError).message; 797 console.error(`terminateSelfWithResult failed, code is ${code}, message is ${message}`); 798 } 799 } 800} 801``` 802 803 804## UIAbilityContext.terminateSelfWithResult 805 806terminateSelfWithResult(parameter: AbilityResult): Promise<void> 807 808停止当前的Ability。使用Promise异步回调。仅支持在主线程调用。 809 810如果该Ability是通过调用[startAbilityForResult](#uiabilitycontextstartabilityforresult)接口被拉起的,调用terminateSelfWithResult接口时会将结果返回给调用者,如果该Ability不是通过调用[startAbilityForResult](#uiabilitycontextstartabilityforresult)接口被拉起的,调用terminateSelfWithResult接口时不会有结果返回给调用者。 811 812> **说明:** 813> 814> 调用该接口后,任务中心的任务默认不会清理,如需清理,需要配置[removeMissionAfterTerminate](../../quick-start/module-configuration-file.md#abilities标签)为true。 815 816**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 817 818**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 819 820**参数:** 821 822| 参数名 | 类型 | 必填 | 说明 | 823| -------- | -------- | -------- | -------- | 824| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | 是 | 返回给startAbilityForResult 调用方的信息。 | 825 826**返回值:** 827 828| 类型 | 说明 | 829| -------- | -------- | 830| Promise<void> | promise形式返回停止结果。 | 831 832**错误码:** 833 834以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 835 836| 错误码ID | 错误信息 | 837| ------- | -------------------------------- | 838| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 839| 16000009 | An ability cannot be started or stopped in Wukong mode. | 840| 16000011 | The context does not exist. | 841| 16000050 | Internal error. | 842 843 844**示例:** 845 846```ts 847import { UIAbility, Want, common } from '@kit.AbilityKit'; 848import { BusinessError } from '@kit.BasicServicesKit'; 849 850export default class EntryAbility extends UIAbility { 851 onForeground() { 852 let want: Want = { 853 bundleName: 'com.example.myapplication', 854 abilityName: 'EntryAbility' 855 }; 856 let resultCode = 100; 857 // 返回给接口调用方AbilityResult信息 858 let abilityResult: common.AbilityResult = { 859 want, 860 resultCode 861 }; 862 863 try { 864 this.context.terminateSelfWithResult(abilityResult) 865 .then(() => { 866 // 执行正常业务 867 console.info('terminateSelfWithResult succeed'); 868 }) 869 .catch((err: BusinessError) => { 870 // 处理业务逻辑错误 871 console.error(`terminateSelfWithResult failed, code is ${err.code}, message is ${err.message}`); 872 }); 873 } catch (err) { 874 // 处理入参错误异常 875 let code = (err as BusinessError).code; 876 let message = (err as BusinessError).message; 877 console.error(`terminateSelfWithResult failed, code is ${code}, message is ${message}`); 878 } 879 } 880} 881``` 882 883## UIAbilityContext.connectServiceExtensionAbility 884 885connectServiceExtensionAbility(want: Want, options: ConnectOptions): number 886 887将当前Ability连接到一个ServiceExtensionAbility。仅支持在主线程调用。 888 889> **说明:** 890> 891> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。 892 893**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 894 895**参数:** 896 897| 参数名 | 类型 | 必填 | 说明 | 898| -------- | -------- | -------- | -------- | 899| want | [Want](js-apis-app-ability-want.md) | 是 | 连接ServiceExtensionAbility的want信息。 | 900| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | 是 | 与ServiceExtensionAbility建立连接后回调函数的实例。 | 901 902**返回值:** 903 904| 类型 | 说明 | 905| -------- | -------- | 906| number | 返回Ability连接的结果code。 | 907 908**错误码:** 909 910以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 911 912| 错误码ID | 错误信息 | 913| ------- | -------------------------------- | 914| 201 | The application does not have permission to call the interface. | 915| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 916| 16000001 | The specified ability does not exist. | 917| 16000002 | Incorrect ability type. | 918| 16000004 | Failed to start the invisible ability. | 919| 16000005 | The specified process does not have the permission. | 920| 16000006 | Cross-user operations are not allowed. | 921| 16000008 | The crowdtesting application expires. | 922| 16000011 | The context does not exist. | 923| 16000050 | Internal error. | 924| 16000053 | The ability is not on the top of the UI. | 925| 16000055 | Installation-free timed out. | 926 927**示例:** 928 929```ts 930import { UIAbility, Want, common } from '@kit.AbilityKit'; 931import { rpc } from '@kit.IPCKit'; 932import { BusinessError } from '@kit.BasicServicesKit'; 933 934export default class EntryAbility extends UIAbility { 935 onForeground() { 936 let want: Want = { 937 deviceId: '', 938 bundleName: 'com.example.myapplication', 939 abilityName: 'ServiceExtensionAbility' 940 }; 941 let commRemote: rpc.IRemoteObject; 942 let options: common.ConnectOptions = { 943 onConnect(elementName, remote) { 944 commRemote = remote; 945 console.info('onConnect...'); 946 }, 947 onDisconnect(elementName) { 948 console.info('onDisconnect...'); 949 }, 950 onFailed(code) { 951 console.info('onFailed...'); 952 } 953 }; 954 let connection: number; 955 956 try { 957 connection = this.context.connectServiceExtensionAbility(want, options); 958 } catch (err) { 959 // 处理入参错误异常 960 let code = (err as BusinessError).code; 961 let message = (err as BusinessError).message; 962 console.error(`connectServiceExtensionAbility failed, code is ${code}, message is ${message}`); 963 } 964 } 965} 966``` 967 968## UIAbilityContext.disconnectServiceExtensionAbility 969 970disconnectServiceExtensionAbility(connection: number): Promise\<void> 971 972断开与ServiceExtensionAbility的连接,断开连接之后需要将连接成功时返回的remote对象置空。使用Promise异步回调。仅支持在主线程调用。 973 974**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 975 976**参数:** 977 978| 参数名 | 类型 | 必填 | 说明 | 979| -------- | -------- | -------- | -------- | 980| connection | number | 是 | 连接的ServiceExtensionAbility的数字代码,即connectServiceExtensionAbility返回的connectionId。 | 981 982**返回值:** 983 984| 类型 | 说明 | 985| -------- | -------- | 986| Promise\<void> | 返回执行结果。 | 987 988**错误码:** 989 990以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 991 992| 错误码ID | 错误信息 | 993| ------- | -------------------------------- | 994| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 995| 16000011 | The context does not exist. | 996| 16000050 | Internal error. | 997 998**示例:** 999 1000```ts 1001import { UIAbility } from '@kit.AbilityKit'; 1002import { rpc } from '@kit.IPCKit'; 1003import { BusinessError } from '@kit.BasicServicesKit'; 1004 1005export default class EntryAbility extends UIAbility { 1006 onForeground() { 1007 // connection为connectServiceExtensionAbility中的返回值 1008 let connection = 1; 1009 let commRemote: rpc.IRemoteObject | null; 1010 1011 try { 1012 this.context.disconnectServiceExtensionAbility(connection).then(() => { 1013 commRemote = null; 1014 // 执行正常业务 1015 console.info('disconnectServiceExtensionAbility succeed'); 1016 }).catch((err: BusinessError) => { 1017 // 处理业务逻辑错误 1018 console.error(`disconnectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); 1019 }); 1020 } catch (err) { 1021 commRemote = null; 1022 // 处理入参错误异常 1023 let code = (err as BusinessError).code; 1024 let message = (err as BusinessError).message; 1025 console.error(`disconnectServiceExtensionAbility failed, code is ${code}, message is ${message}`); 1026 } 1027 } 1028} 1029``` 1030 1031## UIAbilityContext.disconnectServiceExtensionAbility 1032 1033disconnectServiceExtensionAbility(connection: number, callback: AsyncCallback\<void>): void 1034 1035断开与ServiceExtensionAbility的连接,断开连接之后需要将连接成功时返回的remote对象置空。使用callback异步回调。仅支持在主线程调用。 1036 1037**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 1038 1039**参数:** 1040 1041| 参数名 | 类型 | 必填 | 说明 | 1042| -------- | -------- | -------- | -------- | 1043| connection | number | 是 | 连接的ServiceExtensionAbility的数字代码,即connectServiceExtensionAbility返回的connectionId。 | 1044| callback | AsyncCallback\<void> | 是 | callback形式返回断开连接的结果。 | 1045 1046**错误码:** 1047 1048以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 1049 1050| 错误码ID | 错误信息 | 1051| ------- | -------------------------------- | 1052| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 1053| 16000011 | The context does not exist. | 1054| 16000050 | Internal error. | 1055 1056**示例:** 1057 1058```ts 1059import { UIAbility } from '@kit.AbilityKit'; 1060import { rpc } from '@kit.IPCKit'; 1061import { BusinessError } from '@kit.BasicServicesKit'; 1062 1063export default class EntryAbility extends UIAbility { 1064 onForeground() { 1065 // connection为connectServiceExtensionAbility中的返回值 1066 let connection = 1; 1067 let commRemote: rpc.IRemoteObject | null; 1068 1069 try { 1070 this.context.disconnectServiceExtensionAbility(connection, (err: BusinessError) => { 1071 commRemote = null; 1072 if (err.code) { 1073 // 处理业务逻辑错误 1074 console.error(`disconnectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); 1075 return; 1076 } 1077 // 执行正常业务 1078 console.info('disconnectServiceExtensionAbility succeed'); 1079 }); 1080 } catch (err) { 1081 commRemote = null; 1082 // 处理入参错误异常 1083 let code = (err as BusinessError).code; 1084 let message = (err as BusinessError).message; 1085 console.error(`disconnectServiceExtensionAbility failed, code is ${code}, message is ${message}`); 1086 } 1087 } 1088} 1089``` 1090 1091## UIAbilityContext.startAbilityByCall 1092 1093startAbilityByCall(want: Want): Promise<Caller> 1094 1095启动指定Ability至前台或后台,同时获取其Caller通信接口,调用方可使用Caller与被启动的Ability进行通信。使用Promise异步回调。仅支持在主线程调用。 1096该接口不支持拉起启动模式为[specified模式](../../application-models/uiability-launch-type.md#specified启动模式)的UIAbility。 1097 1098> **说明:** 1099> 1100> - 跨设备场景下,调用方与目标方必须为同一应用,且具备ohos.permission.DISTRIBUTED_DATASYNC权限,才能启动成功。 1101> 1102> - 同设备场景下,调用方与目标方必须为不同应用,且具备ohos.permission.ABILITY_BACKGROUND_COMMUNICATION权限(该权限仅系统应用可申请),才能启动成功。 1103> 1104> - 如果调用方位于后台,还需要具备ohos.permission.START_ABILITIES_FROM_BACKGROUND(该权限仅系统应用可申请)。更多的组件启动规则详见[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。 1105 1106**需要权限**:ohos.permission.DISTRIBUTED_DATASYNC 1107 1108> **说明:** 1109> 1110> API version 11之前的版本,该接口需要申请权限ohos.permission.ABILITY_BACKGROUND_COMMUNICATION(该权限仅系统应用可申请)。从API version 11开始,该接口需要申请的权限变更为ohos.permission.DISTRIBUTED_DATASYNC权限。 1111 1112**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 1113 1114**参数:** 1115 1116| 参数名 | 类型 | 必填 | 说明 | 1117| -------- | -------- | -------- | -------- | 1118| want | [Want](js-apis-app-ability-want.md) | 是 | 传入需要启动的Ability的信息,包含abilityName、moduleName、bundleName、deviceId、parameters(可选),parameters缺省或为空表示后台启动Ability。 | 1119 1120**返回值:** 1121 1122| 类型 | 说明 | 1123| -------- | -------- | 1124| Promise<[Caller](js-apis-app-ability-uiAbility.md#caller)> | 获取要通讯的caller对象。 | 1125 1126**错误码:** 1127 1128以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 1129 1130| 错误码ID | 错误信息 | 1131| ------- | -------------------------------- | 1132| 201 | The application does not have permission to call the interface. | 1133| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 1134| 16000001 | The specified ability does not exist. | 1135| 16000002 | Incorrect ability type. | 1136| 16000004 | Failed to start the invisible ability. | 1137| 16000006 | Cross-user operations are not allowed. | 1138| 16000008 | The crowdtesting application expires. | 1139| 16000011 | The context does not exist. | 1140| 16000012 | The application is controlled. | 1141| 16000013 | The application is controlled by EDM. | 1142| 16000018 | Redirection to a third-party application is not allowed in API version 11 or later. | 1143| 16000050 | Internal error. | 1144| 16000071 | App clone is not supported. | 1145| 16000072 | App clone or multi-instance is not supported. | 1146| 16000073 | The app clone index is invalid. | 1147| 16000076 | The app instance key is invalid. | 1148| 16000077 | The number of app instances reaches the limit. | 1149| 16000078 | The multi-instance is not supported. | 1150| 16000079 | The APP_INSTANCE_KEY cannot be specified. | 1151| 16000080 | Creating a new instance is not supported. | 1152 1153**示例:** 1154 1155后台启动: 1156 1157```ts 1158import { UIAbility, Caller, Want } from '@kit.AbilityKit'; 1159import { BusinessError } from '@kit.BasicServicesKit'; 1160 1161export default class EntryAbility extends UIAbility { 1162 onForeground() { 1163 let caller: Caller; 1164 // 后台启动Ability,不配置parameters 1165 let wantBackground: Want = { 1166 bundleName: 'com.example.myapplication', 1167 moduleName: 'entry', 1168 abilityName: 'EntryAbility', 1169 deviceId: '' 1170 }; 1171 1172 try { 1173 this.context.startAbilityByCall(wantBackground) 1174 .then((obj: Caller) => { 1175 // 执行正常业务 1176 caller = obj; 1177 console.info('startAbilityByCall succeed'); 1178 }).catch((err: BusinessError) => { 1179 // 处理业务逻辑错误 1180 console.error(`startAbilityByCall failed, code is ${err.code}, message is ${err.message}`); 1181 }); 1182 } catch (err) { 1183 // 处理入参错误异常 1184 let code = (err as BusinessError).code; 1185 let message = (err as BusinessError).message; 1186 console.error(`startAbilityByCall failed, code is ${code}, message is ${message}`); 1187 } 1188 } 1189} 1190``` 1191 1192前台启动: 1193 1194```ts 1195import { UIAbility, Caller, Want } from '@kit.AbilityKit'; 1196import { BusinessError } from '@kit.BasicServicesKit'; 1197 1198export default class EntryAbility extends UIAbility { 1199 onForeground() { 1200 let caller: Caller; 1201 // 前台启动Ability,将parameters中的'ohos.aafwk.param.callAbilityToForeground'配置为true 1202 let wantForeground: Want = { 1203 bundleName: 'com.example.myapplication', 1204 moduleName: 'entry', 1205 abilityName: 'EntryAbility', 1206 deviceId: '', 1207 parameters: { 1208 'ohos.aafwk.param.callAbilityToForeground': true 1209 } 1210 }; 1211 1212 try { 1213 this.context.startAbilityByCall(wantForeground) 1214 .then((obj: Caller) => { 1215 // 执行正常业务 1216 caller = obj; 1217 console.info('startAbilityByCall succeed'); 1218 }).catch((err: BusinessError) => { 1219 // 处理业务逻辑错误 1220 console.error(`startAbilityByCall failed, code is ${err.code}, message is ${err.message}`); 1221 }); 1222 } catch (err) { 1223 // 处理入参错误异常 1224 let code = (err as BusinessError).code; 1225 let message = (err as BusinessError).message; 1226 console.error(`startAbilityByCall failed, code is ${code}, message is ${message}`); 1227 } 1228 } 1229} 1230``` 1231 1232## UIAbilityContext.setMissionLabel 1233 1234setMissionLabel(label: string, callback: AsyncCallback<void>): void 1235 1236设置UIAbility在任务中显示的名称。使用callback异步回调。 1237 1238**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1239 1240**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 1241 1242**参数:** 1243 1244| 参数名 | 类型 | 必填 | 说明 | 1245| -------- | -------- | -------- | -------- | 1246| label | string | 是 | 显示名称。 | 1247| callback | AsyncCallback<void> | 是 | 回调函数,返回接口调用是否成功的结果。 | 1248 1249**错误码:** 1250 1251以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 1252 1253| 错误码ID | 错误信息 | 1254| ------- | -------------------------------- | 1255| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 1256| 16000011 | The context does not exist. | 1257| 16000050 | Internal error. | 1258 1259**示例:** 1260 1261```ts 1262import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit'; 1263import { BusinessError } from '@kit.BasicServicesKit'; 1264 1265export default class EntryAbility extends UIAbility { 1266 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 1267 this.context.setMissionLabel('test', (result: BusinessError) => { 1268 console.info(`setMissionLabel: ${JSON.stringify(result)}`); 1269 }); 1270 } 1271} 1272``` 1273 1274## UIAbilityContext.setMissionLabel 1275 1276setMissionLabel(label: string): Promise<void> 1277 1278设置UIAbility在任务中显示的名称。使用Promise异步回调。 1279 1280**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1281 1282**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 1283 1284**参数:** 1285 1286| 参数名 | 类型 | 必填 | 说明 | 1287| -------- | -------- | -------- | -------- | 1288| label | string | 是 | 显示名称。 | 1289 1290**返回值:** 1291 1292| 类型 | 说明 | 1293| -------- | -------- | 1294| Promise<void> | 返回一个Promise,包含接口的结果。 | 1295 1296**错误码:** 1297 1298以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 1299 1300| 错误码ID | 错误信息 | 1301| ------- | -------------------------------- | 1302| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 1303| 16000011 | The context does not exist. | 1304| 16000050 | Internal error. | 1305 1306**示例:** 1307 1308```ts 1309import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit'; 1310import { BusinessError } from '@kit.BasicServicesKit'; 1311 1312export default class EntryAbility extends UIAbility { 1313 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 1314 this.context.setMissionLabel('test').then(() => { 1315 console.info('success'); 1316 }).catch((err: BusinessError) => { 1317 let code = (err as BusinessError).code; 1318 let message = (err as BusinessError).message; 1319 console.error(`setMissionLabel failed, code is ${code}, message is ${message}`); 1320 }); 1321 } 1322} 1323``` 1324 1325## UIAbilityContext.setMissionContinueState<sup>10+</sup> 1326 1327setMissionContinueState(state: AbilityConstant.ContinueState, callback: AsyncCallback<void>): void 1328 1329设置UIAbility任务中流转状态。使用callback异步回调。 1330 1331**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1332 1333**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 1334 1335**参数:** 1336 1337| 参数名 | 类型 | 必填 | 说明 | 1338| -------- | -------- | -------- | -------- | 1339| state | [AbilityConstant.ContinueState](js-apis-app-ability-abilityConstant.md#continuestate10) | 是 | 流转状态。 | 1340| callback | AsyncCallback<void> | 是 | 回调函数,返回接口调用是否成功的结果。 | 1341 1342**错误码:** 1343 1344错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 1345 1346| 错误码ID | 错误信息 | 1347| ------- | -------------------------------- | 1348| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 1349| 16000011 | The context does not exist. | 1350| 16000050 | Internal error. | 1351 1352**示例:** 1353 1354```ts 1355import { UIAbility, AbilityConstant } from '@kit.AbilityKit'; 1356import { BusinessError } from '@kit.BasicServicesKit'; 1357 1358export default class EntryAbility extends UIAbility { 1359 onForeground() { 1360 this.context.setMissionContinueState(AbilityConstant.ContinueState.INACTIVE, (result: BusinessError) => { 1361 console.info(`setMissionContinueState: ${JSON.stringify(result)}`); 1362 }); 1363 } 1364} 1365``` 1366 1367## UIAbilityContext.setMissionContinueState<sup>10+</sup> 1368 1369setMissionContinueState(state: AbilityConstant.ContinueState): Promise<void> 1370 1371设置UIAbility任务中流转状态。使用Promise异步回调。 1372 1373**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1374 1375**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 1376 1377**参数:** 1378 1379| 参数名 | 类型 | 必填 | 说明 | 1380| -------- | -------- | -------- | -------- | 1381| state | [AbilityConstant.ContinueState](js-apis-app-ability-abilityConstant.md#continuestate10) | 是 | 流转状态。 | 1382 1383**返回值:** 1384 1385| 类型 | 说明 | 1386| -------- | -------- | 1387| Promise<void> | 返回一个Promise,包含接口的结果。 | 1388 1389**错误码:** 1390 1391错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 1392 1393| 错误码ID | 错误信息 | 1394| ------- | -------------------------------- | 1395| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 1396| 16000011 | The context does not exist. | 1397| 16000050 | Internal error. | 1398 1399**示例:** 1400 1401```ts 1402import { UIAbility, AbilityConstant } from '@kit.AbilityKit'; 1403import { BusinessError } from '@kit.BasicServicesKit'; 1404 1405export default class EntryAbility extends UIAbility { 1406 onForeground() { 1407 this.context.setMissionContinueState(AbilityConstant.ContinueState.INACTIVE).then(() => { 1408 console.info('success'); 1409 }).catch((err: BusinessError) => { 1410 console.error(`setMissionContinueState failed, code is ${err.code}, message is ${err.message}`); 1411 }); 1412 } 1413} 1414``` 1415 1416## UIAbilityContext.restoreWindowStage 1417 1418restoreWindowStage(localStorage: LocalStorage): void 1419 1420恢复UIAbility中的WindowStage数据。仅支持在主线程调用。 1421 1422**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1423 1424**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 1425 1426**参数:** 1427 1428| 参数名 | 类型 | 必填 | 说明 | 1429| -------- | -------- | -------- | -------- | 1430| localStorage | LocalStorage | 是 | 用于恢复window stage的存储数据。 | 1431 1432**错误码:** 1433 1434以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 1435 1436| 错误码ID | 错误信息 | 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**示例:** 1443 1444```ts 1445import { UIAbility } from '@kit.AbilityKit'; 1446 1447export default class EntryAbility extends UIAbility { 1448 onForeground() { 1449 let storage = new LocalStorage(); 1450 this.context.restoreWindowStage(storage); 1451 } 1452} 1453``` 1454 1455## UIAbilityContext.isTerminating 1456 1457isTerminating(): boolean 1458 1459查询UIAbility是否在terminating状态。 1460 1461**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1462 1463**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 1464 1465**返回值:** 1466 1467| 类型 | 说明 | 1468| -------- | -------- | 1469| boolean | true:ability当前处于terminating状态;false:不处于terminating状态。 | 1470 1471**错误码:** 1472 1473以下错误码详细介绍请参考[元能力子系统错误码](errorcode-ability.md)。 1474 1475| 错误码ID | 错误信息 | 1476| ------- | -------------------------------- | 1477| 16000011 | The context does not exist. | 1478 1479**示例:** 1480 1481```ts 1482import { UIAbility } from '@kit.AbilityKit'; 1483 1484export default class EntryAbility extends UIAbility { 1485 onForeground() { 1486 let isTerminating: boolean = this.context.isTerminating(); 1487 console.info(`ability state is ${isTerminating}`); 1488 } 1489} 1490``` 1491 1492## UIAbilityContext.requestDialogService 1493 1494requestDialogService(want: Want, result: AsyncCallback<dialogRequest.RequestResult>): void 1495 1496启动一个支持模态弹框的ServiceExtensionAbility。ServiceExtensionAbility被启动后,应用弹出模态弹框,通过调用[setRequestResult](js-apis-app-ability-dialogRequest.md#requestcallbacksetrequestresult)接口返回结果给调用者。使用callback异步回调。仅支持在主线程调用。 1497 1498> **说明:** 1499> 1500> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。 1501 1502**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 1503 1504**参数:** 1505 1506| 参数名 | 类型 | 必填 | 说明 | 1507| -------- | -------- | -------- | -------- | 1508| want |[Want](js-apis-app-ability-want.md) | 是 | 启动ServiceExtensionAbility的want信息。 | 1509| result | AsyncCallback<[dialogRequest.RequestResult](js-apis-app-ability-dialogRequest.md#requestresult)> | 是 | 执行结果回调函数。 | 1510 1511**错误码:** 1512 1513以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 1514 1515| 错误码ID | 错误信息 | 1516| ------- | -------------------------------- | 1517| 201 | The application does not have permission to call the interface. | 1518| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 1519| 16000001 | The specified ability does not exist. | 1520| 16000002 | Incorrect ability type. | 1521| 16000004 | Failed to start the invisible ability. | 1522| 16000005 | The specified process does not have the permission. | 1523| 16000006 | Cross-user operations are not allowed. | 1524| 16000008 | The crowdtesting application expires. | 1525| 16000009 | An ability cannot be started or stopped in Wukong mode. | 1526| 16000010 | The call with the continuation and prepare continuation flag is forbidden. | 1527| 16000011 | The context does not exist. | 1528| 16000012 | The application is controlled. | 1529| 16000013 | The application is controlled by EDM. | 1530| 16000050 | Internal error. | 1531| 16000053 | The ability is not on the top of the UI. | 1532| 16000055 | Installation-free timed out. | 1533| 16200001 | The caller has been released. | 1534 1535**示例:** 1536 1537```ts 1538import { UIAbility, Want, dialogRequest } from '@kit.AbilityKit'; 1539import { BusinessError } from '@kit.BasicServicesKit'; 1540 1541export default class EntryAbility extends UIAbility { 1542 onForeground() { 1543 let want: Want = { 1544 deviceId: '', 1545 bundleName: 'com.example.myapplication', 1546 abilityName: 'AuthAccountServiceExtension' 1547 }; 1548 1549 try { 1550 this.context.requestDialogService(want, (err: BusinessError, result: dialogRequest.RequestResult) => { 1551 if (err.code) { 1552 // 处理业务逻辑错误 1553 console.error(`requestDialogService failed, code is ${err.code}, message is ${err.message}`); 1554 return; 1555 } 1556 // 执行正常业务 1557 console.info(`requestDialogService succeed, result = ${JSON.stringify(result)}`); 1558 }); 1559 } catch (err) { 1560 // 处理入参错误异常 1561 let code = (err as BusinessError).code; 1562 let message = (err as BusinessError).message; 1563 console.error(`requestDialogService failed, code is ${code}, message is ${message}`); 1564 } 1565 } 1566} 1567``` 1568 1569 ## UIAbilityContext.requestDialogService 1570 1571requestDialogService(want: Want): Promise<dialogRequest.RequestResult> 1572 1573启动一个支持模态弹框的ServiceExtensionAbility。ServiceExtensionAbility被启动后,应用弹出模态弹框,通过调用[setRequestResult](js-apis-app-ability-dialogRequest.md#requestcallbacksetrequestresult)接口返回结果给调用者。使用Promise异步回调。仅支持在主线程调用。 1574 1575> **说明:** 1576> 1577> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。 1578 1579**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 1580 1581**参数:** 1582 1583| 参数名 | 类型 | 必填 | 说明 | 1584| -------- | -------- | -------- | -------- | 1585| want | [Want](js-apis-app-ability-want.md) | 是 | 启动ServiceExtensionAbility的want信息。 | 1586 1587 1588**返回值:** 1589 1590| 类型 | 说明 | 1591| -------- | -------- | 1592| Promise<[dialogRequest.RequestResult](js-apis-app-ability-dialogRequest.md)> | Promise形式返回执行结果。 1593 1594**错误码:** 1595 1596以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 1597 1598| 错误码ID | 错误信息 | 1599| ------- | -------------------------------- | 1600| 201 | The application does not have permission to call the interface. | 1601| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 1602| 16000001 | The specified ability does not exist. | 1603| 16000002 | Incorrect ability type. | 1604| 16000004 | Failed to start the invisible ability. | 1605| 16000005 | The specified process does not have the permission. | 1606| 16000006 | Cross-user operations are not allowed. | 1607| 16000008 | The crowdtesting application expires. | 1608| 16000009 | An ability cannot be started or stopped in Wukong mode. | 1609| 16000010 | The call with the continuation and prepare continuation flag is forbidden. | 1610| 16000011 | The context does not exist. | 1611| 16000012 | The application is controlled. | 1612| 16000013 | The application is controlled by EDM. | 1613| 16000050 | Internal error. | 1614| 16000053 | The ability is not on the top of the UI. | 1615| 16000055 | Installation-free timed out. | 1616| 16200001 | The caller has been released. | 1617 1618**示例:** 1619 1620```ts 1621import { UIAbility, Want, dialogRequest } from '@kit.AbilityKit'; 1622import { BusinessError } from '@kit.BasicServicesKit'; 1623 1624export default class EntryAbility extends UIAbility { 1625 onForeground() { 1626 let want: Want = { 1627 bundleName: 'com.example.myapplication', 1628 abilityName: 'AuthAccountServiceExtension' 1629 }; 1630 1631 try { 1632 this.context.requestDialogService(want) 1633 .then((result: dialogRequest.RequestResult) => { 1634 // 执行正常业务 1635 console.info(`requestDialogService succeed, result = ${JSON.stringify(result)}`); 1636 }) 1637 .catch((err: BusinessError) => { 1638 // 处理业务逻辑错误 1639 console.error(`requestDialogService failed, code is ${err.code}, message is ${err.message}`); 1640 }); 1641 } catch (err) { 1642 // 处理入参错误异常 1643 let code = (err as BusinessError).code; 1644 let message = (err as BusinessError).message; 1645 console.error(`requestDialogService failed, code is ${code}, message is ${message}`); 1646 } 1647 } 1648} 1649``` 1650 1651## UIAbilityContext.reportDrawnCompleted<sup>10+</sup> 1652 1653reportDrawnCompleted(callback: AsyncCallback\<void>): void 1654 1655当页面加载完成(loadContent成功)时,为开发者提供打点功能。使用callback异步回调。 1656 1657**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1658 1659**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 1660 1661**参数:** 1662 1663| 参数名 | 类型 | 必填 | 说明 | 1664| -------- | -------- | -------- | -------- | 1665| callback | AsyncCallback<void> | 是 | 页面加载完成打点的回调函数。 | 1666 1667**错误码:** 1668 1669以下错误码详细介绍请参考[元能力子系统错误码](errorcode-ability.md)。 1670 1671| 错误码ID | 错误信息 | 1672| ------- | -------------------------------- | 1673| 16000011 | The context does not exist. | 1674| 16000050 | Internal error. | 1675 1676**示例:** 1677 1678```ts 1679import { UIAbility } from '@kit.AbilityKit'; 1680import { window } from '@kit.ArkUI'; 1681import { BusinessError } from '@kit.BasicServicesKit'; 1682 1683export default class EntryAbility extends UIAbility { 1684 onWindowStageCreate(windowStage: window.WindowStage) { 1685 windowStage.loadContent('pages/Index', (err, data) => { 1686 if (err.code) { 1687 return; 1688 } 1689 1690 try { 1691 this.context.reportDrawnCompleted((err) => { 1692 if (err.code) { 1693 // 处理业务逻辑错误 1694 console.error(`reportDrawnCompleted failed, code is ${err.code}, message is ${err.message}`); 1695 return; 1696 } 1697 // 执行正常业务 1698 console.info('reportDrawnCompleted succeed'); 1699 }); 1700 } catch (err) { 1701 // 捕获同步的参数错误 1702 let code = (err as BusinessError).code; 1703 let message = (err as BusinessError).message; 1704 console.error(`reportDrawnCompleted failed, code is ${code}, message is ${message}`); 1705 } 1706 }); 1707 console.log("MainAbility onWindowStageCreate"); 1708 } 1709}; 1710``` 1711 1712## UIAbilityContext.startAbilityByType<sup>11+</sup> 1713 1714startAbilityByType(type: string, wantParam: Record<string, Object>, 1715 abilityStartCallback: AbilityStartCallback, callback: AsyncCallback\<void>) : void 1716 1717通过type隐式启动UIExtensionAbility。使用callback异步回调。仅支持在主线程调用,仅支持处于前台的应用调用。 1718 1719**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1720 1721**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 1722 1723**参数:** 1724 1725| 参数名 | 类型 | 必填 | 说明 | 1726| -------- | -------- | -------- | -------- | 1727| type | string | 是 | 显示拉起的UIExtensionAbility类型,取值详见[通过startAbilityByType接口拉起垂类面板](../../application-models/start-intent-panel.md#匹配规则)。 | 1728| wantParam | Record<string, Object> | 是 | 表示扩展参数。 | 1729| abilityStartCallback | [AbilityStartCallback](js-apis-inner-application-abilityStartCallback.md) | 是 | 执行结果回调函数。 | 1730| callback | AsyncCallback<void> | 是 | 回调函数,返回接口调用是否成功的结果。 | 1731 1732**错误码:** 1733 1734以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 1735 1736| 错误码ID | 错误信息 | 1737| ------- | -------------------------------- | 1738| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 1739| 16000050 | Internal error. | 1740 1741**示例:** 1742 1743```ts 1744import { UIAbility, common } from '@kit.AbilityKit'; 1745 1746export default class EntryAbility extends UIAbility { 1747 onForeground() { 1748 let wantParam: Record<string, Object> = { 1749 'time': '2023-10-23 20:45' 1750 }; 1751 let abilityStartCallback: common.AbilityStartCallback = { 1752 onError: (code: number, name: string, message: string) => { 1753 console.log(`code:` + code + `name:` + name + `message:` + message); 1754 }, 1755 onResult: (abilityResult: common.AbilityResult) => { 1756 console.log(`resultCode:` + abilityResult.resultCode + `bundleName:` + abilityResult.want?.bundleName); 1757 } 1758 }; 1759 1760 this.context.startAbilityByType("photoEditor", wantParam, abilityStartCallback, (err) => { 1761 if (err) { 1762 console.error(`startAbilityByType fail, err: ${JSON.stringify(err)}`); 1763 } else { 1764 console.log(`success`); 1765 } 1766 }); 1767 } 1768} 1769``` 1770 1771## UIAbilityContext.startAbilityByType<sup>11+</sup> 1772 1773startAbilityByType(type: string, wantParam: Record<string, Object>, 1774 abilityStartCallback: AbilityStartCallback) : Promise\<void> 1775 1776通过type隐式启动UIExtensionAbility。使用Promise异步回调。仅支持在主线程调用,仅支持处于前台的应用调用。 1777 1778**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1779 1780**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 1781 1782**参数:** 1783 1784| 参数名 | 类型 | 必填 | 说明 | 1785| -------- | -------- | -------- | -------- | 1786| type | string | 是 | 显示拉起的UIExtensionAbility类型,取值详见[通过startAbilityByType接口拉起垂类面板](../../application-models/start-intent-panel.md#匹配规则)。 | 1787| wantParam | Record<string, Object> | 是 | 表示扩展参数。 | 1788| abilityStartCallback | [AbilityStartCallback](js-apis-inner-application-abilityStartCallback.md) | 是 | 执行结果回调函数。 | 1789 1790**返回值:** 1791 1792| 类型 | 说明 | 1793| -------- | -------- | 1794| Promise<void> | Promise对象。无返回结果的Promise对象。 | 1795 1796**错误码:** 1797 1798以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 1799 1800| 错误码ID | 错误信息 | 1801| ------- | -------------------------------- | 1802| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 1803| 16000050 | Internal error. | 1804 1805**示例:** 1806 1807```ts 1808import { UIAbility, common } from '@kit.AbilityKit'; 1809import { BusinessError } from '@kit.BasicServicesKit'; 1810 1811export default class EntryAbility extends UIAbility { 1812 onForeground() { 1813 let wantParam: Record<string, Object> = { 1814 'time': '2023-10-23 20:45' 1815 }; 1816 let abilityStartCallback: common.AbilityStartCallback = { 1817 onError: (code: number, name: string, message: string) => { 1818 console.log(`code:` + code + `name:` + name + `message:` + message); 1819 }, 1820 onResult: (abilityResult: common.AbilityResult) => { 1821 console.log(`resultCode:` + abilityResult.resultCode + `bundleName:` + abilityResult.want?.bundleName); 1822 } 1823 }; 1824 1825 this.context.startAbilityByType("photoEditor", wantParam, abilityStartCallback).then(() => { 1826 console.log(`startAbilityByType success`); 1827 }).catch((err: BusinessError) => { 1828 console.error(`startAbilityByType fail, err: ${JSON.stringify(err)}`); 1829 }); 1830 } 1831} 1832``` 1833 1834## UIAbilityContext.showAbility<sup>12+</sup> 1835 1836showAbility(): Promise\<void> 1837 1838显示当前Ability。使用Promise异步回调。仅在2in1和tablet设备上生效。仅支持在主线程调用。 1839 1840调用此接口前要求确保应用已添加至状态栏。 1841 1842**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 1843 1844**返回值:** 1845 1846| 类型 | 说明 | 1847| -------- | -------- | 1848| Promise<void> | Promise对象。无返回结果的Promise对象。 | 1849 1850**错误码:** 1851 1852以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 1853 1854| 错误码ID | 错误信息 | 1855| ------- | -------------------------------- | 1856| 801 | Capability not support. | 1857| 16000050 | Internal error. | 1858| 16000067 | The StartOptions check failed. | 1859 1860**示例:** 1861 1862```ts 1863// Index.ets 1864import { common } from '@kit.AbilityKit'; 1865import { BusinessError } from '@kit.BasicServicesKit'; 1866 1867@Entry 1868@Component 1869struct Index { 1870 @State showAbility: string = 'showAbility' 1871 1872 build() { 1873 Row() { 1874 Column() { 1875 Text(this.showAbility) 1876 .fontSize(30) 1877 .fontWeight(FontWeight.Bold) 1878 .onClick(() => { 1879 let context = getContext(this) as common.UIAbilityContext; 1880 1881 context.showAbility().then(() => { 1882 console.log(`showAbility success`); 1883 }).catch((err: BusinessError) => { 1884 console.error(`showAbility fail, err: ${JSON.stringify(err)}`); 1885 }); 1886 }); 1887 } 1888 .width('100%') 1889 } 1890 .height('100%') 1891 } 1892} 1893``` 1894```ts 1895// EntryAbility.ts 1896import { UIAbility, Want, StartOptions, contextConstant } from '@kit.AbilityKit'; 1897import { BusinessError } from '@kit.BasicServicesKit'; 1898 1899export default class EntryAbility extends UIAbility { 1900 onForeground() { 1901 let want: Want = { 1902 deviceId: '', 1903 bundleName: 'com.example.myapplication', 1904 abilityName: 'EntryAbility' 1905 }; 1906 let options: StartOptions = { 1907 displayId: 0, 1908 processMode: contextConstant.ProcessMode.NEW_PROCESS_ATTACH_TO_STATUS_BAR_ITEM, 1909 startupVisibility: contextConstant.StartupVisibility.STARTUP_SHOW 1910 }; 1911 1912 try { 1913 this.context.startAbility(want, options, (err: BusinessError) => { 1914 if (err.code) { 1915 // 处理业务逻辑错误 1916 console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); 1917 return; 1918 } 1919 // 执行正常业务 1920 console.info('startAbility succeed'); 1921 }); 1922 } catch (err) { 1923 // 处理入参错误异常 1924 let code = (err as BusinessError).code; 1925 let message = (err as BusinessError).message; 1926 console.error(`startAbility failed, code is ${code}, message is ${message}`); 1927 } 1928 } 1929} 1930``` 1931 1932## UIAbilityContext.hideAbility<sup>12+</sup> 1933 1934hideAbility(): Promise\<void> 1935 1936隐藏当前Ability。使用Promise异步回调。仅在2in1和tablet设备上生效。仅支持在主线程调用。 1937 1938调用此接口前要求确保应用已添加至状态栏。 1939 1940**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 1941 1942**返回值:** 1943 1944| 类型 | 说明 | 1945| -------- | -------- | 1946| Promise<void> | Promise对象。无返回结果的Promise对象。 | 1947 1948**错误码:** 1949 1950以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 1951 1952| 错误码ID | 错误信息 | 1953| ------- | -------------------------------- | 1954| 801 | Capability not support. | 1955| 16000050 | Internal error. | 1956| 16000067 | The StartOptions check failed. | 1957 1958**示例:** 1959 1960```ts 1961// Index.ets 1962import { common } from '@kit.AbilityKit'; 1963import { BusinessError } from '@kit.BasicServicesKit'; 1964 1965@Entry 1966@Component 1967struct Index { 1968 @State hideAbility: string = 'hideAbility' 1969 1970 build() { 1971 Row() { 1972 Column() { 1973 Text(this.hideAbility) 1974 .fontSize(30) 1975 .fontWeight(FontWeight.Bold) 1976 .onClick(() => { 1977 let context = getContext(this) as common.UIAbilityContext; 1978 1979 context.hideAbility().then(() => { 1980 console.log(`hideAbility success`); 1981 }).catch((err: BusinessError) => { 1982 console.error(`hideAbility fail, err: ${JSON.stringify(err)}`); 1983 }); 1984 }); 1985 } 1986 .width('100%') 1987 } 1988 .height('100%') 1989 } 1990} 1991``` 1992```ts 1993// EntryAbility.ts 1994import { UIAbility, Want, StartOptions, contextConstant } from '@kit.AbilityKit'; 1995import { BusinessError } from '@kit.BasicServicesKit'; 1996 1997export default class EntryAbility extends UIAbility { 1998 onForeground() { 1999 let want: Want = { 2000 deviceId: '', 2001 bundleName: 'com.example.myapplication', 2002 abilityName: 'EntryAbility' 2003 }; 2004 let options: StartOptions = { 2005 displayId: 0, 2006 processMode: contextConstant.ProcessMode.NEW_PROCESS_ATTACH_TO_STATUS_BAR_ITEM, 2007 startupVisibility: contextConstant.StartupVisibility.STARTUP_HIDE 2008 }; 2009 2010 try { 2011 this.context.startAbility(want, options, (err: BusinessError) => { 2012 if (err.code) { 2013 // 处理业务逻辑错误 2014 console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); 2015 return; 2016 } 2017 // 执行正常业务 2018 console.info('startAbility succeed'); 2019 }); 2020 } catch (err) { 2021 // 处理入参错误异常 2022 let code = (err as BusinessError).code; 2023 let message = (err as BusinessError).message; 2024 console.error(`startAbility failed, code is ${code}, message is ${message}`); 2025 } 2026 } 2027} 2028``` 2029 2030## UIAbilityContext.moveAbilityToBackground<sup>12+<sup> 2031moveAbilityToBackground(): Promise\<void> 2032 2033将处于前台的Ability移动到后台。使用Promise异步回调。仅支持在主线程调用。<br/><!--RP1--><!--RP1End--> 2034 2035**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 2036 2037**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 2038 2039**返回值:** 2040 2041| 类型 | 说明 | 2042| -------- | -------- | 2043| Promise<void> | Promise对象。无返回结果的Promise对象。 | 2044 2045**错误码:** 2046 2047以下错误码详细介绍请参考[元能力子系统错误码]。 2048 2049| 错误码ID | 错误信息 | 2050| ------- | -------------------------------- | 2051| 16000011 | The context does not exist. | 2052| 16000050 | Internal error. | 2053| 16000061 | Operation not supported. | 2054| 16000065 | The API can be called only when the ability is running in the foreground. | 2055| 16000066 | An ability cannot switch to the foreground or background in Wukong mode. | 2056 2057**示例:** 2058 2059```ts 2060import { common } from '@kit.AbilityKit'; 2061import { BusinessError } from '@kit.BasicServicesKit'; 2062 2063@Entry 2064@Component 2065struct Index { 2066 @State moveAbilityToBackground: string = 'Move To Background' 2067 2068 build() { 2069 Row() { 2070 Column() { 2071 Text(this.moveAbilityToBackground) 2072 .fontSize(30) 2073 .fontWeight(FontWeight.Bold) 2074 .onClick(() => { 2075 let context = getContext(this) as common.UIAbilityContext; 2076 2077 context.moveAbilityToBackground().then(() => { 2078 console.log(`moveAbilityToBackground success.`); 2079 }).catch((err: BusinessError) => { 2080 console.log(`moveAbilityToBackground error: ${JSON.stringify(err)}.`); 2081 }); 2082 }); 2083 } 2084 .width('100%') 2085 } 2086 .height('100%') 2087 } 2088} 2089``` 2090 2091## UIAbilityContext.openAtomicService<sup>12+<sup> 2092 2093openAtomicService(appId: string, options?: AtomicServiceOptions): Promise<AbilityResult> 2094 2095跳出式启动[EmbeddableUIAbility](js-apis-app-ability-embeddableUIAbility.md),并返回结果。使用Promise异步回调。仅支持在主线程调用。 2096 2097分为以下几种情况: 2098 - 正常情况下可通过调用[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)接口使之终止并且返回结果给调用方。 2099 - 异常情况下比如杀死EmbeddableUIAbility会返回异常信息给调用方,异常信息中resultCode为-1。 2100 - 如果不同应用多次调用该接口启动同一个EmbeddableUIAbility,当这个EmbeddableUIAbility调用[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)接口使之终止时,只将正常结果返回给最后一个调用方, 其它调用方返回异常信息,异常信息中resultCode为-1。 2101 2102> **说明:** 2103> 2104> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。 2105 2106**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 2107 2108**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 2109 2110**参数:** 2111 2112| 参数名 | 类型 | 必填 | 说明 | 2113| -------- | -------- | -------- | -------- | 2114| appId | string | 是 | 应用的唯一标识,由云端统一分配。 | 2115| options | [AtomicServiceOptions](js-apis-app-ability-atomicServiceOptions.md) | 否 | 跳出式启动原子化服务所携带的参数。 | 2116 2117 2118**返回值:** 2119 2120| 类型 | 说明 | 2121| -------- | -------- | 2122| Promise<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Promise对象。返回[AbilityResult](js-apis-inner-ability-abilityResult.md)对象。 | 2123 2124**错误码:** 2125 2126以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 2127 2128| 错误码ID | 错误信息 | 2129| ------- | -------------------------------- | 2130| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 2131| 16000002 | Incorrect ability type. | 2132| 16000003 | The specified ID does not exist. | 2133| 16000004 | Failed to start the invisible ability. | 2134| 16000011 | The context does not exist. | 2135| 16000012 | The application is controlled. | 2136| 16000050 | Internal error. | 2137| 16000053 | The ability is not on the top of the UI. | 2138| 16000055 | Installation-free timed out. | 2139| 16200001 | The caller has been released. | 2140 2141**示例:** 2142 2143```ts 2144import { UIAbility, common, AtomicServiceOptions } from '@kit.AbilityKit'; 2145import { BusinessError } from '@kit.BasicServicesKit'; 2146 2147export default class EntryAbility extends UIAbility { 2148 onForeground() { 2149 let appId: string = '6918661953712445909'; 2150 let options: AtomicServiceOptions = { 2151 displayId: 0 2152 }; 2153 2154 try { 2155 this.context.openAtomicService(appId, options) 2156 .then((result: common.AbilityResult) => { 2157 // 执行正常业务 2158 console.info('openAtomicService succeed'); 2159 }) 2160 .catch((err: BusinessError) => { 2161 // 处理业务逻辑错误 2162 console.error(`openAtomicService failed, code is ${err.code}, message is ${err.message}`); 2163 }); 2164 } catch (err) { 2165 // 处理入参错误异常 2166 let code = (err as BusinessError).code; 2167 let message = (err as BusinessError).message; 2168 console.error(`openAtomicService failed, code is ${code}, message is ${message}`); 2169 } 2170 } 2171} 2172``` 2173 2174## UIAbilityContext.openLink<sup>12+<sup> 2175 2176openLink(link: string, options?: OpenLinkOptions, callback?: AsyncCallback<AbilityResult>): Promise<void> 2177 2178通过AppLinking启动UIAbility,使用Promise异步回调。仅支持在主线程调用。 2179 2180通过在link字段中传入标准格式的URL,基于隐式want匹配规则拉起目标UIAbility。目标方必须具备以下过滤器特征,才能处理AppLinking链接: 2181- "actions"列表中包含"ohos.want.action.viewData"。 2182- "entities"列表中包含"entity.system.browsable"。 2183- "uris"列表中包含"scheme"为"https"且"domainVerify"为true的元素。 2184 2185如果希望获取被拉起方终止后的结果,可以设置callback参数,此参数的使用可参照[startAbilityForResult](#uiabilitycontextstartabilityforresult)接口。 2186传入的参数不合法时,如未设置必选参数或link字符串不是标准格式的URL,接口会直接抛出异常。参数校验通过,拉起目标方时出现的错误通过promise返回错误信息。 2187 2188> **说明:** 2189> 2190> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。 2191 2192**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 2193 2194**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 2195 2196**参数:** 2197 2198| 参数名 | 类型 | 必填 | 说明 | 2199| -------- | -------- | -------- | -------- | 2200| link | string | 是 | 指示要打开的标准格式URL。 | 2201| options | [OpenLinkOptions](js-apis-app-ability-openLinkOptions.md) | 否 | 打开URL的选项参数。 | 2202| callback | AsyncCallback<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | 否 | 执行结果回调函数。 | 2203 2204**返回值:** 2205 2206| 类型 | 说明 | 2207| -------- | -------- | 2208| Promise<void> | Promise对象。无返回结果的Promise对象。 | 2209 2210**错误码:** 2211 2212以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 2213 2214| 错误码ID | 错误信息 | 2215| ------- | -------------------------------- | 2216| 201 | The application does not have permission to call the interface. | 2217| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 2218| 16000001 | The specified ability does not exist. | 2219| 16000002 | Incorrect ability type. | 2220| 16000004 | Failed to start the invisible ability. | 2221| 16000005 | The specified process does not have the permission. | 2222| 16000006 | Cross-user operations are not allowed. | 2223| 16000008 | The crowdtesting application expires. | 2224| 16000009 | An ability cannot be started or stopped in Wukong mode. | 2225| 16000010 | The call with the continuation flag is forbidden. | 2226| 16000011 | The context does not exist. | 2227| 16000012 | The application is controlled. | 2228| 16000013 | The application is controlled by EDM. | 2229| 16000019 | No matching ability is found. | 2230| 16200001 | The caller has been released. | 2231| 16000053 | The ability is not on the top of the UI. | 2232 2233**示例:** 2234 2235```ts 2236import { common, OpenLinkOptions } from '@kit.AbilityKit'; 2237import { hilog } from '@kit.PerformanceAnalysisKit'; 2238import { BusinessError } from '@kit.BasicServicesKit'; 2239 2240const DOMAIN = 0xeeee; 2241const TAG: string = '[openLinkDemo]'; 2242 2243@Entry 2244@Component 2245struct Index { 2246 build() { 2247 RelativeContainer() { 2248 Button("Call StartAbilityForResult") 2249 .onClick(() => { 2250 let context = getContext(this) as common.UIAbilityContext; 2251 let link: string = 'https://www.example.com'; 2252 let openLinkOptions: OpenLinkOptions = { 2253 appLinkingOnly: true, 2254 parameters: { demo_key: 'demo_value' } 2255 }; 2256 2257 try { 2258 context.openLink( 2259 link, 2260 openLinkOptions, 2261 (err, result) => { 2262 hilog.error(DOMAIN, TAG, `openLink callback error.code: ${JSON.stringify(err)}`); 2263 hilog.info(DOMAIN, TAG, `openLink callback result: ${JSON.stringify(result.resultCode)}`); 2264 hilog.info(DOMAIN, TAG, `openLink callback result data: ${JSON.stringify(result.want)}`); 2265 } 2266 ).then(() => { 2267 hilog.info(DOMAIN, TAG, `open link success.`); 2268 }).catch((err: BusinessError) => { 2269 hilog.error(DOMAIN, TAG, `open link failed, errCode ${JSON.stringify(err.code)}`); 2270 }); 2271 } 2272 catch (e) { 2273 hilog.error(DOMAIN, TAG, `exception occured, errCode ${JSON.stringify(e.code)}`); 2274 } 2275 }) 2276 } 2277 .height('100%') 2278 .width('100%') 2279 } 2280} 2281``` 2282 2283## UIAbilityContext.backToCallerAbilityWithResult<sup>12+<sup> 2284 2285backToCallerAbilityWithResult(abilityResult: AbilityResult, requestCode: string): Promise<void> 2286 2287当通过[startAbilityForResult](#uiabilitycontextstartabilityforresult)或[openLink](#uiabilitycontextopenlink12)拉起目标方Ability,且需要目标方返回结果时,目标方可以通过该接口将结果返回并拉起调用方。与[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)不同的是,本接口在返回时不会销毁当前Ability。使用Promise异步回调。 2288 2289**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 2290 2291**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 2292 2293**参数:** 2294 2295| 参数名 | 类型 | 必填 | 说明 | 2296| -------- | -------- | -------- | -------- | 2297| abilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | 是 | 指示目标方返回给拉起方的结果。 | 2298| requestCode | string | 是 | 通过[startAbilityForResult](#uiabilitycontextstartabilityforresult)或[openLink](#uiabilitycontextopenlink12)拉起目标方Ability且需要目标方返回结果时,系统生成的用于标识本次调用的requestCode。该值可以通过want中的[CALLER_REQUEST_CODE](js-apis-app-ability-wantConstant.md)字段获取。| 2299 2300**返回值:** 2301 2302| 类型 | 说明 | 2303| -------- | -------- | 2304| Promise<void> | Promise对象。无返回结果的Promise对象。 | 2305 2306**错误码:** 2307 2308以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 2309 2310| 错误码ID | 错误信息 | 2311| ------- | -------------------------------- | 2312| 201 | The application does not have permission to call the interface. | 2313| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 2314| 16000009 | An ability cannot be started or stopped in Wukong mode. | 2315| 16000011 | The context does not exist. | 2316| 16000050 | Internal error. | 2317| 16000074 | The caller does not exist. | 2318| 16000075 | Not support back to caller. | 2319 2320**示例:** 2321调用方通过startAbilityForResult接口拉起目标方, 目标方再调用backToCallerAbilityWithResult接口返回到调用方。 2322 2323```ts 2324// 调用方 2325// index.ets 2326import { common, Want } from '@kit.AbilityKit'; 2327import { BusinessError } from '@ohos.base'; 2328import { hilog } from '@kit.PerformanceAnalysisKit'; 2329 2330@Entry 2331@Component 2332struct Index { 2333 @State message: string = 'Hello World'; 2334 2335 build() { 2336 Row() { 2337 Column() { 2338 Text(this.message) 2339 .fontSize(30) 2340 .fontWeight(FontWeight.Bold) 2341 2342 Button("Call StartAbilityForResult") 2343 .onClick(() => { 2344 let context: common.UIAbilityContext = getContext() as common.UIAbilityContext; 2345 let want: Want = { 2346 bundleName: 'com.example.demo2', 2347 abilityName: 'EntryAbility' 2348 }; 2349 2350 try { 2351 // 通过startAbilityForResult拉起目标应用 2352 context.startAbilityForResult(want, (err: BusinessError, result: common.AbilityResult) => { 2353 if (err.code) { 2354 // 处理业务逻辑错误 2355 hilog.error(0x0000, 'testTag', `startAbilityForResult failed, code is ${err.code}, message is ${err.message}`); 2356 this.message = `startAbilityForResult failed: code is ${err.code}, message is ${err.message}` 2357 return; 2358 } 2359 // 执行正常业务 2360 hilog.info(0x0000, 'testTag', `startAbilityForResult succeed`); 2361 hilog.info(0x0000, 'testTag', `AbilityResult is ${JSON.stringify(result)}`); 2362 this.message = `AbilityResult.resultCode: ${JSON.stringify(result.resultCode)}` 2363 }); 2364 } catch (err) { 2365 // 处理入参错误异常 2366 let code = (err as BusinessError).code; 2367 let message = (err as BusinessError).message; 2368 hilog.error(0x0000, 'testTag', `startAbilityForResult failed, code is ${code}, message is ${message}`); 2369 this.message = `startAbilityForResult failed, code is ${code}, message is ${message}`; 2370 } 2371 }) 2372 } 2373 .width('100%') 2374 } 2375 .height('100%') 2376 } 2377} 2378``` 2379 2380```ts 2381// 目标方 2382// EntryAbility.ets 2383import { AbilityConstant, common, UIAbility, Want, wantConstant } from '@kit.AbilityKit'; 2384import { hilog } from '@kit.PerformanceAnalysisKit'; 2385import { BusinessError } from '@kit.BasicServicesKit'; 2386 2387export default class EntryAbility extends UIAbility { 2388 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 2389 // 从want中获取调用方的CALLER_REQUEST_CODE,并保存 2390 let callerRequestCode: string = want?.parameters?.[wantConstant.Params.CALLER_REQUEST_CODE] as string; 2391 AppStorage.setOrCreate<string>("callerRequestCode", callerRequestCode) 2392 } 2393 2394 onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void { 2395 let callerRequestCode: string = want?.parameters?.[wantConstant.Params.CALLER_REQUEST_CODE] as string; 2396 AppStorage.setOrCreate<string>("callerRequestCode", callerRequestCode) 2397 } 2398 2399 onForeground(): void { 2400 // 获取保存的CALLER_REQUEST_CODE 2401 let callerRequestCode: string = AppStorage.get<string>("callerRequestCode") as string; 2402 hilog.info(0x0000, 'testTag', `callerRequestCode is ${callerRequestCode}`); 2403 let want: Want = {}; 2404 let resultCode = 100; 2405 let abilityResult: common.AbilityResult = { 2406 want, 2407 resultCode 2408 }; 2409 try { 2410 // 将结果信息返回给调用方 2411 this.context.backToCallerAbilityWithResult(abilityResult, callerRequestCode) 2412 .then(() => { 2413 // 执行正常业务 2414 hilog.info(0x0000, 'testTag', 'backToCallerAbilityWithResult succeed'); 2415 }) 2416 .catch((err: BusinessError) => { 2417 // 处理业务逻辑错误 2418 hilog.error(0x0000, 'testTag', `backToCallerAbilityWithResult failed, code is ${err.code}, message is ${err.message}`); 2419 }); 2420 } catch (err) { 2421 // 捕获同步的参数错误 2422 let code = (err as BusinessError).code; 2423 let message = (err as BusinessError).message; 2424 hilog.error(0x0000, 'testTag', `backToCallerAbilityWithResult failed, code is ${code}, message is ${message}`); 2425 } 2426 } 2427} 2428``` 2429 2430## UIAbilityContext.setRestoreEnabled<sup>14+</sup> 2431 2432setRestoreEnabled(enabled: boolean): void 2433 2434设置UIAbility是否启用备份恢复。 2435 2436**原子化服务API**:从API version 14开始,该接口支持在原子化服务中使用。 2437 2438**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 2439 2440**参数:** 2441 2442| 参数名 | 类型 | 必填 | 说明 | 2443| -------- | -------- | -------- | -------- | 2444| enabled | boolean | 是 | 表示是否启用恢复。true表示启用,false表示不启用。 | 2445 2446**错误码:** 2447 2448以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 2449 2450| 错误码ID | 错误信息 | 2451| ------- | -------------------------------- | 2452| 401 | If the input parameter is not valid parameter. | 2453| 16000011 | The context does not exist. | 2454 2455**示例:** 2456 2457```ts 2458import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit'; 2459import { BusinessError } from '@kit.BasicServicesKit'; 2460 2461export default class EntryAbility extends UIAbility { 2462 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 2463 let enabled = true; 2464 try { 2465 this.context.setRestoreEnabled(enabled); 2466 } catch (paramError) { 2467 let code = (paramError as BusinessError).code; 2468 let message = (paramError as BusinessError).message; 2469 console.error(`setRestoreEnabled failed, err code: ${code}, err msg: ${message}`); 2470 } 2471 } 2472} 2473``` 2474 2475## UIAbilityContext.startUIServiceExtensionAbility<sup>14+<sup> 2476 2477startUIServiceExtensionAbility(want: Want): Promise<void> 2478 2479启动一个UIServiceExtensionAbility。使用Promise异步回调。 2480 2481> **说明:** 2482> 2483> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。 2484 2485**原子化服务API**:从API version 14开始,该接口支持在原子化服务中使用。 2486 2487**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 2488 2489**参数:** 2490 2491| 参数名 | 类型 | 必填 | 说明 | 2492| -------- | --------------------------------------- | ---- | ------------------------ | 2493| want | [Want](js-apis-app-ability-want.md) | 是 | 启动需要的Want信息。 | 2494 2495**返回值:** 2496 2497| 类型 | 说明 | 2498| ------------------- | -------------------------------------- | 2499| Promise<void> | Promise对象。无返回结果的Promise对象。 | 2500 2501**错误码:** 2502 2503以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 2504 2505| 错误码ID | 错误信息 | 2506| -------- | ----------------------------------------------------------------------------------------------------------- | 2507| 201 | The application does not have permission to call the interface. | 2508| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 2509| 801 | Capability not supported. | 2510| 16000001 | The specified ability does not exist. | 2511| 16000002 | Incorrect ability type. | 2512| 16000004 | Failed to start the invisible ability. | 2513| 16000005 | The specified process does not have the permission. | 2514| 16000008 | The crowdtesting application expires. | 2515| 16000011 | The context does not exist. | 2516| 16000012 | The application is controlled. | 2517| 16000013 | The application is controlled by EDM. | 2518| 16000019 | No matching ability is found. | 2519| 16000050 | Internal error. | 2520| 16200001 | The caller has been released. | 2521 2522**示例:** 2523 2524```ts 2525import { common, Want } from '@kit.AbilityKit'; 2526import { BusinessError } from '@kit.BasicServicesKit'; 2527 2528@Entry 2529@Component 2530struct Index { 2531 build() { 2532 Column() { 2533 Row() { 2534 // 创建启动按钮 2535 Button('start ability') 2536 .enabled(true) 2537 .onClick(() => { 2538 let context = getContext(this) as common.UIAbilityContext; 2539 let startWant: Want = { 2540 bundleName: 'com.acts.uiserviceextensionability', 2541 abilityName: 'UiServiceExtAbility', 2542 }; 2543 try { 2544 // 启动UIServiceExtensionAbility 2545 context.startUIServiceExtensionAbility(startWant).then(() => { 2546 console.log('startUIServiceExtensionAbility success'); 2547 }).catch((error: BusinessError) => { 2548 console.log('startUIServiceExtensionAbility error', JSON.stringify(error)); 2549 }) 2550 } catch (err) { 2551 console.log('startUIServiceExtensionAbility failed', JSON.stringify(err)); 2552 } 2553 }) 2554 } 2555 } 2556 } 2557} 2558``` 2559 2560## UIAbilityContext.connectUIServiceExtensionAbility<sup>14+<sup> 2561 2562connectUIServiceExtensionAbility(want: Want, callback: UIServiceExtensionConnectCallback) : Promise<UIServiceProxy> 2563 2564连接一个UIServiceExtensionAbility。使用Promise异步回调。 2565 2566> **说明:** 2567> 2568> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。 2569> 2570 2571**原子化服务API**:从API version 14开始,该接口支持在原子化服务中使用。 2572 2573**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 2574 2575**参数:** 2576 2577| 参数名 | 类型 | 必填 | 说明 | 2578| ------ | ---- | ---- | ---- | 2579| want |[Want](js-apis-app-ability-want.md) | 是 | 连接需要的Want信息。 | 2580| callback | [UIServiceExtensionConnectCallback](js-apis-inner-application-uiServiceExtensionconnectcallback.md) | 是 | 连接UIServiceExtensionAbility回调。 | 2581 2582**返回值:** 2583 2584| 类型 | 说明 | 2585| ------------------- | -------------------------------------- | 2586| Promise<UIServiceProxy> | [connectUIServiceExtensionAbility](js-apis-inner-application-uiExtensionContext.md#uiextensioncontextconnectuiserviceextensionability13)执行后返回的[UIServiceProxy](js-apis-inner-application-uiserviceproxy.md)对象。 | 2587 2588**错误码:** 2589 2590以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 2591 2592| 错误码ID | 错误信息 | 2593| -------- | ----------------------------------------------------------------------------------- | 2594| 201 | The application does not have permission to call the interface. | 2595| 801 | Capability not supported. | 2596| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 2597| 16000001 | The specified ability does not exist. | 2598| 16000002 | Incorrect ability type. | 2599| 16000004 | Failed to start the invisible ability. | 2600| 16000005 | The specified process does not have the permission. | 2601| 16000008 | The crowdtesting application expires. | 2602| 16000011 | The context does not exist. | 2603| 16000013 | The EDM prohibits the application from launching. | 2604| 16000050 | Internal error. | 2605| 16000055 | Installation-free timed out. | 2606 2607**示例:** 2608 2609```ts 2610import { common, Want } from '@kit.AbilityKit'; 2611import { BusinessError } from '@kit.BasicServicesKit'; 2612 2613const TAG: string = '[Extension] '; 2614 2615@Entry 2616@Component 2617struct UIServiceExtensionAbility { 2618 dataCallBack : common.UIServiceExtensionConnectCallback = { 2619 // 接收数据 2620 onData: (data: Record<string, Object>) => { 2621 console.log(`dataCallBack received data`, JSON.stringify(data)); 2622 }, 2623 // 连接断开 2624 onDisconnect: () => { 2625 console.log(`dataCallBack onDisconnect`); 2626 } 2627 } 2628 2629 async myConnect() { 2630 // 获取上下文 2631 let context = getContext(this) as common.UIAbilityContext; 2632 let startWant: Want = { 2633 deviceId: '', 2634 bundleName: 'com.example.myapplication', 2635 abilityName: 'UiServiceExtAbility' 2636 }; 2637 2638 try { 2639 // 连接服务 2640 context.connectUIServiceExtensionAbility(startWant, this.dataCallBack) 2641 .then((proxy: common.UIServiceProxy) => { 2642 console.log(TAG + `try to connectUIServiceExtensionAbility`, JSON.stringify(proxy)); 2643 }).catch((err: Error) => { 2644 let code = (err as BusinessError).code; 2645 let message = (err as BusinessError).message; 2646 console.log(TAG + `connectUIServiceExtensionAbility failed, code is ${code}, message is ${message}`); 2647 }); 2648 } catch (err) { 2649 let code = (err as BusinessError).code; 2650 let message = (err as BusinessError).message; 2651 console.log(TAG + `connectUIServiceExtensionAbility failed, code is ${code}, message is ${message}`); 2652 }; 2653 } 2654 2655 build() { 2656 RelativeContainer() { 2657 // 创建连接按钮 2658 Button('connectServiceExtensionAbility', { type: ButtonType.Capsule, stateEffect: true }) 2659 .alignRules({ 2660 center: { anchor: '__container__', align: VerticalAlign.Center }, 2661 middle: { anchor: '__container__', align: HorizontalAlign.Center } 2662 }) 2663 .onClick(() => { 2664 this.myConnect() 2665 }); 2666 } 2667 .height('100%') 2668 .width('100%') 2669 } 2670} 2671``` 2672 2673## UIAbilityContext.disconnectUIServiceExtensionAbility<sup>14+<sup> 2674 2675disconnectUIServiceExtensionAbility(proxy: UIServiceProxy): Promise<void> 2676 2677断开与UIServiceExtensionAbility的连接。使用Promise异步回调。 2678 2679> **说明:** 2680> 2681> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。 2682> 2683 2684**原子化服务API**:从API version 14开始,该接口支持在原子化服务中使用。 2685 2686**系统能力**:SystemCapability.Ability.AbilityRuntime.Core 2687 2688**参数:** 2689 2690| 参数名 | 类型 | 必填 | 说明 | 2691| ------ | ---- | ---- | -------------------- | 2692| proxy | [UIServiceProxy](js-apis-inner-application-uiserviceproxy.md) | 是 | [connectUIServiceExtensionAbility](#uiabilitycontextconnectuiserviceextensionability13)执行返回的Proxy。 | 2693 2694**返回值:** 2695 2696| 类型 | 说明 | 2697| ------------------- | -------------------------------------- | 2698| Promise<void> | Promise对象。无返回结果的Promise对象。 | 2699 2700**错误码:** 2701 2702以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 2703 2704| 错误码ID | 错误信息 | 2705| -------- | ------------------------------------------------------------------------------------------- | 2706| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 2707| 16000011 | The context does not exist. | 2708| 16000050 | Internal error. | 2709 2710**示例:** 2711 2712```ts 2713import { common } from '@kit.AbilityKit'; 2714import { BusinessError } from '@kit.BasicServicesKit'; 2715 2716const TAG: string = '[Extension] '; 2717 2718@Entry 2719@Component 2720struct UIServiceExtensionAbility { 2721 comProxy: common.UIServiceProxy | null = null; 2722 2723 build() { 2724 Scroll() { 2725 Column() { 2726 // 创建断开连接的按钮 2727 Button('disconnectUIServiceExtensionAbility', { type: ButtonType.Capsule, stateEffect: true }) 2728 .margin({ 2729 top: 5, 2730 left: 10, 2731 right: 10, 2732 bottom: 5 2733 }) 2734 .alignRules({ 2735 center: { anchor: '__container__', align: VerticalAlign.Center }, 2736 middle: { anchor: '__container__', align: HorizontalAlign.Center } 2737 }) 2738 .onClick(() => { 2739 this.myDisconnectUIServiceExtensionAbility() 2740 }); 2741 } 2742 .width('100%') 2743 } 2744 .height('100%') 2745 } 2746 2747 myDisconnectUIServiceExtensionAbility() { 2748 let context = getContext(this) as common.UIAbilityContext; 2749 2750 try { 2751 // 断开UIServiceExtension连接 2752 context.disconnectUIServiceExtensionAbility(this.comProxy) 2753 .then(() => { 2754 console.log(TAG + `disconnectUIServiceExtensionAbility succeed ${this.comProxy}}`); 2755 }).catch((err: Error) => { 2756 let code = (err as BusinessError).code; 2757 let message = (err as BusinessError).message; 2758 console.log(TAG + `disconnectUIServiceExtensionAbility failed, code is ${code}, message is ${message}`); 2759 }); 2760 } catch (err) { 2761 let code = (err as BusinessError).code; 2762 let message = (err as BusinessError).message; 2763 console.log(TAG + `disconnectUIServiceExtensionAbility failed, code is ${code}, message is ${message}`); 2764 } 2765 } 2766} 2767``` 2768 2769## UIAbilityContext.setAbilityInstanceInfo<sup>15+<sup> 2770 2771setAbilityInstanceInfo(label: string, icon: image.PixelMap) : Promise<void> 2772 2773设置当前UIAbility实例的图标和标签信息。图标与标签信息可在任务中心和快捷栏的界面中显示。使用Promise异步回调。 2774 2775 2776> **说明**: 2777> 2778> 仅支持2in1设备。 2779 2780**需要权限**: ohos.permission.SET_ABILITY_INSTANCE_INFO 2781 2782**系统能力**: SystemCapability.Ability.AbilityRuntime.Core 2783 2784**参数**: 2785 2786| 参数名 | 类型 | 必填 | 说明 | 2787| ------ | -------------------------------------------------------------- | ---- | -------------------------------------------------- | 2788| label |string | 是 | 新的标题。标题长度不超过1024字节,标题不可为空字符串。 | 2789| icon | [image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | 是 | 新的图标。建议图标大小为512px*512px。 | 2790 2791**返回值**: 2792 2793| 类型 | 说明 | 2794| ------------------- | -------------------------------------- | 2795| Promise<void> | Promise对象。无返回结果的Promise对象。 | 2796 2797**错误码**: 2798 2799以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。 2800 2801| 错误码ID | 错误信息 | 2802| -------- | ----------------------------------------------------------------------------------- | 2803| 201 | The application does not have permission to call the interface. | 2804| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 2805| 801 | Capability not supported. | 2806| 16000011 | The context does not exist. | 2807| 16000050 | Internal error. | 2808 2809**示例**: 2810 2811```ts 2812import { UIAbility } from '@kit.AbilityKit'; 2813import { image } from '@kit.ImageKit'; 2814import { BusinessError } from '@kit.BasicServicesKit'; 2815import { window } from '@kit.ArkUI'; 2816 2817export default class EntryAbility extends UIAbility { 2818 onWindowStageCreate(windowStage: window.WindowStage): void { 2819 windowStage.loadContent('pages/Index', async (err, data) => { 2820 if (err.code) { 2821 console.error(`loadContent failed, code is ${err.code}`); 2822 return; 2823 } 2824 2825 let newLabel: string = 'instance label'; 2826 let color = new ArrayBuffer(0); 2827 let imagePixelMap: image.PixelMap = await image.createPixelMap(color, { 2828 size: { 2829 height: 100, 2830 width: 100 2831 } 2832 }); 2833 this.context.setAbilityInstanceInfo(newLabel, imagePixelMap) 2834 .then(() => { 2835 console.info('setAbilityInstanceInfo success'); 2836 }).catch((err: BusinessError) => { 2837 console.error(`setAbilityInstanceInfo failed, code is ${err.code}, message is ${err.message}`); 2838 }); 2839 }); 2840 } 2841} 2842```