diff --git a/zh-cn/application-dev/reference/apis-new/application/UIAbilityContext-sys.md b/zh-cn/application-dev/reference/apis-new/application/UIAbilityContext-sys.md new file mode 100644 index 0000000000000000000000000000000000000000..acf5a8cbc63ffbc412a8730c52d47985d92e7642 --- /dev/null +++ b/zh-cn/application-dev/reference/apis-new/application/UIAbilityContext-sys.md @@ -0,0 +1,1346 @@ +# UIAbilityContext +UIAbilityContext是[UIAbility](js-apis-app-ability-uiAbility.md)的上下文环境,继承自[Context](js-apis-inner-application-context.md),提供UIAbility的相关配置信息以及操作UIAbility和ServiceExtensionAbility的方法,如启动UIAbility,停止当前UIAbilityContext所属的UIAbility,启动、停止、连接、断开连接ServiceExtensionAbility等。 +> **说明** +>本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本 + +## UIAbilityContext + **模型约束:** 此接口仅可在stage模型下使用。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core +### startAbilityAsCaller(10+) +使用设置的caller信息启动一个Ability,caller信息由want携带,在系统服务层识别,Ability可以在onCreate生命周期的want参数中获取到caller信息。使用该接口启动一个Ability时,want的caller信息不会被当前自身的应用信息覆盖,系统服务层可获取到初始caller的信息。 使用规则: - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 - 跨应用场景下,目标Ability的exported属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 - 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md) + **调用形式:** + +- startAbilityAsCaller(want: Want, callback: AsyncCallback\): void +起始版本: 10 +- startAbilityAsCaller(want: Want, options: StartOptions, callback: AsyncCallback\): void +起始版本: 10 +- startAbilityAsCaller(want: Want, options?: StartOptions): Promise\ +起始版本: 10 + + **模型约束:** 此接口仅可在stage模型下使用。 + **系统API:** 此接口为系统接口。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| want | Want | true | 启动Ability的want信息。 | +| options | StartOptions | true | 启动Ability所携带的参数。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | 回调函数。当启动Ability成功,err为undefined,否则为错误对象。 | +| Promise | Promise对象。无返回结果的Promise对象。 | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 201 | | +| 202 | | +| 401 | | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000012 | The application is controlled. | +| 16000013 | The application is controlled by EDM. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + + **示例代码1:** +示例(callback): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import AbilityConstant from '@ohos.app.ability.AbilityConstant'; +import StartOptions from '@ohos.app.ability.StartOptions'; +import Want from '@ohos.app.ability.Want'; + +export default class EntryAbility extends UIAbility { + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { + // want包含启动该应用的Caller信息 + let localWant: Want = want; + localWant.bundleName = 'com.example.demo'; + localWant.moduleName = 'entry'; + localWant.abilityName = 'TestAbility'; + + let option: StartOptions = { + displayId: 0 + } + + // 使用启动方的Caller身份信息启动新Ability + this.context.startAbilityAsCaller(localWant, option, (err) => { + if (err err.code != 0) { + console.error('startAbilityAsCaller failed, err:' + JSON.stringify(err)); + } else { + console.log('startAbilityAsCaller success.'); + } + }) + } +} + +``` + + + **示例代码2:** +示例(Promise): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import AbilityConstant from '@ohos.app.ability.AbilityConstant'; +import StartOptions from '@ohos.app.ability.StartOptions'; +import Want from '@ohos.app.ability.Want'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { + // want包含启动该应用的Caller信息 + let localWant: Want = want; + localWant.bundleName = 'com.example.demo'; + localWant.moduleName = 'entry'; + localWant.abilityName = 'TestAbility'; + + let option: StartOptions = { + displayId: 0 + } + + // 使用启动方的Caller身份信息启动新Ability + this.context.startAbilityAsCaller(localWant, option) + .then(() => { + console.log('startAbilityAsCaller success.'); + }) + .catch((err: BusinessError) => { + console.error('startAbilityAsCaller failed, err:' + JSON.stringify(err)); + }) + } +} + +``` + + +### startAbilityByCallWithAccount(10+) +根据accountId对指定的Ability进行call调用,并且可以使用返回的Caller通信接口与被调用方进行通信。 使用规则: - 跨用户场景下,Call调用目标Ability时,调用方应用需同时申请`ohos.permission.ABILITY_BACKGROUND_COMMUNICATION`与`ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS`权限 - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 - 跨应用场景下,目标Ability的exported属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 - 同设备与跨设备场景下,该接口的使用规则存在差异,详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md) + **调用形式:** + +- startAbilityByCallWithAccount(want: Want, accountId: number): Promise\ +起始版本: 10 + + **模型约束:** 此接口仅可在stage模型下使用。 + **系统API:** 此接口为系统接口。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core + **需要权限:** ohos.permission.ABILITY_BACKGROUND_COMMUNICATION and ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| want | Want | true | 传入需要启动的Ability的信息,包含abilityName、moduleName、bundleName、deviceId(可选)、parameters(可选),其中deviceId缺省或为空表示启动本地Ability,parameters缺省或为空表示后台启动Ability。 | +| accountId | number | true | 系统帐号的帐号ID,-1表示当前活动用户,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | | +| Promise | 获取要通讯的caller对象。 | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 201 | | +| 202 | | +| 401 | | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000011 | The context does not exist. | +| 16000012 | The application is controlled. | +| 16000013 | The application is controlled by EDM. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | + + **示例代码:** +示例(Promise): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { Caller } from '@ohos.app.ability.UIAbility'; +import Want from '@ohos.app.ability.Want'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + + onForeground() { + let caller: Caller; + + // 系统账号的账号ID, -1表示当前激活用户 + let accountId = -1; + + // 指定启动的Ability + let want: Want = { + bundleName: 'com.acts.actscalleeabilityrely', + moduleName: 'entry', + abilityName: 'EntryAbility', + deviceId: '', + parameters: { + // 'ohos.aafwk.param.callAbilityToForeground' 值设置为true时为前台启动, 设置false或不设置为后台启动 + 'ohos.aafwk.param.callAbilityToForeground': true + } + }; + + try { + this.context.startAbilityByCallWithAccount(want, accountId) + .then((obj: Caller) => { + // 执行正常业务 + caller = obj; + console.log('startAbilityByCallWithAccount succeed'); + }).catch((error: BusinessError) => { + // 处理业务逻辑错误 + console.error('startAbilityByCallWithAccount failed, error.code: ${error.code}, error.message: ${error.message}'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.error('error.code: ${paramError.code}, error.message: ${paramError.message}'); + } + } +} + +``` + + +### startAbilityWithAccount +根据want和accountId启动Ability。 使用规则: - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 - 跨应用场景下,目标Ability的exported属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 - 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md) + **调用形式:** + +- startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void +起始版本: 9 +- startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\): void +起始版本: 9 +- startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\): void +起始版本: 10 +- startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\ +起始版本: 9 + + **模型约束:** 此接口仅可在stage模型下使用。 + **系统API:** 此接口为系统接口。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core + **需要权限:** ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| want | Want | true | 启动Ability的want信息。 | +| accountId | number | true | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount)。 | +| options | StartOptions | true | 启动Ability所携带的参数。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | 启动Ability的回调函数。 | +| Promise | | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 201 | | +| 202 | | +| 401 | | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000012 | The application is controlled. | +| 16000013 | The application is controlled by EDM. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + + **示例代码1:** +示例(callback): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import Want from '@ohos.app.ability.Want'; +import StartOptions from '@ohos.app.ability.StartOptions'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + + onForeground() { + let want: Want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' + }; + let accountId = 100; + let options: StartOptions = { + windowMode: 0 + }; + + try { + this.context.startAbilityWithAccount(want, accountId, options, (err: BusinessError) => { + if (err.code) { + // 处理业务逻辑错误 + console.error(`startAbilityWithAccount failed, code is ${err.code}, message is ${err.message}`); + return; + } + // 执行正常业务 + console.info('startAbilityWithAccount succeed'); + }); + } catch (err) { + // 处理入参错误异常 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`startAbilityWithAccount failed, code is ${code}, message is ${message}`); + } + } +} + +``` + + + **示例代码2:** +示例(Promise): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import Want from '@ohos.app.ability.Want'; +import StartOptions from '@ohos.app.ability.StartOptions'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + + onForeground() { + let want: Want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' + }; + let accountId = 100; + let options: StartOptions = { + windowMode: 0 + }; + + try { + this.context.startAbilityWithAccount(want, accountId, options) + .then(() => { + // 执行正常业务 + console.info('startAbilityWithAccount succeed'); + }) + .catch((err: BusinessError) => { + // 处理业务逻辑错误 + console.error(`startAbilityWithAccount failed, code is ${err.code}, message is ${err.message}`); + }); + } catch (err) { + // 处理入参错误异常 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`startAbilityWithAccount failed, code is ${code}, message is ${message}`); + } + } +} + +``` + + +### startAbilityForResultWithAccount +启动一个Ability并在该Ability销毁时返回执行结果。 + **调用形式:** + +- startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void +起始版本: 9 +- startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void +起始版本: 10 +- startAbilityForResultWithAccount( want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\ ): void +起始版本: 9 +- startAbilityForResultWithAccount( want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\ ): void +起始版本: 10 +- startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\ +起始版本: 9 +- startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\ +起始版本: 10 + + **模型约束:** 此接口仅可在stage模型下使用。 + **系统API:** 此接口为系统接口。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core + **需要权限:** ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| want | Want | true | 启动Ability的want信息。 | +| accountId | number | true | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount)。 | +| options | StartOptions | true | 启动Ability所携带的参数。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | 启动Ability后,Ability被销毁时的回调函数。 | +| Promise | Ability被销毁时的回调函数,包含AbilityResult参数。 | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 201 | | +| 202 | | +| 401 | | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | +| 16000012 | The application is controlled. | +| 16000013 | The application is controlled by EDM. | + + **示例代码1:** +示例(callback): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import Want from '@ohos.app.ability.Want'; +import StartOptions from '@ohos.app.ability.StartOptions'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + + onForeground() { + + let want: Want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' + }; + let accountId = 100; + let options: StartOptions = { + windowMode: 0 + }; + + try { + this.context.startAbilityForResultWithAccount(want, accountId, options, (err: BusinessError) => { + if (err.code) { + // 处理业务逻辑错误 + console.error(`startAbilityForResultWithAccount failed, code is ${err.code}, message is ${err.message}`); + return; + } + // 执行正常业务 + console.info('startAbilityForResultWithAccount succeed'); + }); + } catch (err) { + // 处理入参错误异常 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`startAbilityForResultWithAccount failed, code is ${code}, message is ${message}`); + } + } +} + +``` + + + **示例代码2:** +示例(Promise): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import common from '@ohos.app.ability.common'; +import Want from '@ohos.app.ability.Want'; +import StartOptions from '@ohos.app.ability.StartOptions'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + + onForeground() { + let want: Want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' + }; + let accountId = 100; + let options: StartOptions = { + windowMode: 0 + }; + + try { + this.context.startAbilityForResultWithAccount(want, accountId, options) + .then((result: common.AbilityResult) => { + // 执行正常业务 + console.info('startAbilityForResultWithAccount succeed'); + }) + .catch((err: BusinessError) => { + // 处理业务逻辑错误 + console.error(`startAbilityForResultWithAccount failed, code is ${err.code}, message is ${err.message}`); + }); + } catch (err) { + // 处理入参错误异常 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`startAbilityForResultWithAccount failed, code is ${code}, message is ${message}`); + } + } +} + +``` + + +### startServiceExtensionAbility +启动一个新的ServiceExtensionAbility。 + **调用形式:** + +- startServiceExtensionAbility(want: Want, callback: AsyncCallback\): void +起始版本: 9 +- startServiceExtensionAbility(want: Want, callback: AsyncCallback\): void +起始版本: 10 +- startServiceExtensionAbility(want: Want): Promise\ +起始版本: 9 +- startServiceExtensionAbility(want: Want): Promise\ +起始版本: 10 + + **模型约束:** 此接口仅可在stage模型下使用。 + **系统API:** 此接口为系统接口。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| want | Want | true | 启动ServiceExtensionAbility的want信息。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | 启动ServiceExtensionAbility的回调函数。 | +| Promise | | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 201 | | +| 202 | | +| 401 | | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | +| 16000004 | Can not start invisible component. | +| 16000012 | The application is controlled. | +| 16000013 | The application is controlled by EDM. | + + **示例代码1:** +示例(callback): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import Want from '@ohos.app.ability.Want'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + + onForeground() { + let want: Want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'ServiceExtensionAbility' + }; + + try { + this.context.startServiceExtensionAbility(want) + .then(() => { + // 执行正常业务 + console.info('startServiceExtensionAbility succeed'); + }) + .catch((err: BusinessError) => { + // 处理业务逻辑错误 + console.error(`startServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); + }); + } catch (err) { + // 处理入参错误异常 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`startServiceExtensionAbility failed, code is ${code}, message is ${message}`); + } + } +} + +``` + + + **示例代码2:** +示例(Promise): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import Want from '@ohos.app.ability.Want'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + + onForeground() { + let want: Want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'ServiceExtensionAbility' + }; + + try { + this.context.startServiceExtensionAbility(want) + .then(() => { + // 执行正常业务 + console.info('startServiceExtensionAbility succeed'); + }) + .catch((err: BusinessError) => { + // 处理业务逻辑错误 + console.error(`startServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); + }); + } catch (err) { + // 处理入参错误异常 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`startServiceExtensionAbility failed, code is ${code}, message is ${message}`); + } + } +} + +``` + + +### startServiceExtensionAbilityWithAccount +启动一个新的ServiceExtensionAbility。 + **调用形式:** + +- startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void +起始版本: 9 +- startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void +起始版本: 10 +- startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\ +起始版本: 9 +- startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\ +起始版本: 10 + + **模型约束:** 此接口仅可在stage模型下使用。 + **系统API:** 此接口为系统接口。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core + **需要权限:** ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| want | Want | true | 启动ServiceExtensionAbility的want信息。 | +| accountId | number | true | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount)。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | 启动ServiceExtensionAbility的回调函数。 | +| Promise | | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 201 | | +| 202 | | +| 401 | | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | +| 16000004 | Can not start invisible component. | +| 16000012 | The application is controlled. | +| 16000013 | The application is controlled by EDM. | + + **示例代码1:** +示例(callback): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import Want from '@ohos.app.ability.Want'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + + onForeground() { + let want: Want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'ServiceExtensionAbility' + }; + let accountId = 100; + + try { + this.context.startServiceExtensionAbilityWithAccount(want, accountId, (err: BusinessError) => { + if (err.code) { + // 处理业务逻辑错误 + console.error(`startServiceExtensionAbilityWithAccount failed, code is ${err.code}, message is ${err.message}`); + return; + } + // 执行正常业务 + console.info('startServiceExtensionAbilityWithAccount succeed'); + }); + } catch (err) { + // 处理入参错误异常 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`startServiceExtensionAbilityWithAccount failed, code is ${code}, message is ${message}`); + } + } +} + +``` + + + **示例代码2:** +示例(Promise): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import Want from '@ohos.app.ability.Want'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + + onForeground() { + let want: Want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'ServiceExtensionAbility' + }; + let accountId = 100; + + try { + this.context.startServiceExtensionAbilityWithAccount(want, accountId) + .then(() => { + // 执行正常业务 + console.info('startServiceExtensionAbilityWithAccount succeed'); + }) + .catch((err: BusinessError) => { + // 处理业务逻辑错误 + console.error(`startServiceExtensionAbilityWithAccount failed, code is ${err.code}, message is ${err.message}`); + }); + } catch (err) { + // 处理入参错误异常 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`startServiceExtensionAbilityWithAccount failed, code is ${code}, message is ${message}`); + } + } +} + +``` + + +### stopServiceExtensionAbility +停止同一应用程序内的服务。 + **调用形式:** + +- stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void +起始版本: 9 +- stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void +起始版本: 10 +- stopServiceExtensionAbility(want: Want): Promise\ +起始版本: 9 +- stopServiceExtensionAbility(want: Want): Promise\ +起始版本: 10 + + **模型约束:** 此接口仅可在stage模型下使用。 + **系统API:** 此接口为系统接口。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| want | Want | true | 停止ServiceExtensionAbility的want信息。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | 停止ServiceExtensionAbility的回调函数。 | +| Promise | | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 202 | | +| 401 | | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | +| 201 | | +| 16000004 | Can not start invisible component. | +| 16000012 | The application is controlled. | +| 16000013 | The application is controlled by EDM. | + + **示例代码1:** +示例(callback): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import Want from '@ohos.app.ability.Want'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + +onForeground() { + let want: Want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'ServiceExtensionAbility' + }; + + try { + this.context.stopServiceExtensionAbility(want, (err: BusinessError) => { + if (err.code) { + // 处理业务逻辑错误 + console.error(`stopServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); + return; + } + // 执行正常业务 + console.info('stopServiceExtensionAbility succeed'); + }); + } catch (err) { + // 处理入参错误异常 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`stopServiceExtensionAbility failed, code is ${code}, message is ${message}`); + } +} +} + +``` + + + **示例代码2:** +示例(Promise): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import Want from '@ohos.app.ability.Want'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + +onForeground() { + let want: Want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'ServiceExtensionAbility' + }; + + try { + this.context.stopServiceExtensionAbility(want) + .then(() => { + // 执行正常业务 + console.info('stopServiceExtensionAbility succeed'); + }) + .catch((err: BusinessError) => { + // 处理业务逻辑错误 + console.error(`stopServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); + }); + } catch (err) { + // 处理入参错误异常 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`stopServiceExtensionAbility failed, code is ${code}, message is ${message}`); + } +} +} + +``` + + +### stopServiceExtensionAbilityWithAccount +停止同一应用程序内指定账户的服务。 + **调用形式:** + +- stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void +起始版本: 9 +- stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void +起始版本: 10 +- stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\ +起始版本: 9 +- stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\ +起始版本: 10 + + **模型约束:** 此接口仅可在stage模型下使用。 + **系统API:** 此接口为系统接口。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core + **需要权限:** ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| want | Want | true | 停止ServiceExtensionAbility的want信息。 | +| accountId | number | true | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount)。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | 停止ServiceExtensionAbility的回调函数。 | +| Promise | | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 201 | | +| 202 | | +| 401 | | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | +| 16000004 | Can not start invisible component. | + + **示例代码1:** +示例(callback): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import Want from '@ohos.app.ability.Want'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + + onForeground() { + let want: Want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'ServiceExtensionAbility' + }; + let accountId = 100; + + try { + this.context.stopServiceExtensionAbilityWithAccount(want, accountId, (err: BusinessError) => { + if (err.code) { + // 处理业务逻辑错误 + console.error(`stopServiceExtensionAbilityWithAccount failed, code is ${err.code}, message is ${err.message}`); + return; + } + // 执行正常业务 + console.info('stopServiceExtensionAbilityWithAccount succeed'); + }); + } catch (err) { + // 处理入参错误异常 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`stopServiceExtensionAbilityWithAccount failed, code is ${code}, message is ${message}`); + } + } +} + +``` + + + **示例代码2:** +示例(Promise): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import Want from '@ohos.app.ability.Want'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + + onForeground() { + let want: Want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'ServiceExtensionAbility' + }; + let accountId = 100; + + try { + this.context.stopServiceExtensionAbilityWithAccount(want, accountId) + .then(() => { + // 执行正常业务 + console.info('stopServiceExtensionAbilityWithAccount succeed'); + }) + .catch((err: BusinessError) => { + // 处理业务逻辑错误 + console.error(`stopServiceExtensionAbilityWithAccount failed, code is ${err.code}, message is ${err.message}`); + }); + } catch (err) { + // 处理入参错误异常 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`stopServiceExtensionAbilityWithAccount failed, code is ${code}, message is ${message}`); + } + } +} + +``` + + +### connectServiceExtensionAbilityWithAccount +将当前Ability连接到一个使用AbilityInfo.AbilityType.SERVICE模板的指定account的Ability。 + **调用形式:** +- connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number + + **模型约束:** 此接口仅可在stage模型下使用。 + **系统API:** 此接口为系统接口。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core + **需要权限:** ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| want | Want | true | 启动Ability的want信息。 | +| accountId | number | true | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount)。 | +| options | ConnectOptions | true | 与ServiceExtensionAbility建立连接后回调函数的实例。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| number | 返回Ability连接的结果code。 | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 201 | | +| 202 | | +| 401 | | +| 16000001 | The specified ability does not exist. | +| 16000005 | The specified process does not have the permission. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | + + **示例代码:** +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import common from '@ohos.app.ability.common'; +import Want from '@ohos.app.ability.Want'; +import { BusinessError } from '@ohos.base'; +import rpc from '@ohos.rpc'; + +export default class EntryAbility extends UIAbility { + + onForeground() { + let want: Want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'ServiceExtensionAbility' + }; + let accountId = 100; + let commRemote: rpc.IRemoteObject; + let options: common.ConnectOptions = { + onConnect(elementName, remote) { + commRemote = remote; + console.info('onConnect...') + }, + onDisconnect(elementName) { + console.info('onDisconnect...') + }, + onFailed(code) { + console.info('onFailed...') + } + }; + let connection: number; + try { + connection = this.context.connectServiceExtensionAbilityWithAccount(want, accountId, options); + } catch (err) { + // 处理入参错误异常 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`connectServiceExtensionAbility failed, code is ${code}, message is ${message}`); + } + } +} + +``` + + +### connectServiceExtensionAbilityWithAccount(10+) + **调用形式:** +- connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number + + **模型约束:** 此接口仅可在stage模型下使用。 + **系统API:** 此接口为系统接口。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core + **需要权限:** ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| want | Want | true | | +| accountId | number | true | | +| options | ConnectOptions | true | | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| number | | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 201 | | +| 202 | | +| 401 | | +| 16000001 | | +| 16000002 | | +| 16000004 | | +| 16000005 | | +| 16000006 | | +| 16000008 | | +| 16000011 | | +| 16000050 | | +| 16000053 | | +| 16000055 | | + +### setMissionIcon +设置当前ability在任务中显示的图标, 图标大小最大为600M。 + **调用形式:** + +- setMissionIcon(icon: image.PixelMap, callback: AsyncCallback\): void +起始版本: 9 +- setMissionIcon(icon: image.PixelMap, callback: AsyncCallback\): void +起始版本: 10 +- setMissionIcon(icon: image.PixelMap): Promise\ +起始版本: 9 +- setMissionIcon(icon: image.PixelMap): Promise\ +起始版本: 10 + + **模型约束:** 此接口仅可在stage模型下使用。 + **系统API:** 此接口为系统接口。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| icon | image.PixelMap | true | 在最近的任务中显示的ability图标。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | 指定的回调函数的结果。 | +| Promise | 返回一个Promise,包含接口的结果。 | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 401 | | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 202 | | + + **示例代码1:** +示例(callback): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base'; +import image from '@ohos.multimedia.image'; + +export default class EntryAbility extends UIAbility { + onForeground() { + let imagePixelMap: image.PixelMap; + let color = new ArrayBuffer(0); + image.createPixelMap(color, { + size: { + height: 100, + width: 100 + } + }).then((data) => { + imagePixelMap = data; + this.context.setMissionIcon(imagePixelMap, (err: BusinessError) => { + console.error(`setMissionLabel failed, code is ${err.code}, message is ${err.message}`); + }) + }) + .catch((err: BusinessError) => { + console.error(`createPixelMap failed, code is ${err.code}, message is ${err.message}`); + }); + } +} + +``` + + + **示例代码2:** +示例(Promise): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base'; +import image from '@ohos.multimedia.image'; + +export default class EntryAbility extends UIAbility { + onForeground() { + let imagePixelMap: image.PixelMap; + let color = new ArrayBuffer(0); + image.createPixelMap(color, { + size: { + height: 100, + width: 100 + } + }).then((data) => { + imagePixelMap = data; + this.context.setMissionIcon(imagePixelMap) + .then(() => { + console.info('setMissionIcon succeed'); + }) + .catch((err: BusinessError) => { + console.error(`setMissionLabel failed, code is ${err.code}, message is ${err.message}`); + }); + }) + .catch((err: BusinessError) => { + console.error(`createPixelMap failed, code is ${err.code}, message is ${err.message}`); + }); + } +} + +``` + + +### startRecentAbility +启动一个指定的Ability,如果这个Ability有多个实例,将拉起最近启动的那个实例。 使用规则: - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 - 跨应用场景下,目标Ability的exported属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 - 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md) + **调用形式:** + +- startRecentAbility(want: Want, callback: AsyncCallback\): void +起始版本: 9 +- startRecentAbility(want: Want, callback: AsyncCallback\): void +起始版本: 10 +- startRecentAbility(want: Want, options: StartOptions, callback: AsyncCallback\): void +起始版本: 9 +- startRecentAbility(want: Want, options: StartOptions, callback: AsyncCallback\): void +起始版本: 10 +- startRecentAbility(want: Want, options?: StartOptions): Promise\ +起始版本: 9 +- startRecentAbility(want: Want, options?: StartOptions): Promise\ +起始版本: 10 + + **模型约束:** 此接口仅可在stage模型下使用。 + **系统API:** 此接口为系统接口。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| want | Want | true | 需要启动Ability的want信息。 | +| options | StartOptions | true | 启动Ability所携带的参数。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | 指定的回调函数的结果。 | +| Promise | | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 401 | | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | +| 201 | | +| 16000012 | The application is controlled. | +| 16000013 | The application is controlled by EDM. | + + **示例代码1:** +示例(callback): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import Want from '@ohos.app.ability.Want'; +import StartOptions from '@ohos.app.ability.StartOptions'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + + onForeground() { + let want: Want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' + }; + let options: StartOptions = { + windowMode: 0 + }; + + try { + this.context.startRecentAbility(want, options, (err: BusinessError) => { + if (err.code) { + // 处理业务逻辑错误 + console.error(`startRecentAbility failed, code is ${err.code}, message is ${err.message}`); + return; + } + // 执行正常业务 + console.info('startRecentAbility succeed'); + }); + } catch (err) { + // 处理入参错误异常 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`startRecentAbility failed, code is ${code}, message is ${message}`); + } + } +} + +``` + + + **示例代码2:** +示例(Promise): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import Want from '@ohos.app.ability.Want'; +import StartOptions from '@ohos.app.ability.StartOptions'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + + onForeground() { + let want: Want = { + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' + }; + let options: StartOptions = { + windowMode: 0, + }; + + try { + this.context.startRecentAbility(want, options) + .then(() => { + // 执行正常业务 + console.info('startRecentAbility succeed'); + }) + .catch((err: BusinessError) => { + // 处理业务逻辑错误 + console.error(`startRecentAbility failed, code is ${err.code}, message is ${err.message}`); + }); + } catch (err) { + // 处理入参错误异常 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`startRecentAbility failed, code is ${code}, message is ${message}`); + } + } +} + +``` + diff --git a/zh-cn/application-dev/reference/apis-new/application/UIAbilityContext.md b/zh-cn/application-dev/reference/apis-new/application/UIAbilityContext.md new file mode 100644 index 0000000000000000000000000000000000000000..2c7b0ad07e1823f6c4228fac58ab8856d12ad4f3 --- /dev/null +++ b/zh-cn/application-dev/reference/apis-new/application/UIAbilityContext.md @@ -0,0 +1,1250 @@ +# UIAbilityContext +UIAbilityContext是[UIAbility](js-apis-app-ability-uiAbility.md)的上下文环境,继承自[Context](js-apis-inner-application-context.md),提供UIAbility的相关配置信息以及操作UIAbility和ServiceExtensionAbility的方法,如启动UIAbility,停止当前UIAbilityContext所属的UIAbility,启动、停止、连接、断开连接ServiceExtensionAbility等。 +> **说明** +>本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本 + +## UIAbilityContext + **模型约束:** 此接口仅可在stage模型下使用。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core +### 属性 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core + **模型约束:** 本模块接口仅可在Stage模型下使用。 +| 名称 | 类型 | 只读 | 必填 | 说明 | +| --------| --------| --------| --------| --------| +| abilityInfo | AbilityInfo | false | true | UIAbility的相关信息。 | +| currentHapModuleInfo | HapModuleInfo | false | true | 当前HAP的信息。 | +| config | Configuration | false | true | 与UIAbility相关的配置信息,如语言、颜色模式等。 | + +### startAbility +启动Ability。使用规则: - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 - 跨应用场景下,目标Ability的exported属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 - 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md) - 跨任务链启动时,如果需要跨任务链进行返回,需要参考[Want](js-apis-app-ability-want.md)中的parameter参数用法。 + **调用形式:** + +- startAbility(want: Want, callback: AsyncCallback\): void +起始版本: 9 +- startAbility(want: Want, callback: AsyncCallback\): void +起始版本: 10 +- startAbility(want: Want, options: StartOptions, callback: AsyncCallback\): void +起始版本: 9 +- startAbility(want: Want, options: StartOptions, callback: AsyncCallback\): void +起始版本: 10 +- startAbility(want: Want, options?: StartOptions): Promise\ +起始版本: 9 +- startAbility(want: Want, options?: StartOptions): Promise\ +起始版本: 10 + + **模型约束:** 此接口仅可在stage模型下使用。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| want | Want | true | 启动Ability的want信息。 | +| options | StartOptions | true | 启动Ability所携带的参数。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | callback形式返回启动结果。 | +| Promise | Promise形式返回启动结果。 | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 401 | | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | +| 201 | | +| 16000012 | The application is controlled. | +| 16000013 | The application is controlled by EDM. | + + **示例代码1:** +示例(callback): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import Want from '@ohos.app.ability.Want'; +import StartOptions from '@ohos.app.ability.StartOptions'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + + onForeground() { + let want: Want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' + }; + let options: StartOptions = { + windowMode: 0 + }; + + try { + this.context.startAbility(want, options, (err: BusinessError) => { + if (err.code) { + // 处理业务逻辑错误 + console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); + return; + } + // 执行正常业务 + console.info('startAbility succeed'); + }); + } catch (err) { + // 处理入参错误异常 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`startAbility failed, code is ${code}, message is ${message}`); + } + } +} + +``` + + + **示例代码2:** +示例(Promise): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import Want from '@ohos.app.ability.Want'; +import StartOptions from '@ohos.app.ability.StartOptions'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + + onForeground() { + let want: Want = { + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' + }; + let options: StartOptions = { + windowMode: 0, + }; + + try { + this.context.startAbility(want, options) + .then(() => { + // 执行正常业务 + console.info('startAbility succeed'); + }) + .catch((err: BusinessError) => { + // 处理业务逻辑错误 + console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); + }); + } catch (err) { + // 处理入参错误异常 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`startAbility failed, code is ${code}, message is ${message}`); + } + } +} + +``` + + +### startAbilityByCall +启动指定Ability至前台或后台,同时获取其Caller通信接口,调用方可使用Caller与被启动的Ability进行通信。 使用规则: - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 - 跨应用场景下,目标Ability的exported属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 - 同设备与跨设备场景下,该接口的使用规则存在差异,详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md) + **调用形式:** + +- startAbilityByCall(want: Want): Promise\ +起始版本: 9 +- startAbilityByCall(want: Want): Promise\ +起始版本: 10 + + **模型约束:** 此接口仅可在stage模型下使用。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core + **需要权限:** ohos.permission.ABILITY_BACKGROUND_COMMUNICATION + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| want | Want | true | 传入需要启动的Ability的信息,包含abilityName、moduleName、bundleName、deviceId(可选)、parameters(可选),其中deviceId缺省或为空表示启动本地Ability,parameters缺省或为空表示后台启动Ability。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | | +| Promise | 获取要通讯的caller对象。 | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 201 | | +| 401 | | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | +| 16000012 | The application is controlled. | +| 16000013 | The application is controlled by EDM. | + + **示例代码:** +示例(Promise): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { Caller } from '@ohos.app.ability.UIAbility'; +import Want from '@ohos.app.ability.Want'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + + onForeground() { + let caller: Caller; + + // 后台启动Ability,不配置parameters + let wantBackground: Want = { + bundleName: 'com.example.myapplication', + moduleName: 'entry', + abilityName: 'EntryAbility', + deviceId: '' + }; + + try { + this.context.startAbilityByCall(wantBackground) + .then((obj: Caller) => { + // 执行正常业务 + caller = obj; + console.info('startAbilityByCall succeed'); + }).catch((err: BusinessError) => { + // 处理业务逻辑错误 + console.error(`startAbilityByCall failed, code is ${err.code}, message is ${err.message}`); + }); + } catch (err) { + // 处理入参错误异常 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`startAbilityByCall failed, code is ${code}, message is ${message}`); + } + } +} + +``` + + +### startAbilityForResult +启动一个Ability。Ability被启动后,有如下情况: - 正常情况下可通过调用[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)接口使之终止并且返回结果给调用方。 - 异常情况下比如杀死Ability会返回异常信息给调用方, 异常信息中resultCode为-1。 - 如果被启动的Ability模式是单实例模式, 不同应用多次调用该接口启动这个Ability,当这个Ability调用[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)接口使之终止时,只将正常结果返回给最后一个调用方, 其它调用方返回异常信息, 异常信息中resultCode为-1。 使用规则: - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 - 跨应用场景下,目标Ability的exported属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 - 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md) + **调用形式:** + +- startAbilityForResult(want: Want, callback: AsyncCallback\): void +起始版本: 9 +- startAbilityForResult(want: Want, callback: AsyncCallback\): void +起始版本: 10 +- startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback\): void +起始版本: 9 +- startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback\): void +起始版本: 10 +- startAbilityForResult(want: Want, options?: StartOptions): Promise\ +起始版本: 9 +- startAbilityForResult(want: Want, options?: StartOptions): Promise\ +起始版本: 10 + + **模型约束:** 此接口仅可在stage模型下使用。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| want | Want | true | 启动Ability的want信息。 | +| options | StartOptions | true | 启动Ability所携带的参数。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | 执行结果回调函数。 | +| Promise | Promise形式返回执行结果。 | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 401 | | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | +| 201 | | +| 16000012 | The application is controlled. | +| 16000013 | The application is controlled by EDM. | + + **示例代码1:** +示例(callback): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import common from '@ohos.app.ability.common'; +import Want from '@ohos.app.ability.Want'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + + onForeground() { + let want: Want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' + }; + + try { + this.context.startAbilityForResult(want, (err: BusinessError, result: common.AbilityResult) => { + if (err.code) { + // 处理业务逻辑错误 + console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`); + return; + } + // 执行正常业务 + console.info('startAbilityForResult succeed'); + }); + } catch (err) { + // 处理入参错误异常 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`startAbilityForResult failed, code is ${code}, message is ${message}`); + } + } +} + +``` + + + **示例代码2:** +示例(Promise): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import common from '@ohos.app.ability.common'; +import Want from '@ohos.app.ability.Want'; +import StartOptions from '@ohos.app.ability.StartOptions'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + + onForeground() { + let want: Want = { + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' + }; + let options: StartOptions = { + windowMode: 0, + }; + + try { + this.context.startAbilityForResult(want, options) + .then((result: common.AbilityResult) => { + // 执行正常业务 + console.info('startAbilityForResult succeed'); + }) + .catch((err: BusinessError) => { + // 处理业务逻辑错误 + console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`); + }); + } catch (err) { + // 处理入参错误异常 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`startAbilityForResult failed, code is ${code}, message is ${message}`); + } + } +} + +``` + + +### terminateSelf +停止Ability自身。 + **调用形式:** + +- terminateSelf(callback: AsyncCallback\): void +起始版本: 9 +- terminateSelf(callback: AsyncCallback\): void +起始版本: 10 +- terminateSelf(): Promise\ +起始版本: 9 +- terminateSelf(): Promise\ +起始版本: 10 + + **模型约束:** 此接口仅可在stage模型下使用。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | 停止Ability自身的回调函数。 | +| Promise | 停止Ability自身的回调函数。 | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 401 | | +| 16000001 | The specified ability does not exist. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | + + **示例代码1:** +示例(callback): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + + onForeground() { + try { + this.context.terminateSelf((err: BusinessError) => { + if (err.code) { + // 处理业务逻辑错误 + console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`); + return; + } + // 执行正常业务 + console.info('terminateSelf succeed'); + }); + } catch (err) { + // 捕获同步的参数错误 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`terminateSelf failed, code is ${code}, message is ${message}`); + } + } +} + +``` + + + **示例代码2:** +示例(Promise): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + + onForeground() { + try { + this.context.terminateSelf() + .then(() => { + // 执行正常业务 + console.info('terminateSelf succeed'); + }) + .catch((err: BusinessError) => { + // 处理业务逻辑错误 + console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`); + }); + } catch (err) { + // 捕获同步的参数错误 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`terminateSelf failed, code is ${code}, message is ${message}`); + } + } +} + +``` + + +### terminateSelfWithResult +停止当前的Ability。如果该Ability是通过调用[startAbilityForResult](#uiabilitycontextstartabilityforresult)接口被拉起的,调用terminateSelfWithResult接口时会将结果返回给调用者,如果该Ability不是通过调用[startAbilityForResult](#uiabilitycontextstartabilityforresult)接口被拉起的,调用terminateSelfWithResult接口时不会有结果返回给调用者。 + **调用形式:** + +- terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback\): void +起始版本: 9 +- terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback\): void +起始版本: 10 +- terminateSelfWithResult(parameter: AbilityResult): Promise\ +起始版本: 9 +- terminateSelfWithResult(parameter: AbilityResult): Promise\ +起始版本: 10 + + **模型约束:** 此接口仅可在stage模型下使用。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| parameter | AbilityResult | true | 返回给调用startAbilityForResult接口调用方的相关信息。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | callback形式返回停止结果。 | +| Promise | promise形式返回停止结果。 | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 401 | | +| 16000001 | The specified ability does not exist. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | + + **示例代码1:** +示例(callback): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import common from '@ohos.app.ability.common'; +import Want from '@ohos.app.ability.Want'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + + onForeground() { + let want: Want = { + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' + }; + let resultCode = 100; + // 返回给接口调用方AbilityResult信息 + let abilityResult = { + want, + resultCode + }; + + try { + this.context.terminateSelfWithResult(abilityResult, (err: BusinessError) => { + if (err.code) { + // 处理业务逻辑错误 + console.error(`terminateSelfWithResult failed, code is ${err.code}, message is ${err.message}`); + return; + } + // 执行正常业务 + console.info('terminateSelfWithResult succeed'); + }); + } catch (err) { + // 处理入参错误异常 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`terminateSelfWithResult failed, code is ${code}, message is ${message}`); + } + } +} + +``` + + + **示例代码2:** +示例(Promise): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import common from '@ohos.app.ability.common'; +import Want from '@ohos.app.ability.Want'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + + onForeground() { + let want: Want = { + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' + }; + let resultCode = 100; + // 返回给接口调用方AbilityResult信息 + let abilityResult = { + want, + resultCode + }; + + try { + this.context.terminateSelfWithResult(abilityResult) + .then(() => { + // 执行正常业务 + console.info('terminateSelfWithResult succeed'); + }) + .catch((err: BusinessError) => { + // 处理业务逻辑错误 + console.error(`terminateSelfWithResult failed, code is ${err.code}, message is ${err.message}`); + }); + } catch (err) { + // 处理入参错误异常 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`terminateSelfWithResult failed, code is ${code}, message is ${message}`); + } + } +} + +``` + + +### connectServiceExtensionAbility +将当前Ability连接到一个使用AbilityInfo.AbilityType.SERVICE模板的Ability。 + **调用形式:** +- connectServiceExtensionAbility(want: Want, options: ConnectOptions): number + + **模型约束:** 此接口仅可在stage模型下使用。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| want | Want | true | 连接ServiceExtensionAbility的want信息。 | +| options | ConnectOptions | true | 与ServiceExtensionAbility建立连接后回调函数的实例。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| number | 返回Ability连接的结果code。 | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 201 | | +| 401 | | +| 16000001 | The specified ability does not exist. | +| 16000005 | The specified process does not have the permission. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | + + **示例代码:** +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import common from '@ohos.app.ability.common'; +import Want from '@ohos.app.ability.Want'; +import { BusinessError } from '@ohos.base'; +import rpc from '@ohos.rpc'; + +export default class EntryAbility extends UIAbility { + + onForeground() { + let want: Want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'ServiceExtensionAbility' + }; + let commRemote: rpc.IRemoteObject; + let options: common.ConnectOptions = { + onConnect(elementName, remote) { + commRemote = remote; + console.info('onConnect...') + }, + onDisconnect(elementName) { + console.info('onDisconnect...') + }, + onFailed(code) { + console.info('onFailed...') + } + }; + let connection: number; + try { + connection = this.context.connectServiceExtensionAbility(want, options); + } catch (err) { + // 处理入参错误异常 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`connectServiceExtensionAbility failed, code is ${code}, message is ${message}`); + } + } +} + +``` + + +### connectServiceExtensionAbility(10+) + **调用形式:** +- connectServiceExtensionAbility(want: Want, options: ConnectOptions): number + + **模型约束:** 此接口仅可在stage模型下使用。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| want | Want | true | | +| options | ConnectOptions | true | | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| number | | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 201 | | +| 401 | | +| 16000001 | | +| 16000002 | | +| 16000004 | | +| 16000005 | | +| 16000006 | | +| 16000008 | | +| 16000011 | | +| 16000050 | | +| 16000053 | | +| 16000055 | | + +### disconnectServiceExtensionAbility +断开与ServiceExtensionAbility的连接,断开连接之后需要将连接成功时返回的remote对象置空。 + **调用形式:** + +- disconnectServiceExtensionAbility(connection: number, callback: AsyncCallback\): void +起始版本: 9 +- disconnectServiceExtensionAbility(connection: number): Promise\ +起始版本: 9 + + **模型约束:** 此接口仅可在stage模型下使用。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| connection | number | true | 连接的ServiceExtensionAbility的数字代码,即connectServiceExtensionAbility返回的connectionId。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | callback形式返回断开连接的结果。 | +| Promise | 返回执行结果。 | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 401 | | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | + + **示例代码1:** +示例(callback): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base'; +import rpc from '@ohos.rpc'; + +export default class EntryAbility extends UIAbility { + + onForeground() { + // connection为connectServiceExtensionAbility中的返回值 + let connection = 1; + let commRemote: rpc.IRemoteObject | null; + + try { + this.context.disconnectServiceExtensionAbility(connection, (err: BusinessError) => { + commRemote = null; + if (err.code) { + // 处理业务逻辑错误 + console.error(`disconnectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); + return; + } + // 执行正常业务 + console.info('disconnectServiceExtensionAbility succeed'); + }); + } catch (err) { + commRemote = null; + // 处理入参错误异常 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`disconnectServiceExtensionAbility failed, code is ${code}, message is ${message}`); + } + } +} + +``` + + + **示例代码2:** +示例(Promise): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base'; +import rpc from '@ohos.rpc'; + +export default class EntryAbility extends UIAbility { + + onForeground() { + // connection为connectServiceExtensionAbility中的返回值 + let connection = 1; + let commRemote: rpc.IRemoteObject | null; + + try { + this.context.disconnectServiceExtensionAbility(connection).then(() => { + commRemote = null; + // 执行正常业务 + console.info('disconnectServiceExtensionAbility succeed'); + }).catch((err: BusinessError) => { + // 处理业务逻辑错误 + console.error(`disconnectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); + }) + } catch (err) { + commRemote = null; + // 处理入参错误异常 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`disconnectServiceExtensionAbility failed, code is ${code}, message is ${message}`); + } + } +} + +``` + + +### setMissionLabel +设置UIAbility在任务中显示的名称。 + **调用形式:** + +- setMissionLabel(label: string, callback: AsyncCallback\): void +起始版本: 9 +- setMissionLabel(label: string): Promise\ +起始版本: 9 + + **模型约束:** 此接口仅可在stage模型下使用。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| label | string | true | 显示名称。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | 回调函数,返回接口调用是否成功的结果。 | +| Promise | 返回一个Promise,包含接口的结果。 | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 401 | | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | + + **示例代码1:** +示例(callback): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + + onCreate(want, launchParam) { + this.context.setMissionLabel('test', (result: BusinessError) => { + console.info(`setMissionLabel: ${JSON.stringify(result)}`); + }); + } +} + +``` + + + **示例代码2:** +示例(Promise): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + +onCreate(want, launchParam) { + this.context.setMissionLabel('test').then(() => { + console.info('success'); + }).catch((err: BusinessError) => { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`setMissionLabel failed, code is ${code}, message is ${message}`); + }); +} +} + +``` + + +### setMissionContinueState(10+) +设置UIAbility任务中流转状态。 + **调用形式:** + +- setMissionContinueState(state: AbilityConstant.ContinueState, callback: AsyncCallback\): void +起始版本: 10 +- setMissionContinueState(state: AbilityConstant.ContinueState): Promise\ +起始版本: 10 + + **模型约束:** 此接口仅可在stage模型下使用。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| state | AbilityConstant.ContinueState | true | 流转状态。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | 回调函数,返回接口调用是否成功的结果。 | +| Promise | 返回一个Promise,包含接口的结果。 | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 401 | | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | + + **示例代码1:** +示例(callback): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import AbilityConstant from '@ohos.app.ability.AbilityConstant'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + onForeground() { + this.context.setMissionContinueState(AbilityConstant.ContinueState.INACTIVE, (result: BusinessError) => { + console.info(`setMissionContinueState: ${JSON.stringify(result)}`); + }); + } +} + +``` + + + **示例代码2:** +示例(Promise): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import AbilityConstant from '@ohos.app.ability.AbilityConstant'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + onForeground() { + this.context.setMissionContinueState(AbilityConstant.ContinueState.INACTIVE).then(() => { + console.info('success'); + }).catch((err: BusinessError) => { + console.error(`setMissionContinueState failed, code is ${err.code}, message is ${err.message}`); + }); + } +} + +``` + + +### restoreWindowStage +恢复UIAbility中的WindowStage数据。 + **调用形式:** +- restoreWindowStage(localStorage: LocalStorage): void + + **模型约束:** 此接口仅可在stage模型下使用。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| localStorage | LocalStorage | true | 用于恢复window stage的存储数据。 | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 401 | | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | + + **示例代码:** +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + onForeground() { + let storage = new LocalStorage(); + this.context.restoreWindowStage(storage); + } +} + +``` + + +### isTerminating +查询UIAbility是否在terminating状态。 + **调用形式:** +- isTerminating(): boolean + + **模型约束:** 此接口仅可在stage模型下使用。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| boolean | true:ability当前处于terminating状态;false:不处于terminating状态。 | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 16000011 | The context does not exist. | + + **示例代码:** +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + onForeground() { + let isTerminating: boolean = this.context.isTerminating(); + console.info(`ability state is ${isTerminating}`); + } +} + +``` + + +### requestDialogService +启动一个支持模态弹框的ServiceExtensionAbility。ServiceExtensionAbility被启动后,应用弹出模态弹框,通过调用[setRequestResult](js-apis-app-ability-dialogRequest.md#requestcallbacksetrequestresult)接口返回结果给调用者。 +使用规则: - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限。 - 跨应用场景下,目标Ability的exported属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限。 - 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。 + **调用形式:** +- requestDialogService(want: Want, result: AsyncCallback\): void + + **模型约束:** 此接口仅可在stage模型下使用。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| want | Want | true | 启动ServiceExtensionAbility的want信息。 | +| result | AsyncCallback | true | 执行结果回调函数。 | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 401 | | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + + **示例代码:** +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import dialogRequest from '@ohos.app.ability.dialogRequest'; +import Want from '@ohos.app.ability.Want'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + onForeground() { + let want: Want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'AuthAccountServiceExtension' + }; + + try { + this.context.requestDialogService(want, (err: BusinessError, result: dialogRequest.RequestResult) => { + if (err.code) { + // 处理业务逻辑错误 + console.error(`requestDialogService failed, code is ${err.code}, message is ${err.message}`); + return; + } + // 执行正常业务 + console.info(`requestDialogService succeed, result = ${JSON.stringify(result)}`); + }); + } catch (err) { + // 处理入参错误异常 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`requestDialogService failed, code is ${code}, message is ${message}`); + } + } +} + +``` + + +### requestDialogService(10+) + **调用形式:** +- requestDialogService(want: Want, result: AsyncCallback\): void + + **模型约束:** 此接口仅可在stage模型下使用。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| want | Want | true | | +| result | AsyncCallback | true | | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 201 | | +| 401 | | +| 16000001 | | +| 16000002 | | +| 16000004 | | +| 16000005 | | +| 16000006 | | +| 16000008 | | +| 16000009 | | +| 16000010 | | +| 16000011 | | +| 16000012 | | +| 16000013 | | +| 16000050 | | +| 16000053 | | +| 16000055 | | +| 16200001 | | + +### requestDialogService +启动一个支持模态弹框的ServiceExtensionAbility。ServiceExtensionAbility被启动后,应用弹出模态弹框,通过调用[setRequestResult](js-apis-app-ability-dialogRequest.md#requestcallbacksetrequestresult)接口返回结果给调用者。 使用规则: - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限。 - 跨应用场景下,目标Ability的exported属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限。 - 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。 + **调用形式:** + +- requestDialogService(want: Want): Promise\ +起始版本: 9 +- requestDialogService(want: Want): Promise\ +起始版本: 10 + + **模型约束:** 此接口仅可在stage模型下使用。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| want | Want | true | 启动ServiceExtensionAbility的want信息。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | | +| Promise | Promise形式返回执行结果。 | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 401 | | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | +| 201 | | +| 16000012 | The application is controlled. | +| 16000013 | The application is controlled by EDM. | + + **示例代码:** +示例(Promise): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import dialogRequest from '@ohos.app.ability.dialogRequest'; +import Want from '@ohos.app.ability.Want'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { + + onForeground() { + let want: Want = { + bundleName: 'com.example.myapplication', + abilityName: 'AuthAccountServiceExtension' + }; + + try { + this.context.requestDialogService(want) + .then((result: dialogRequest.RequestResult) => { + // 执行正常业务 + console.info(`requestDialogService succeed, result = ${JSON.stringify(result)}`); + }) + .catch((err: BusinessError) => { + // 处理业务逻辑错误 + console.error(`requestDialogService failed, code is ${err.code}, message is ${err.message}`); + }); + } catch (err) { + // 处理入参错误异常 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`requestDialogService failed, code is ${code}, message is ${message}`); + } + } +} + +``` + + +### reportDrawnCompleted(10+) +当页面加载完成(loadContent成功)时,为开发者提供打点功能。 + **调用形式:** + +- reportDrawnCompleted(callback: AsyncCallback\): void +起始版本: 10 + + **模型约束:** 此接口仅可在stage模型下使用。 + **系统能力:** SystemCapability.Ability.AbilityRuntime.Core + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | 页面加载完成打点的回调函数。 | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | + + **示例代码:** +示例(callback): +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import window from '@ohos.window'; +import { BusinessError } from '@ohos.base'; + +export default class EntryAbility extends UIAbility { +onWindowStageCreate(windowStage: window.WindowStage) { + windowStage.loadContent('pages/Index', (err, data) => { + if (err.code) { + return; + } + try { + this.context.reportDrawnCompleted((err) => { + if (err.code) { + // 处理业务逻辑错误 + console.error(`reportDrawnCompleted failed, code is ${err.code}, message is ${err.message}`); + return; + } + // 执行正常业务 + console.info('reportDrawnCompleted succeed'); + }); + } catch (err) { + // 捕获同步的参数错误 + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`reportDrawnCompleted failed, code is ${code}, message is ${message}`); + } + }); + console.log("MainAbility onWindowStageCreate") +} +}; + +``` + diff --git a/zh-cn/application-dev/reference/apis-new/commonEvent/commonEventSubscriber.md b/zh-cn/application-dev/reference/apis-new/commonEvent/commonEventSubscriber.md new file mode 100644 index 0000000000000000000000000000000000000000..8fc9cb4960ad3bb36e865d579b95e6d76f2efb13 --- /dev/null +++ b/zh-cn/application-dev/reference/apis-new/commonEvent/commonEventSubscriber.md @@ -0,0 +1,751 @@ +# commonEventSubscriber +> **说明** +>本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本 + +## CommonEventSubscriber + **系统能力:** SystemCapability.Notification.CommonEvent +### getCode + **调用形式:** + +- getCode(callback: AsyncCallback\): void +起始版本: 7 +- getCode(): Promise\ +起始版本: 7 + + **系统能力:** SystemCapability.Notification.CommonEvent + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | | +| Promise | | + + **示例代码1:** +示例(callback) +```ts +//获取有序公共事件代码回调 +function getCodeCB(err:Base.BusinessError, code:number) { + if (err.code !== undefined err.code != null) { + console.error(`getCode failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("getCode " + JSON.stringify(code)); + } +} +subscriber.getCode(getCodeCB); + +``` + + + **示例代码2:** +示例(promise) +```ts +subscriber.getCode().then((code:number) => { + console.info("getCode " + JSON.stringify(code)); +}).catch((err:Base.BusinessError) => { + console.error(`getCode failed, code is ${err.code}, message is ${err.message}`); +}); +``` + + +### getCodeSync(10+) + **调用形式:** +- getCodeSync(): number + + **系统能力:** SystemCapability.Notification.CommonEvent + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| number | | + + **示例代码:** +```ts + +try { + subscriber.setCodeSync(1); +} catch (error) { + let err:Base.BusinessError = error as Base.BusinessError; + console.error(`setCodeSync failed, code is ${err.code}, message is ${err.message}`); +} + +``` + + +### setCode + **调用形式:** + +- setCode(code: number, callback: AsyncCallback\): void +起始版本: 7 +- setCode(code: number): Promise\ +起始版本: 7 + + **系统能力:** SystemCapability.Notification.CommonEvent + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| code | number | true | | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | | +| Promise | | + + **示例代码1:** +示例(callback) +```ts +//设置有序公共事件的代码回调 +function setCodeCB(err:Base.BusinessError) { + if (err.code !== undefined err.code != null) { + console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("setCode"); + } +} +subscriber.setCode(1, setCodeCB); + +``` + + + **示例代码2:** +示例(promise) +```ts +subscriber.setCode(1).then(() => { + console.info("setCode"); +}).catch((err:Base.BusinessError) => { + console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); +}); +``` + + +### setCodeSync(10+) + **调用形式:** +- setCodeSync(code: number): void + + **系统能力:** SystemCapability.Notification.CommonEvent + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| code | number | true | | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 401 | | + + **示例代码:** +```ts + +try { + subscriber.setCodeSync(1); +} catch (error) { + let err:Base.BusinessError = error as Base.BusinessError; + console.error(`setCodeSync failed, code is ${err.code}, message is ${err.message}`); +} + +``` + + +### getData + **调用形式:** + +- getData(callback: AsyncCallback\): void +起始版本: 7 +- getData(): Promise\ +起始版本: 7 + + **系统能力:** SystemCapability.Notification.CommonEvent + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | | +| Promise | | + + **示例代码1:** +示例(callback) +```ts +//获取有序公共事件代码数据回调 +function getDataCB(err:Base.BusinessError, data:string) { + if (err.code !== undefined err.code != null) { + console.error(`getData failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("getData " + JSON.stringify(data)); + } +} +subscriber.getData(getDataCB); + +``` + + + **示例代码2:** +示例(promise) +```ts +subscriber.getData().then((data:string) => { + console.info("getData " + JSON.stringify(data)); +}).catch((err:Base.BusinessError) => { + console.error(`getData failed, code is ${err.code}, message is ${err.message}`); +}); +``` + + +### getDataSync(10+) + **调用形式:** +- getDataSync(): string + + **系统能力:** SystemCapability.Notification.CommonEvent + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| string | | + + **示例代码:** +```ts +let data = subscriber.getDataSync(); +console.info("getDataSync " + JSON.stringify(data)); +``` + + +### setData + **调用形式:** + +- setData(data: string, callback: AsyncCallback\): void +起始版本: 7 +- setData(data: string): Promise\ +起始版本: 7 + + **系统能力:** SystemCapability.Notification.CommonEvent + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| data | string | true | | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | | +| Promise | | + + **示例代码1:** +示例(callback) +```ts +//设置有序公共事件的结果数据回调 +function setDataCB(err:Base.BusinessError) { + if (err.code !== undefined err.code != null) { + console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("setData"); + } +} +subscriber.setData("publish_data_changed", setDataCB); + +``` + + + **示例代码2:** +示例(promise) +```ts +subscriber.setData("publish_data_changed").then(() => { + console.info("setData"); +}).catch((err:Base.BusinessError) => { + console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); +}); +``` + + +### setDataSync(10+) + **调用形式:** +- setDataSync(data: string): void + + **系统能力:** SystemCapability.Notification.CommonEvent + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| data | string | true | | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 401 | | + + **示例代码:** +```ts +try { + subscriber.setDataSync("publish_data_changed"); +} catch (error) { + let err:Base.BusinessError = error as Base.BusinessError; + console.error(`setDataSync failed, code is ${err.code}, message is ${err.message}`); +} + +``` + + +### setCodeAndData + **调用形式:** + +- setCodeAndData(code: number, data: string, callback: AsyncCallback\): void +起始版本: 7 +- setCodeAndData(code: number, data: string): Promise\ +起始版本: 7 + + **系统能力:** SystemCapability.Notification.CommonEvent + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| code | number | true | | +| data | string | true | | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | | +| Promise | | + + **示例代码1:** +示例(callback) +```ts +//设置有序公共事件的代码和数据回调 +function setCodeDataCB(err:Base.BusinessError) { + if (err.code !== undefined err.code != null) { + console.error(`setCodeAndData failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("setCodeDataCallback"); + } +} +subscriber.setCodeAndData(1, "publish_data_changed", setCodeDataCB); + +``` + + + **示例代码2:** +示例(promise) +```ts +subscriber.setCodeAndData(1, "publish_data_changed").then(() => { + console.info("setCodeAndData"); +}).catch((err:Base.BusinessError) => { + console.error(`setCodeAndData failed, code is ${err.code}, message is ${err.message}`); +}); +``` + + +### setCodeAndDataSync(10+) + **调用形式:** +- setCodeAndDataSync(code: number, data: string): void + + **系统能力:** SystemCapability.Notification.CommonEvent + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| code | number | true | | +| data | string | true | | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 401 | | + + **示例代码:** +```ts +try { + subscriber.setCodeAndDataSync(1, "publish_data_changed"); +} catch (error) { + let err:Base.BusinessError = error as Base.BusinessError; + console.error(`setCodeAndData failed, code is ${err.code}, message is ${err.message}`); +} + +``` + + +### isOrderedCommonEvent + **调用形式:** + +- isOrderedCommonEvent(callback: AsyncCallback\): void +起始版本: 7 +- isOrderedCommonEvent(): Promise\ +起始版本: 7 + + **系统能力:** SystemCapability.Notification.CommonEvent + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | | +| Promise | | + + **示例代码1:** +示例(callback) +```ts +//获取当前公共事件是否为有序事件的回调 +function isOrderedCB(err:Base.BusinessError, isOrdered:boolean) { + if (err.code !== undefined err.code != null) { + console.error(`isOrderedCommonEvent failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("isOrdered " + JSON.stringify(isOrdered)); + } +} +subscriber.isOrderedCommonEvent(isOrderedCB); + +``` + + + **示例代码2:** +示例(promise) +```ts +subscriber.isOrderedCommonEvent().then((isOrdered:boolean) => { + console.info("isOrdered " + JSON.stringify(isOrdered)); +}).catch((err:Base.BusinessError) => { + console.error(`isOrdered failed, code is ${err.code}, message is ${err.message}`); +}); +``` + + +### isOrderedCommonEventSync(10+) + **调用形式:** +- isOrderedCommonEventSync(): boolean + + **系统能力:** SystemCapability.Notification.CommonEvent + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| boolean | | + + **示例代码:** +```ts +let isOrdered = subscriber.isOrderedCommonEventSync(); +console.info("isOrdered " + JSON.stringify(isOrdered)); +``` + + +### isStickyCommonEvent + **调用形式:** + +- isStickyCommonEvent(callback: AsyncCallback\): void +起始版本: 7 +- isStickyCommonEvent(): Promise\ +起始版本: 7 + + **系统能力:** SystemCapability.Notification.CommonEvent + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | | +| Promise | | + + **示例代码1:** +示例(callback) +```ts +//获取当前公共事件是否为粘性事件的回调 +function isStickyCB(err:Base.BusinessError, isSticky:boolean) { + if (err.code !== undefined err.code != null) { + console.error(`isStickyCommonEvent failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("isSticky " + JSON.stringify(isSticky)); + } +} +subscriber.isStickyCommonEvent(isStickyCB); + +``` + + + **示例代码2:** +示例(promise) +```ts +subscriber.isStickyCommonEvent().then((isSticky:boolean) => { + console.info("isSticky " + JSON.stringify(isSticky)); +}).catch((err:Base.BusinessError) => { + console.error(`isSticky failed, code is ${err.code}, message is ${err.message}`); +}); +``` + + +### isStickyCommonEventSync(10+) + **调用形式:** +- isStickyCommonEventSync(): boolean + + **系统能力:** SystemCapability.Notification.CommonEvent + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| boolean | | + + **示例代码:** +```ts +let isSticky = subscriber.isStickyCommonEventSync(); +console.info("isSticky " + JSON.stringify(isSticky)); +``` + + +### abortCommonEvent + **调用形式:** + +- abortCommonEvent(callback: AsyncCallback\): void +起始版本: 7 +- abortCommonEvent(): Promise\ +起始版本: 7 + + **系统能力:** SystemCapability.Notification.CommonEvent + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | | +| Promise | | + + **示例代码1:** +示例(callback) +```ts +//取消当前有序公共事件的回调 +function abortCB(err:Base.BusinessError) { + if (err.code !== undefined err.code != null) { + console.error(`abortCommonEvent failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("abortCommonEvent"); + } +} +subscriber.abortCommonEvent(abortCB); + +``` + + + **示例代码2:** +示例(promise) +```ts +subscriber.abortCommonEvent().then(() => { + console.info("abortCommonEvent"); +}).catch((err:Base.BusinessError) => { + console.error(`abortCommonEvent failed, code is ${err.code}, message is ${err.message}`); +}); +``` + + +### abortCommonEventSync(10+) + **调用形式:** +- abortCommonEventSync(): void + + **系统能力:** SystemCapability.Notification.CommonEvent + **示例代码:** +```ts +//清除当前公共事件取消状态的回调 +function clearAbortCB(err:Base.BusinessError) { + if (err.code !== undefined err.code != null) { + console.error(`clearAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("clearAbortCommonEvent"); + } +} +subscriber.clearAbortCommonEvent(clearAbortCB); + +``` + + +### clearAbortCommonEvent + **调用形式:** + +- clearAbortCommonEvent(callback: AsyncCallback\): void +起始版本: 7 +- clearAbortCommonEvent(): Promise\ +起始版本: 7 + + **系统能力:** SystemCapability.Notification.CommonEvent + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | | +| Promise | | + + **示例代码1:** +示例(callback) +```ts +//清除当前公共事件取消状态的回调 +function clearAbortCB(err:Base.BusinessError) { + if (err.code !== undefined err.code != null) { + console.error(`clearAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("clearAbortCommonEvent"); + } +} +subscriber.clearAbortCommonEvent(clearAbortCB); + +``` + + + **示例代码2:** +示例(promise) +```ts +subscriber.clearAbortCommonEvent().then(() => { + console.info("clearAbortCommonEvent"); +}).catch((err:Base.BusinessError) => { + console.error(`clearAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); +}); +``` + + +### clearAbortCommonEventSync(10+) + **调用形式:** +- clearAbortCommonEventSync(): void + + **系统能力:** SystemCapability.Notification.CommonEvent + **示例代码:** +```ts +subscriber.clearAbortCommonEventSync(); +``` + + +### getAbortCommonEvent + **调用形式:** + +- getAbortCommonEvent(callback: AsyncCallback\): void +起始版本: 7 +- getAbortCommonEvent(): Promise\ +起始版本: 7 + + **系统能力:** SystemCapability.Notification.CommonEvent + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | | +| Promise | | + + **示例代码1:** +示例(callback) +```ts +//获取当前有序公共事件是否取消的回调 +function getAbortCB(err:Base.BusinessError, abortEvent:boolean) { + if (err.code !== undefined err.code != null) { + console.error(`getAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("abortCommonEvent " + abortEvent) + } +} +subscriber.getAbortCommonEvent(getAbortCB); + +``` + + + **示例代码2:** +示例(promise) +```ts +subscriber.getAbortCommonEvent().then((abortEvent:boolean) => { + console.info("abortCommonEvent " + JSON.stringify(abortEvent)); +}).catch((err:Base.BusinessError) => { + console.error(`getAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); +}); +``` + + +### getAbortCommonEventSync(10+) + **调用形式:** +- getAbortCommonEventSync(): boolean + + **系统能力:** SystemCapability.Notification.CommonEvent + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| boolean | | + + **示例代码:** +```ts +let abortEvent = subscriber.getAbortCommonEventSync(); +console.info("getAbortCommonEventSync " + JSON.stringify(abortEvent)); +``` + + +### getSubscribeInfo + **调用形式:** + +- getSubscribeInfo(callback: AsyncCallback\): void +起始版本: 7 +- getSubscribeInfo(): Promise\ +起始版本: 7 + + **系统能力:** SystemCapability.Notification.CommonEvent + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | | +| Promise | | + + **示例代码1:** +示例(callback) +```ts +//获取订阅者信息回调 +function getCB(err:Base.BusinessError, subscribeInfo:CommonEventManager.CommonEventSubscribeInfo) { + if (err.code !== undefined err.code != null) { + console.error(`getSubscribeInfo failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("subscribeInfo " + JSON.stringify(subscribeInfo)); + } +} +subscriber.getSubscribeInfo(getCB); + +``` + + + **示例代码2:** +示例(promise) +```ts +subscriber.getSubscribeInfo().then((subscribeInfo:CommonEventManager.CommonEventSubscribeInfo) => { + console.info("subscribeInfo " + JSON.stringify(subscribeInfo)); +}).catch((err:Base.BusinessError) => { + console.error(`getSubscribeInfo failed, code is ${err.code}, message is ${err.message}`); +}); +``` + + +### getSubscribeInfoSync(10+) + **调用形式:** +- getSubscribeInfoSync(): CommonEventSubscribeInfo + + **系统能力:** SystemCapability.Notification.CommonEvent + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| CommonEventSubscribeInfo | | + + **示例代码:** +```ts +let subscribeInfo = subscriber.getSubscribeInfoSync(); +console.info("subscribeInfo " + JSON.stringify(subscribeInfo)); +``` + + +### finishCommonEvent(9+) + **调用形式:** + +- finishCommonEvent(callback: AsyncCallback\): void +起始版本: 9 +- finishCommonEvent(): Promise\ +起始版本: 9 + + **系统能力:** SystemCapability.Notification.CommonEvent + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | | +| Promise | | + + **示例代码1:** +示例(callback) +```ts +//结束当前有序公共事件的回调 +function finishCB(err:Base.BusinessError) { + if (err.code !== undefined err.code != null) { + console.error(`finishCommonEvent failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("FinishCommonEvent"); + } +} + +subscriber.finishCommonEvent(finishCB); + +``` + + + **示例代码2:** +示例(promise) +```ts +subscriber.finishCommonEvent().then(() => { + console.info("FinishCommonEvent"); +}).catch((err:Base.BusinessError) => { + console.error(`finishCommonEvent failed, code is ${err.code}, message is ${err.message}`); +}); +``` + diff --git a/zh-cn/application-dev/reference/apis-new/internal/component/ets/shape.md b/zh-cn/application-dev/reference/apis-new/internal/component/ets/shape.md new file mode 100644 index 0000000000000000000000000000000000000000..903940ebb319dcd5e4c7f60bf6f5ba184c376993 --- /dev/null +++ b/zh-cn/application-dev/reference/apis-new/internal/component/ets/shape.md @@ -0,0 +1,149 @@ +# shape +绘制组件的父组件,父组件中会描述所有绘制组件均支持的通用属性。1、绘制组件使用Shape作为父组件,实现类似SVG的效果。2、绘制组件单独使用,用于在页面上绘制指定的图形。 +> **说明** +>本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本 + + **子组件** +无 + +## 接口 + + + + **调用形式** + +- Shape() +起始版本: 7 + +- Shape(value: PixelMap) +起始版本: 7 +## 属性 + + **系统能力:** SystemCapability.ArkUI.ArkUI.Full +| 名称 | 类型 | 说明 | +| --------| --------| --------| +| viewPort | { x?: number \| string; y?: number \| string; width?: number \| string; height?: number \| string } | | +| stroke | ResourceColor | | +| fill | ResourceColor | | +| strokeDashOffset | number \| string | | +| strokeDashArray | Array | | +| strokeLineCap | LineCapStyle | | +| strokeLineJoin | LineJoinStyle | | +| strokeMiterLimit | number \| string | | +| strokeOpacity | number \| string \| Resource | | +| fillOpacity | number \| string \| Resource | | +| strokeWidth | number \| string | | +| antiAlias | boolean | | +| mesh8+ | Array, column: number, row: number | | + + **示例代码:** +```ts +// xxx.ets +@Entry +@Component +struct ShapeExample { + build() { + Column({ space: 10 }) { + Text('basic').fontSize(11).fontColor(0xCCCCCC).width(320) + // 在Shape的(-2, -2)点绘制一个 300 * 50 带边框的矩形,颜色0x317AF7,边框颜色黑色,边框宽度4,边框间隙20,向左偏移10,线条两端样式为半圆,拐角样式圆角,抗锯齿(默认开启) + // 在Shape的(-2, 58)点绘制一个 300 * 50 带边框的椭圆,颜色0x317AF7,边框颜色黑色,边框宽度4,边框间隙20,向左偏移10,线条两端样式为半圆,拐角样式圆角,抗锯齿(默认开启) + // 在Shape的(-2, 118)点绘制一个 300 * 10 直线路径,颜色0x317AF7,边框颜色黑色,宽度4,间隙20,向左偏移10,线条两端样式为半圆,拐角样式圆角,抗锯齿(默认开启) + Shape() { + Rect().width(300).height(50) + Ellipse().width(300).height(50).offset({ x: 0, y: 60 }) + Path().width(300).height(10).commands('M0 0 L900 0').offset({ x: 0, y: 120 }) + } + .width(350) + .height(140) + .viewPort({ x: -2, y: -2, width: 304, height: 130 }) + .fill(0x317AF7) + .stroke(Color.Black) + .strokeWidth(4) + .strokeDashArray([20]) + .strokeDashOffset(10) + .strokeLineCap(LineCapStyle.Round) + .strokeLineJoin(LineJoinStyle.Round) + .antiAlias(true) + // 分别在Shape的(0, 0)、(-5, -5)点绘制一个 300 * 50 带边框的矩形,可以看出之所以将视口的起始位置坐标设为负值是因为绘制的起点默认为线宽的中点位置,因此要让边框完全显示则需要让视口偏移半个线宽 + Shape() { + Rect().width(300).height(50) + } + .width(350) + .height(80) + .viewPort({ x: 0, y: 0, width: 320, height: 70 }) + .fill(0x317AF7) + .stroke(Color.Black) + .strokeWidth(10) + + Shape() { + Rect().width(300).height(50) + } + .width(350) + .height(80) + .viewPort({ x: -5, y: -5, width: 320, height: 70 }) + .fill(0x317AF7) + .stroke(Color.Black) + .strokeWidth(10) + + Text('path').fontSize(11).fontColor(0xCCCCCC).width(320) + // 在Shape的(0, -5)点绘制一条直线路径,颜色0xEE8443,线条宽度10,线条间隙20 + Shape() { + Path().width(300).height(10).commands('M0 0 L900 0') + } + .width(350) + .height(20) + .viewPort({ x: 0, y: -5, width: 300, height: 20 }) + .stroke(0xEE8443) + .strokeWidth(10) + .strokeDashArray([20]) + // 在Shape的(0, -5)点绘制一条直线路径,颜色0xEE8443,线条宽度10,线条间隙20,向左偏移10 + Shape() { + Path().width(300).height(10).commands('M0 0 L900 0') + } + .width(350) + .height(20) + .viewPort({ x: 0, y: -5, width: 300, height: 20 }) + .stroke(0xEE8443) + .strokeWidth(10) + .strokeDashArray([20]) + .strokeDashOffset(10) + // 在Shape的(0, -5)点绘制一条直线路径,颜色0xEE8443,线条宽度10,透明度0.5 + Shape() { + Path().width(300).height(10).commands('M0 0 L900 0') + } + .width(350) + .height(20) + .viewPort({ x: 0, y: -5, width: 300, height: 20 }) + .stroke(0xEE8443) + .strokeWidth(10) + .strokeOpacity(0.5) + // 在Shape的(0, -5)点绘制一条直线路径,颜色0xEE8443,线条宽度10,线条间隙20,线条两端样式为半圆 + Shape() { + Path().width(300).height(10).commands('M0 0 L900 0') + } + .width(350) + .height(20) + .viewPort({ x: 0, y: -5, width: 300, height: 20 }) + .stroke(0xEE8443) + .strokeWidth(10) + .strokeDashArray([20]) + .strokeLineCap(LineCapStyle.Round) + // 在Shape的(-80, -5)点绘制一个封闭路径,颜色0x317AF7,线条宽度10,边框颜色0xEE8443,拐角样式锐角(默认值) + Shape() { + Path().width(200).height(60).commands('M0 0 L400 0 L400 150 Z') + } + .width(300) + .height(200) + .viewPort({ x: -20, y: -5, width: 310, height: 90 }) + .fill(0x317AF7) + .stroke(0xEE8443) + .strokeWidth(10) + .strokeLineJoin(LineJoinStyle.Miter) + .strokeMiterLimit(5) + }.width('100%').margin({ top: 15 }) + } +} + +``` + +![zh-cn_image_0000001184628104](figures/zh-cn_image_0000001184628104.png) diff --git a/zh-cn/application-dev/reference/apis-new/ohos-net-http.md b/zh-cn/application-dev/reference/apis-new/ohos-net-http.md new file mode 100644 index 0000000000000000000000000000000000000000..abd38b4cc401eac4a4d2a431dbf16498145d6c80 --- /dev/null +++ b/zh-cn/application-dev/reference/apis-new/ohos-net-http.md @@ -0,0 +1,889 @@ +# @ohos.net.http +> **说明** +>本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本 + +## 导入模块 + +```js +import http from '@ohos.net.http' +``` + +## createHttp +创建一个HTTP请求,里面包括发起请求、中断请求、订阅/取消订阅HTTP Response Header事件。每一个HttpRequest对象对应一个HTTP请求。如需发起多个HTTP请求,须为每个HTTP请求创建对应HttpRequest对象。 + **调用形式:** +- createHttp(): HttpRequest + + **系统能力:** SystemCapability.Communication.NetStack + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| HttpRequest | 返回一个HttpRequest对象,里面包括request、requestInStream、destroy、on和off方法。 | + + **示例代码:** +```ts +import http from '@ohos.net.http'; + +let httpRequest = http.createHttp(); +``` + + +## HttpRequestOptions +发起请求可选参数的类型和取值范围。 + **系统能力:** SystemCapability.Communication.NetStack +### 属性 + **系统能力:** SystemCapability.Communication.NetStack +| 名称 | 类型 | 只读 | 必填 | 说明 | +| --------| --------| --------| --------| --------| +| method | RequestMethod | false | false | 请求方式,默认为GET。 | +| extraData | string \| Object \| ArrayBuffer | false | false | 发送请求的额外数据,默认无此字段。
当HTTP请求为POST、PUT等方法时,此字段为HTTP请求的content,以UTF-8编码形式作为请求体。当'Content-Type'为'application/x-www-form-urlencoded'时,请求提交的信息主体数据应在key和value进行URL转码后按照键值对"key1=value1key2=value2key3=value3"的方式进行编码,该字段对应的类型通常为String;当'Content-Type'为'text/xml'时,该字段对应的类型通常为String;当'Content-Type'为'application/json'时,该字段对应的类型通常为Object;当'Content-Type'为'application/octet-stream'时,该字段对应的类型通常为ArrayBuffer;当'Content-Type'为'multipart/form-data'且需上传的字段为文件时,该字段对应的类型通常为ArrayBuffer。以上信息仅供参考,并可能根据具体情况有所不同。
- 当HTTP请求为GET、OPTIONS、DELETE、TRACE、CONNECT等方法时,此字段为HTTP请求参数的补充。开发者需传入Encode编码后的string类型参数,Object类型的参数无需预编码,参数内容会拼接到URL中进行发送;ArrayBuffer类型的参数不会做拼接处理。 | +| expectDataType(9+) | HttpDataType | false | false | 指定返回数据的类型,默认无此字段。如果设置了此参数,系统将优先返回指定的类型。 | +| usingCache(9+) | boolean | false | false | 是否使用缓存,默认为true。 | +| priority(9+) | number | false | false | 优先级,范围[1,1000],默认是1。 | +| header | Object | false | false | HTTP请求头字段。默认{'Content-Type': 'application/json'}。 | +| readTimeout | number | false | false | | +| connectTimeout | number | false | false | 读取超时时间。单位为毫秒(ms),默认为60000ms。
设置为0表示不会出现超时情况 | +| usingProtocol(9+) | HttpProtocol | false | false | 使用协议。默认值由系统自动指定。 | +| usingProxy(10+) | boolean \| HttpProxy | false | false | 是否使用HTTP代理,默认为false,不使用代理。
- 当usingProxy为布尔类型true时,使用默认网络代理。
- 当usingProxy为object类型时,使用指定网络代理。 | +| caPath(10+) | string | false | false | 如果设置了此参数,系统将使用用户指定路径的CA证书,(开发者需保证该路径下CA证书的可访问性),否则将使用系统预设CA证书,系统预设CA证书位置:/etc/ssl/certs/cacert.pem。证书路径为沙箱映射路径(开发者可通过Global.getContext().filesDir获取应用沙箱路径)。目前仅支持后缀名为.pem的文本格式证书。 | + +## HttpRequest +HTTP请求任务。在调用HttpRequest的方法前,需要先通过[createHttp()](#httpcreatehttp)创建一个任务。 + **系统能力:** SystemCapability.Communication.NetStack +### request +根据URL地址,发起HTTP网络请求,使用callback方式作为异步方法。 + **调用形式:** + +- request(url: string, callback: AsyncCallback\): void +起始版本: 6 +- request(url: string, options: HttpRequestOptions, callback: AsyncCallback\): void +起始版本: 6 +- request(url: string, options?: HttpRequestOptions): Promise\ +起始版本: 6 + + **系统能力:** SystemCapability.Communication.NetStack + **需要权限:** ohos.permission.INTERNET + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| url | string | true | 发起网络请求的URL地址。 | +| options | HttpRequestOptions | true | | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | 回调函数。 | +| Promise | | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 401 | Parameter error. | +| 201 | Permission denied. | +| 2300001 | Unsupported protocol. | +| 2300003 | URL using bad/illegal format or missing URL. | +| 2300005 | Couldn't resolve proxy name. | +| 2300006 | Couldn't resolve host name. | +| 2300007 | Couldn't connect to server. | +| 2300008 | Weird server reply. | +| 2300009 | | 2300009 | Access denied to remote resource. | | +| 2300016 | Error in the HTTP2 framing layer. | +| 2300018 | Transferred a partial file. | +| 2300023 | Failed writing received data to disk/application. | +| 2300025 | Upload failed. | +| 2300026 | Failed to open/read local data from file/application. | +| 2300027 | Out of memory. | +| 2300028 | Timeout was reached. | +| 2300047 | Number of redirects hit maximum amount. | +| 2300052 | Server returned nothing (no headers, no data). | +| 2300055 | Failed sending data to the peer. | +| 2300056 | Failure when receiving data from the peer. | +| 2300058 | Problem with the local SSL certificate. | +| 2300059 | Couldn't use specified SSL cipher. | +| 2300060 | SSL peer certificate or SSH remote key was not OK. | +| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding. | +| 2300063 | Maximum file size exceeded. | +| 2300070 | Disk full or allocation exceeded. | +| 2300073 | Remote file already exists. | +| 2300077 | Problem with the SSL CA cert (path? access rights?). | +| 2300078 | Remote file not found. | +| 2300094 | An authentication function returned an error. | +| 2300999 | Unknown Other Error. | + + **示例代码1:** +示例代码(callback): +```ts +import http from '@ohos.net.http'; + +let httpRequest = http.createHttp(); +httpRequest.request("EXAMPLE_URL", (err: Error, data: http.HttpResponse) => { + if (!err) { + console.info('Result:' + data.result); + console.info('code:' + data.responseCode); + console.info('header:' + JSON.stringify(data.header)); + console.info('cookies:' + data.cookies); // 8+ + } else { + console.info('error:' + JSON.stringify(err)); + } +}); + +``` + + + **示例代码2:** +示例代码(promise): +```ts +import http from '@ohos.net.http'; + +class Header { + public contentType: string; + + constructor(contentType: string) { + this.contentType = contentType; + } +} + +let httpRequest = http.createHttp(); +let promise = httpRequest.request("EXAMPLE_URL", { + method: http.RequestMethod.GET, + connectTimeout: 60000, + readTimeout: 60000, + header: new Header('application/json') +}); +promise.then((data:http.HttpResponse) => { + console.info('Result:' + data.result); + console.info('code:' + data.responseCode); + console.info('header:' + JSON.stringify(data.header)); + console.info('cookies:' + data.cookies); // 8+ + console.info('header.Content-Type:' + data.header); + console.info('header.Status-Line:' + data.header); +}).catch((err:Error) => { + console.info('error:' + JSON.stringify(err)); +}); + +``` + + +### requestInStream(10+) +根据URL地址,发起HTTP网络请求并返回流式响应,使用callback方式作为异步方法。 + **调用形式:** + +- requestInStream(url: string, callback: AsyncCallback\): void +起始版本: 10 +- requestInStream(url: string, options: HttpRequestOptions, callback: AsyncCallback\): void +起始版本: 10 +- requestInStream(url: string, options?: HttpRequestOptions): Promise\ +起始版本: 10 + + **系统能力:** SystemCapability.Communication.NetStack + **需要权限:** ohos.permission.INTERNET + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| url | string | true | | +| options | HttpRequestOptions | true | | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | | +| Promise | | + + + **错误码:** +| 错误码ID | 错误信息 | +| --------| --------| +| 401 | | +| 201 | | +| 2300001 | | +| 2300003 | | +| 2300005 | | +| 2300006 | | +| 2300007 | | +| 2300008 | | +| 2300009 | | +| 2300016 | | +| 2300018 | | +| 2300023 | | +| 2300025 | | +| 2300026 | | +| 2300027 | | +| 2300028 | | +| 2300047 | | +| 2300052 | | +| 2300055 | | +| 2300056 | | +| 2300058 | | +| 2300059 | | +| 2300060 | | +| 2300061 | | +| 2300063 | | +| 2300070 | | +| 2300073 | | +| 2300077 | | +| 2300078 | | +| 2300094 | | +| 2300999 | | + + **示例代码1:** +示例代码(callback): +```ts +import http from '@ohos.net.http'; +import { BusinessError } from '@ohos.base'; + +let httpRequest = http.createHttp(); +httpRequest.requestInStream("EXAMPLE_URL", (err: BusinessError, data: number) => { + if (!err) { + console.info("requestInStream OK! ResponseCode is " + JSON.stringify(data)); + } else { + console.info("requestInStream ERROR : err = " + JSON.stringify(err)); + } +}) + +``` + + + **示例代码2:** +示例代码(promise): +```ts +import http from '@ohos.net.http'; + +class Header { + public contentType: string; + + constructor(contentType: string) { + this.contentType = contentType; + } +} + +let httpRequest = http.createHttp(); +let promise = httpRequest.request("EXAMPLE_URL", { + method: http.RequestMethod.GET, + connectTimeout: 60000, + readTimeout: 60000, + header: new Header('application/json') +}); +promise.then((data: http.HttpResponse) => { + console.info("requestInStream OK!" + JSON.stringify(data)); +}).catch((err: Error) => { + console.info("requestInStream ERROR : err = " + JSON.stringify(err)); +}); + +``` + + +### destroy +中断请求任务。 + **调用形式:** +- destroy(): void + + **系统能力:** SystemCapability.Communication.NetStack + **示例代码:** +```ts +import http from '@ohos.net.http'; +let httpRequest = http.createHttp(); + +httpRequest.destroy(); +``` + + +### on("headerReceive")(deprecated) +订阅HTTP Response Header 事件。 + **调用形式:** +- on(type: "headerReceive", callback: AsyncCallback\): void + + **废弃说明:** 从API version 8 开始废弃。替代接口: on_headersReceive。 + **系统能力:** SystemCapability.Communication.NetStack + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| type(deprecated) | string | true | 订阅的事件类型,'headerReceive'。 | +| callback(deprecated) | AsyncCallback | true | 回调函数。 | + + **示例代码:** +示例代码(callback): +```ts +import http from '@ohos.net.http'; +import { BusinessError } from '@ohos.base'; + +let httpRequest = http.createHttp(); +httpRequest.on('headerReceive', (data: BusinessError) => { + console.info('error:' + JSON.stringify(data)); +}); + +``` + + +### off("headerReceive")(deprecated) +取消订阅HTTP Response Header 事件。 + **调用形式:** +- off(type: "headerReceive", callback?: AsyncCallback\): void + + **废弃说明:** 从API version 8 开始废弃。替代接口: off_headersReceive。 + **系统能力:** SystemCapability.Communication.NetStack + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| type(deprecated) | string | true | 取消订阅的事件类型,'headerReceive'。 | +| callback(deprecated) | AsyncCallback | false | 回调函数。 | + + **示例代码:** +示例代码(callback): +```ts +import http from '@ohos.net.http'; + +let httpRequest = http.createHttp(); +httpRequest.off('headerReceive'); +``` + + +### on("headersReceive")(8+) +订阅HTTP Response Header 事件 + **调用形式:** + +- on(type: "headersReceive", callback: Callback\): void +起始版本: 8 + + **系统能力:** SystemCapability.Communication.NetStack + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| type | string | true | 订阅的事件类型:'headersReceive'。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | 回调函数。 | + + **示例代码:** +示例代码(callback): +```ts +import http from '@ohos.net.http'; + +let httpRequest = http.createHttp(); +httpRequest.on('headersReceive', (header: Object) => { + console.info('header: ' + JSON.stringify(header)); +}); +``` + + +### off("headersReceive")(8+) +取消订阅HTTP Response Header 事件。 + **调用形式:** + +- off(type: "headersReceive", callback?: Callback\): void +起始版本: 8 + + **系统能力:** SystemCapability.Communication.NetStack + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| type | string | true | 取消订阅的事件类型:'headersReceive'。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | 回调函数。 | + + **示例代码:** +示例代码(promise): +```ts +import http from '@ohos.net.http'; + +let httpRequest = http.createHttp(); +httpRequest.off('headersReceive'); +``` + + +### once("headersReceive")(8+) +订阅HTTP Response Header 事件,但是只触发一次。一旦触发之后,订阅器就会被移除。使用callback方式作为异步方法。 + **调用形式:** + +- once(type: "headersReceive", callback: Callback\): void +起始版本: 8 + + **系统能力:** SystemCapability.Communication.NetStack + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| type | string | true | 订阅的事件类型:'headersReceive'。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | 回调函数。 | + + **示例代码:** +示例代码(callback): +```ts +import http from '@ohos.net.http'; + +let httpRequest = http.createHttp(); +httpRequest.once('headersReceive', (header: Object) => { + console.info('header: ' + JSON.stringify(header)); +}); +``` + + +### on("dataReceive")(10+) +订阅HTTP流式响应数据接收事件。 + **调用形式:** + +- on(type: "dataReceive", callback: Callback\): void +起始版本: 10 + + **系统能力:** SystemCapability.Communication.NetStack + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| type | string | true | 订阅的事件类型,'dataReceive'。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | 回调函数。 | + + **示例代码:** +示例代码(callback): +```ts +import http from '@ohos.net.http'; + +let httpRequest = http.createHttp(); +httpRequest.on('dataReceive', (data: ArrayBuffer) => { + console.info('dataReceive length: ' + JSON.stringify(data.byteLength)); +}); +``` + + +### off("dataReceive")(10+) +取消订阅HTTP流式响应数据接收事件。 + **调用形式:** + +- off(type: "dataReceive", callback?: Callback\): void +起始版本: 10 + + **系统能力:** SystemCapability.Communication.NetStack + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| type | string | true | 取消订阅的事件类型:'dataReceive'。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | 回调函数。 | + + **示例代码:** +示例代码(callback): +```ts +import http from '@ohos.net.http'; + +let httpRequest = http.createHttp(); +httpRequest.off('dataReceive'); +``` + + +### on("dataEnd")(10+) +订阅HTTP流式响应数据接收完毕事件。 + **调用形式:** + +- on(type: "dataEnd", callback: Callback\): void +起始版本: 10 + + **系统能力:** SystemCapability.Communication.NetStack + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| type | string | true | 订阅的事件类型,'dataEnd'。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | 回调函数。 | + + **示例代码:** +示例代码(callback): +```ts +import http from '@ohos.net.http'; + +let httpRequest = http.createHttp(); +httpRequest.on('dataEnd', () => { + console.info('Receive dataEnd !'); +}); +``` + + +### off("dataEnd")(10+) +取消订阅HTTP流式响应数据接收完毕事件。 + **调用形式:** + +- off(type: "dataEnd", callback?: Callback\): void +起始版本: 10 + + **系统能力:** SystemCapability.Communication.NetStack + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| type | string | true | 取消订阅的事件类型:'dataEnd'。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | 回调函数。 | + + **示例代码:** +示例代码(callback): +```ts +import http from '@ohos.net.http'; + +let httpRequest = http.createHttp(); +httpRequest.off('dataEnd'); +``` + + +### on('dataReceiveProgress')(10+) +订阅HTTP流式响应数据接收进度事件。 + **调用形式:** + +- on(type: 'dataReceiveProgress', callback: Callback\<{ receiveSize: number, totalSize: number }>): void +起始版本: 10 + + **系统能力:** SystemCapability.Communication.NetStack + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| type | string | true | 订阅的事件类型,'dataReceiveProgress'。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | 回调函数。
receiveSize:已接收的数据字节数,totalSize待接收的字节总数 | + + **示例代码:** +示例代码(callback): +```ts +import http from '@ohos.net.http'; + +class RequestData{ + receiveSize: number = 2000 + totalSize: number = 2000 +} + +let httpRequest = http.createHttp(); +httpRequest.on('dataReceiveProgress', (data: RequestData) => { + console.info('dataReceiveProgress:' + JSON.stringify(data)); +}); +``` + + +### off('dataReceiveProgress')(10+) +取消订阅HTTP流式响应数据接收进度事件。 + **调用形式:** + +- off(type: 'dataReceiveProgress', callback?: Callback\<{ receiveSize: number, totalSize: number }>): void +起始版本: 10 + + **系统能力:** SystemCapability.Communication.NetStack + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| type | string | true | 取消订阅的事件类型:'dataReceiveProgress'。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | 回调函数。 | + + **示例代码:** +示例代码(callback): +```ts +import http from '@ohos.net.http'; + +let httpRequest = http.createHttp(); +httpRequest.off('dataReceiveProgress'); +``` + + +## RequestMethod +HTTP 请求方法。 + + **系统能力:** SystemCapability.Communication.NetStack +| 名称 | 值 | 说明 | +| --------| --------| --------| +| OPTIONS | OPTIONS | HTTP 请求 OPTIONS。 | +| GET | GET | HTTP 请求 GET。 | +| HEAD | HEAD | HTTP 请求 HEAD。 | +| POST | POST | HTTP 请求 POST。 | +| PUT | PUT | HTTP 请求 PUT。 | +| DELETE | DELETE | HTTP 请求 DELETE。 | +| TRACE | TRACE | HTTP 请求 TRACE。 | +| CONNECT | CONNECT | HTTP 请求 CONNECT。 | + +## ResponseCode +发起请求返回的响应码。 + + **系统能力:** SystemCapability.Communication.NetStack +| 名称 | 值 | 说明 | +| --------| --------| --------| +| OK | 200 | 请求成功。一般用于GET与POST请求。 | +| CREATED | 201 | 已创建。成功请求并创建了新的资源。 | +| ACCEPTED | 202 | 已接受。已经接受请求,但未处理完成。 | +| NOT_AUTHORITATIVE | 203 | 非授权信息。请求成功。 | +| NO_CONTENT | 204 | 无内容。服务器成功处理,但未返回内容。 | +| RESET | 205 | 重置内容。 | +| PARTIAL | 206 | 部分内容。服务器成功处理了部分GET请求。 | +| MULT_CHOICE | 300 | 多种选择。 | +| MOVED_PERM | 301 | 永久移动。请求的资源已被永久的移动到新URI,返回信息会包括新的URI,浏览器会自动定向到新URI。 | +| MOVED_TEMP | 302 | 临时移动。 | +| SEE_OTHER | 303 | 查看其它地址。 | +| NOT_MODIFIED | 304 | 未修改。 | +| USE_PROXY | 305 | 使用代理。 | +| BAD_REQUEST | 400 | 客户端请求的语法错误,服务器无法理解。 | +| UNAUTHORIZED | 401 | 请求要求用户的身份认证。 | +| PAYMENT_REQUIRED | 402 | 保留,将来使用。 | +| FORBIDDEN | 403 | 服务器理解请求客户端的请求,但是拒绝执行此请求。 | +| NOT_FOUND | 404 | 服务器无法根据客户端的请求找到资源(网页)。 | +| BAD_METHOD | 405 | 客户端请求中的方法被禁止。 | +| NOT_ACCEPTABLE | 406 | 服务器无法根据客户端请求的内容特性完成请求。 | +| PROXY_AUTH | 407 | 请求要求代理的身份认证。 | +| CLIENT_TIMEOUT | 408 | 请求时间过长,超时。 | +| CONFLICT | 409 | 服务器完成客户端的PUT请求是可能返回此代码,服务器处理请求时发生了冲突。 | +| GONE | 410 | 客户端请求的资源已经不存在。 | +| LENGTH_REQUIRED | 411 | 服务器无法处理客户端发送的不带Content-Length的请求信息。 | +| PRECON_FAILED | 412 | 客户端请求信息的先决条件错误。 | +| ENTITY_TOO_LARGE | 413 | 由于请求的实体过大,服务器无法处理,因此拒绝请求。 | +| REQ_TOO_LONG | 414 | 请求的URI过长(URI通常为网址),服务器无法处理。 | +| UNSUPPORTED_TYPE | 415 | 服务器无法处理请求的格式。 | +| INTERNAL_ERROR | 500 | 服务器内部错误,无法完成请求。 | +| NOT_IMPLEMENTED | 501 | 服务器不支持请求的功能,无法完成请求。 | +| BAD_GATEWAY | 502 | 充当网关或代理的服务器,从远端服务器接收到了一个无效的请求。 | +| UNAVAILABLE | 503 | 由于超载或系统维护,服务器暂时的无法处理客户端的请求。 | +| GATEWAY_TIMEOUT | 504 | 充当网关或代理的服务器,未及时从远端服务器获取请求。 | +| VERSION | 505 | 服务器请求的HTTP协议的版本。 | + +## HttpProtocol(9+) +http协议版本。 + + **系统能力:** SystemCapability.Communication.NetStack +| 名称 | 值 | 说明 | +| --------| --------| --------| +| HTTP1_1 | 0 | 协议http1.1 | +| HTTP2 | 1 | 协议http2 | + +## HttpDataType(9+) +http的数据类型。 + + **系统能力:** SystemCapability.Communication.NetStack +| 名称 | 值 | 说明 | +| --------| --------| --------| +| STRING | 0 | 字符串类型。 | +| OBJECT | 1 | 对象类型。 | +| ARRAY_BUFFER | 2 | 二进制数组类型。 | + +## HttpResponse +request方法回调函数的返回值类型。 + **系统能力:** SystemCapability.Communication.NetStack +### 属性 + **系统能力:** SystemCapability.Communication.NetStack +| 名称 | 类型 | 只读 | 必填 | 说明 | +| --------| --------| --------| --------| --------| +| result | string \| Object \| ArrayBuffer | false | true | HTTP请求根据响应头中Content-type类型返回对应的响应格式内容,若HttpRequestOptions无expectDataType字段,按如下规则返回:
- application/json:返回JSON格式的字符串;
- application/octet-stream:ArrayBuffer;
- image:ArrayBuffer;
- 其他:string。
若HttpRequestOption有expectDataType字段,开发者需传入与服务器返回类型相同的数据类型。 | +| resultType(9+) | HttpDataType | false | true | 返回值类型。 | +| responseCode | ResponseCode \| number | false | true | 回调函数执行成功时,此字段为[ResponseCode](#responsecode)。若执行失败,错误码将会从AsyncCallback中的err字段返回。 | +| header | Object | false | true | 发起HTTP请求返回来的响应头。当前返回的是JSON格式字符串,如需具体字段内容,需开发者自行解析。常见字段及解析方式如下:
- content-type:header['content-type'];
- status-line:header['status-line'];
- date:header.date/header['date'];
- server:header.server/header['server']; | +| cookies(8+) | string | false | true | 服务器返回的 cookies。 | + +## createHttpResponseCache(9+) +创建一个默认的对象来存储HTTP访问请求的响应。 + **调用形式:** +- createHttpResponseCache(cacheSize?: number): HttpResponseCache + + **系统能力:** SystemCapability.Communication.NetStack + **参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------| --------| --------| --------| +| cacheSize | number | false | 缓存大小最大为10\*1024\*1024(10MB),默认最大。 | + + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| HttpResponseCache | 返回一个存储HTTP访问请求响应的对象。 | + + **示例代码:** +```ts +import http from '@ohos.net.http'; + +let httpResponseCache = http.createHttpResponseCache(); +``` + + +## HttpResponseCache(9+) +存储HTTP访问请求响应的对象。在调用HttpResponseCache的方法前,需要先通过[createHttpResponseCache()](#httpcreatehttpresponsecache9)创建一个任务。 + **系统能力:** SystemCapability.Communication.NetStack +### flush(9+) +将缓存中的数据写入文件系统,以便在下一个HTTP请求中访问所有缓存数据,使用Promise方式作为异步方法。 + **调用形式:** + +- flush(callback: AsyncCallback\): void +起始版本: 9 +- flush(): Promise\ +起始版本: 9 + + **系统能力:** SystemCapability.Communication.NetStack + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | | +| Promise | 以Promise形式返回写入结果。 | + + **示例代码1:** +示例代码(callback): +```ts +import http from '@ohos.net.http'; +import { BusinessError } from '@ohos.base'; + +let httpResponseCache = http.createHttpResponseCache(); +httpResponseCache.flush((err: BusinessError) => { + if (err) { + console.info('flush fail'); + return; + } + console.info('flush success'); +}); + +``` + + + **示例代码2:** +示例代码(promise): +```ts +import http from '@ohos.net.http'; +import { BusinessError } from '@ohos.base'; + +let httpResponseCache = http.createHttpResponseCache(); +httpResponseCache.flush().then(() => { + console.info('flush success'); +}).catch((err: BusinessError) => { + console.info('flush fail'); +}); + +``` + + +### delete(9+) +禁用缓存并删除其中的数据,使用callback方式作为异步方法。 + **调用形式:** + +- delete(callback: AsyncCallback\): void +起始版本: 9 +- delete(): Promise\ +起始版本: 9 + + **系统能力:** SystemCapability.Communication.NetStack + **回调或返回值:** +| 类型 | 说明 | +| --------| --------| +| callback | 回调函数返回删除结果。 | +| Promise | 以Promise形式返回删除结果。 | + + **示例代码1:** +示例代码(callback): +```ts +import http from '@ohos.net.http'; +import { BusinessError } from '@ohos.base'; + +let httpResponseCache = http.createHttpResponseCache(); +httpResponseCache.delete((err: BusinessError) => { + if (err) { + console.info('delete fail'); + return; + } + console.info('delete success'); +}); + +``` + + + **示例代码2:** +示例代码(promise): +```ts +import http from '@ohos.net.http'; +import { BusinessError } from '@ohos.base'; + +let httpResponseCache = http.createHttpResponseCache(); +httpResponseCache.delete().then(() => { + console.info('delete success'); +}).catch((err: Error) => { + console.info('delete fail'); +}); + +``` + + + **示例代码:** +```ts +// 引入包名 +import http from '@ohos.net.http'; +import { BusinessError } from '@ohos.base'; + +// 每一个httpRequest对应一个HTTP请求任务,不可复用 +let httpRequest = http.createHttp(); +// 用于订阅HTTP响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息 +// 从API 8开始,使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+ +httpRequest.on('headersReceive', (header:Object) => { + console.info('header: ' + JSON.stringify(header)); +}); +class ExtraData { + public data: string; + + constructor(data: string) { + this.data = data; + } +} +class Header { + public contentType: string; + + constructor(contentType: string) { + this.contentType = contentType; + } +} +httpRequest.request( + // 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定 + "EXAMPLE_URL", + { + method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET + // 当使用POST请求时此字段用于传递内容 + extraData: new ExtraData('data to send'), + expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型 + usingCache: true, // 可选,默认为true + priority: 1, // 可选,默认为1 + // 开发者根据自身业务需要添加header字段 + header: new Header('application/json'), + readTimeout: 60000, // 可选,默认为60000ms + connectTimeout: 60000, // 可选,默认为60000ms + usingProtocol: http.HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定 + usingProxy: false, //可选,默认不使用网络代理,自API 10开始支持该属性 + caPath: "", // 可选,默认使用系统预设CA证书,自API 10开始支持该属性 + }, + (err: BusinessError, data: http.HttpResponse ) => { + if (!err) { + // data.result为HTTP响应内容,可根据业务需要进行解析 + console.info('Result:' + JSON.stringify(data.result)); + console.info('code:' + JSON.stringify(data.responseCode)); + // data.header为HTTP响应头,可根据业务需要进行解析 + console.info('header:' + JSON.stringify(data.header)); + console.info('cookies:' + JSON.stringify(data.cookies)); // 8+ + // 取消订阅HTTP响应头事件 + httpRequest.off('headersReceive'); + // 当该请求使用完毕时,开发者务必调用destroy方法主动销毁该JavaScript Object。 + httpRequest.destroy(); + } else { + console.info('error:' + JSON.stringify(err)); + // 取消订阅HTTP响应头事件 + httpRequest.off('headersReceive'); + // 当该请求使用完毕时,开发者务必调用destroy方法主动销毁该JavaScript Object。 + httpRequest.destroy(); + }}); + +``` +