1.2K Star 6.4K Fork 5.4K

OpenHarmony/docs

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
js-apis-inner-application-uiAbilityContext.md 80.70 KB
一键复制 编辑 原始数据 按行查看 历史
zhuhan 提交于 2024-07-04 09:32 . Merge branch '0704' into 0626

UIAbilityContext

UIAbilityContext是需要保存状态的UIAbility所对应的context,继承自Context,提供UIAbility的相关配置信息以及操作UIAbility和ServiceExtensionAbility的方法,如启动UIAbility,停止当前UIAbilityContext所属的UIAbility,启动、停止、连接、断开连接ServiceExtensionAbility等。

说明:

  • 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
  • 本模块接口仅可在Stage模型下使用。

导入模块

import { common } from '@kit.AbilityKit';

属性

系统能力:SystemCapability.Ability.AbilityRuntime.Core

名称 类型 可读 可写 说明
abilityInfo AbilityInfo UIAbility的相关信息。
原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。
currentHapModuleInfo HapModuleInfo 当前HAP的信息。
原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。
config Configuration 与UIAbility相关的配置信息,如语言、颜色模式等。
原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。
windowStage12+ window.WindowStage 当前WindowStage对象。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。 仅支持在主线程调用。

关于示例代码的说明:

在本文档的示例中,通过this.context来获取UIAbilityContext,其中this代表继承自UIAbilityUIAbility实例。如需要在页面中使用UIAbilityContext提供的能力,请参见获取UIAbility的上下文信息

UIAbilityContext.startAbility

startAbility(want: Want, callback: AsyncCallback<void>): void

启动Ability(callback形式)。仅支持在主线程调用。

说明:

组件启动规则详见:组件启动规则(Stage模型)

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力:SystemCapability.Ability.AbilityRuntime.Core

参数:

参数名 类型 必填 说明
want Want 启动Ability的want信息。
callback AsyncCallback<void> callback形式返回启动结果。

错误码:

以下错误码详细介绍请参考通用错误码元能力子系统错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
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.
16000018 The application is not allow jumping to other applications.
16000019 Can not match any component.
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.
16000073 The app clone index is invalid.

示例:

import { UIAbility, Want } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  onForeground() {
    let want: Want = {
      bundleName: 'com.example.myapplication',
      abilityName: 'EntryAbility'
    };

    try {
      this.context.startAbility(want, (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}`);
    }
  }
}

UIAbilityContext.startAbility

startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void

启动Ability(callback形式)。仅支持在主线程调用。

说明:

组件启动规则详见:组件启动规则(Stage模型)

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力:SystemCapability.Ability.AbilityRuntime.Core

参数:

参数名 类型 必填 说明
want Want 启动Ability的want信息。
options StartOptions 启动Ability所携带的参数。
callback AsyncCallback<void> callback形式返回启动结果。

错误码:

以下错误码详细介绍请参考通用错误码元能力子系统错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
16000001 The specified ability does not exist.
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.
16000011 The context does not exist.
16000012 The application is controlled.
16000013 The application is controlled by EDM.
16000018 The application is not allow jumping to other applications.
16000019 Can not match any component.
16000050 Internal error.
16000053 The ability is not on the top of the UI.
16000055 Installation-free timed out.
16000067 Start options check failed.
16000068 Ability already running.
16200001 The caller has been released.
16300003 The target application is not self application.
16000073 The app clone index is invalid.

示例:

import { UIAbility, Want, StartOptions } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  onForeground() {
    let want: Want = {
      deviceId: '',
      bundleName: 'com.example.myapplication',
      abilityName: 'EntryAbility'
    };
    let options: StartOptions = {
      displayId: 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}`);
    }
  }
}

UIAbilityContext.startAbility

startAbility(want: Want, options?: StartOptions): Promise<void>

启动Ability(promise形式)。仅支持在主线程调用。

说明:

组件启动规则详见:组件启动规则(Stage模型)

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力:SystemCapability.Ability.AbilityRuntime.Core

参数:

参数名 类型 必填 说明
want Want 启动Ability的want信息。
options StartOptions 启动Ability所携带的参数。

返回值:

类型 说明
Promise<void> Promise形式返回启动结果。

错误码:

以下错误码详细介绍请参考通用错误码元能力子系统错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
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.
16000018 The application is not allow jumping to other applications.
16000019 Can not match any component.
16000050 Internal error.
16000053 The ability is not on the top of the UI.
16000055 Installation-free timed out.
16000067 Start options check failed.
16000068 Ability already running.
16200001 The caller has been released.
16300003 The target application is not self application.
16000073 The app clone index is invalid.

示例:

import { UIAbility, Want, StartOptions } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  onForeground() {
    let want: Want = {
      bundleName: 'com.example.myapplication',
      abilityName: 'EntryAbility'
    };
    let options: StartOptions = {
      displayId: 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}`);
    }
  }
}

UIAbilityContext.startAbilityForResult

startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void

启动一个Ability。Ability被启动后,有如下情况(callback形式):

  • 正常情况下可通过调用terminateSelfWithResult接口使之终止并且返回结果给调用方。
  • 异常情况下比如杀死Ability会返回异常信息给调用方, 异常信息中resultCode为-1。
  • 如果被启动的Ability模式是单实例模式, 不同应用多次调用该接口启动这个Ability,当这个Ability调用terminateSelfWithResult接口使之终止时,只将正常结果返回给最后一个调用方, 其它调用方返回异常信息, 异常信息中resultCode为-1。仅支持在主线程调用。

说明:

组件启动规则详见:组件启动规则(Stage模型)

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力:SystemCapability.Ability.AbilityRuntime.Core

参数:

参数名 类型 必填 说明
want Want 启动Ability的want信息。
callback AsyncCallback<AbilityResult> 执行结果回调函数。

错误码:

以下错误码详细介绍请参考通用错误码元能力子系统错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
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.
16000018 The application is not allow jumping to other applications.
16000019 Can not match any component.
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.
16000073 The app clone index is invalid.

示例:

import { UIAbility, Want, common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

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}`);
    }
  }
}

UIAbilityContext.startAbilityForResult

startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>): void

启动一个Ability。Ability被启动后,有如下情况(callback形式):

  • 正常情况下可通过调用terminateSelfWithResult接口使之终止并且返回结果给调用方。
  • 异常情况下比如杀死Ability会返回异常信息给调用方,异常信息中resultCode为-1。
  • 如果被启动的Ability模式是单实例模式, 不同应用多次调用该接口启动这个Ability,当这个Ability调用terminateSelfWithResult接口使之终止时,只将正常结果返回给最后一个调用方,其它调用方返回异常信息, 异常信息中resultCode为-1。

说明:

组件启动规则详见:组件启动规则(Stage模型)

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力:SystemCapability.Ability.AbilityRuntime.Core

参数:

参数名 类型 必填 说明
want Want 启动Ability的want信息。
options StartOptions 启动Ability所携带的参数。
callback AsyncCallback<AbilityResult> 执行结果回调函数。

错误码:

以下错误码详细介绍请参考通用错误码元能力子系统错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
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.
16000011 The context does not exist.
16000012 The application is controlled.
16000013 The application is controlled by EDM.
16000018 The application is not allow jumping to other applications.
16000019 Can not match any component.
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.
16000073 The app clone index is invalid.

示例:

import { UIAbility, Want, common, StartOptions } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  onForeground() {
    let want: Want = {
      deviceId: '',
      bundleName: 'com.example.myapplication',
      abilityName: 'EntryAbility'
    };
    let options: StartOptions = {
      displayId: 0
    };

    try {
      this.context.startAbilityForResult(want, options, (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}`);
    }
  }
}

UIAbilityContext.startAbilityForResult

startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityResult>

启动一个Ability。Ability被启动后,有如下情况(promise形式):

  • 正常情况下可通过调用terminateSelfWithResult接口使之终止并且返回结果给调用方。
  • 异常情况下比如杀死Ability会返回异常信息给调用方, 异常信息中resultCode为-1。
  • 如果被启动的Ability模式是单实例模式, 不同应用多次调用该接口启动这个Ability,当这个Ability调用terminateSelfWithResult接口使之终止时,只将正常结果返回给最后一个调用方, 其它调用方返回异常信息, 异常信息中resultCode为-1。仅支持在主线程调用。

说明:

组件启动规则详见:组件启动规则(Stage模型)

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力:SystemCapability.Ability.AbilityRuntime.Core

参数:

参数名 类型 必填 说明
want Want 启动Ability的want信息。
options StartOptions 启动Ability所携带的参数。

返回值:

类型 说明
Promise<AbilityResult> Promise形式返回执行结果。

错误码:

以下错误码详细介绍请参考通用错误码元能力子系统错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
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.
16000018 The application is not allow jumping to other applications.
16000019 Can not match any component.
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.
16000073 The app clone index is invalid.

示例:

import { UIAbility, Want, common, StartOptions } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  onForeground() {
    let want: Want = {
      bundleName: 'com.example.myapplication',
      abilityName: 'EntryAbility'
    };
    let options: StartOptions = {
      displayId: 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}`);
    }
  }
}

UIAbilityContext.terminateSelf

terminateSelf(callback: AsyncCallback<void>): void

停止Ability自身(callback形式)。仅支持在主线程调用。

说明:

调用该接口后,任务中心的任务默认不会清理,如需清理,需要配置removeMissionAfterTerminate为true。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力:SystemCapability.Ability.AbilityRuntime.Core

参数:

参数名 类型 必填 说明
callback AsyncCallback<void> 停止Ability自身的回调函数。

错误码:

以下错误码详细介绍请参考通用错误码元能力子系统错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
16000009 An ability cannot be started or stopped in Wukong mode.
16000011 The context does not exist.
16000050 Internal error.

示例:

import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

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}`);
    }
  }
}

UIAbilityContext.terminateSelf

terminateSelf(): Promise<void>

停止Ability自身(promise形式)。仅支持在主线程调用。

说明:

调用该接口后,任务中心的任务默认不会清理,如需清理,需要配置removeMissionAfterTerminate为true。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力:SystemCapability.Ability.AbilityRuntime.Core

返回值:

类型 说明
Promise<void> 停止Ability自身的回调函数。

错误码:

以下错误码详细介绍请参考元能力子系统错误码

错误码ID 错误信息
16000009 An ability cannot be started or stopped in Wukong mode.
16000011 The context does not exist.
16000050 Internal error.

示例:

import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

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}`);
    }
  }
}

UIAbilityContext.terminateSelfWithResult

terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>): void

停止当前的Ability。如果该Ability是通过调用startAbilityForResult接口被拉起的,调用terminateSelfWithResult接口时会将结果返回给调用者,如果该Ability不是通过调用startAbilityForResult接口被拉起的,调用terminateSelfWithResult接口时不会有结果返回给调用者(callback形式)。仅支持在主线程调用。

说明:

调用该接口后,任务中心的任务默认不会清理,如需清理,需要配置removeMissionAfterTerminate为true。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力:SystemCapability.Ability.AbilityRuntime.Core

参数:

参数名 类型 必填 说明
parameter AbilityResult 返回给调用startAbilityForResult 接口调用方的相关信息。
callback AsyncCallback<void> callback形式返回停止结果。

错误码:

以下错误码详细介绍请参考通用错误码元能力子系统错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
16000009 An ability cannot be started or stopped in Wukong mode.
16000011 The context does not exist.
16000050 Internal error.

示例:

import { UIAbility, Want, common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  onForeground() {
    let want: Want = {
      bundleName: 'com.example.myapplication',
      abilityName: 'EntryAbility'
    };
    let resultCode = 100;
    // 返回给接口调用方AbilityResult信息
    let abilityResult: common.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}`);
    }
  }
}

UIAbilityContext.terminateSelfWithResult

terminateSelfWithResult(parameter: AbilityResult): Promise<void>

停止当前的Ability。如果该Ability是通过调用startAbilityForResult接口被拉起的,调用terminateSelfWithResult接口时会将结果返回给调用者,如果该Ability不是通过调用startAbilityForResult接口被拉起的,调用terminateSelfWithResult接口时不会有结果返回给调用者(promise形式)。仅支持在主线程调用。

说明:

调用该接口后,任务中心的任务默认不会清理,如需清理,需要配置removeMissionAfterTerminate为true。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力:SystemCapability.Ability.AbilityRuntime.Core

参数:

参数名 类型 必填 说明
parameter AbilityResult 返回给startAbilityForResult 调用方的信息。

返回值:

类型 说明
Promise<void> promise形式返回停止结果。

错误码:

以下错误码详细介绍请参考通用错误码元能力子系统错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
16000009 An ability cannot be started or stopped in Wukong mode.
16000011 The context does not exist.
16000050 Internal error.

示例:

import { UIAbility, Want, common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  onForeground() {
    let want: Want = {
      bundleName: 'com.example.myapplication',
      abilityName: 'EntryAbility'
    };
    let resultCode = 100;
    // 返回给接口调用方AbilityResult信息
    let abilityResult: common.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}`);
    }
  }
}

UIAbilityContext.connectServiceExtensionAbility

connectServiceExtensionAbility(want: Want, options: ConnectOptions): number

将当前Ability连接到一个ServiceExtensionAbility。仅支持在主线程调用。

说明:

组件启动规则详见:组件启动规则(Stage模型)

系统能力:SystemCapability.Ability.AbilityRuntime.Core

参数:

参数名 类型 必填 说明
want Want 连接ServiceExtensionAbility的want信息。
options ConnectOptions 与ServiceExtensionAbility建立连接后回调函数的实例。

返回值:

类型 说明
number 返回Ability连接的结果code。

错误码:

以下错误码详细介绍请参考通用错误码元能力子系统错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
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.
16000053 The ability is not on the top of the UI.
16000055 Installation-free timed out.

示例:

import { UIAbility, Want, common } from '@kit.AbilityKit';
import { rpc } from '@kit.IPCKit';
import { BusinessError } from '@kit.BasicServicesKit';

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}`);
    }
  }
}

UIAbilityContext.disconnectServiceExtensionAbility

disconnectServiceExtensionAbility(connection: number): Promise<void>

断开与ServiceExtensionAbility的连接,断开连接之后需要将连接成功时返回的remote对象置空(promise形式)。仅支持在主线程调用。

系统能力:SystemCapability.Ability.AbilityRuntime.Core

参数:

参数名 类型 必填 说明
connection number 连接的ServiceExtensionAbility的数字代码,即connectServiceExtensionAbility返回的connectionId。

返回值:

类型 说明
Promise<void> 返回执行结果。

错误码:

以下错误码详细介绍请参考通用错误码元能力子系统错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
16000011 The context does not exist.
16000050 Internal error.

示例:

import { UIAbility } from '@kit.AbilityKit';
import { rpc } from '@kit.IPCKit';
import { BusinessError } from '@kit.BasicServicesKit';

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}`);
    }
  }
}

UIAbilityContext.disconnectServiceExtensionAbility

disconnectServiceExtensionAbility(connection: number, callback: AsyncCallback<void>): void

断开与ServiceExtensionAbility的连接,断开连接之后需要将连接成功时返回的remote对象置空(callback形式)。仅支持在主线程调用。

系统能力:SystemCapability.Ability.AbilityRuntime.Core

参数:

参数名 类型 必填 说明
connection number 连接的ServiceExtensionAbility的数字代码,即connectServiceExtensionAbility返回的connectionId。
callback AsyncCallback<void> callback形式返回断开连接的结果。

错误码:

以下错误码详细介绍请参考通用错误码元能力子系统错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
16000011 The context does not exist.
16000050 Internal error.

示例:

import { UIAbility } from '@kit.AbilityKit';
import { rpc } from '@kit.IPCKit';
import { BusinessError } from '@kit.BasicServicesKit';

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}`);
    }
  }
}

UIAbilityContext.startAbilityByCall

startAbilityByCall(want: Want): Promise<Caller>

跨设备场景下,启动指定Ability至前台或后台,同时获取其Caller通信接口,调用方可使用Caller与被启动的Ability进行通信。仅支持在主线程调用。

说明:

组件启动规则详见:组件启动规则(Stage模型)

需要权限: ohos.permission.DISTRIBUTED_DATASYNC

说明:

API version 11之前的版本,该接口需要申请权限ohos.permission.ABILITY_BACKGROUND_COMMUNICATION(该权限仅系统应用可申请)。从API version 11开始,该接口需要申请的权限变更为ohos.permission.DISTRIBUTED_DATASYNC权限。

系统能力:SystemCapability.Ability.AbilityRuntime.Core

参数:

参数名 类型 必填 说明
want Want 传入需要启动的Ability的信息,包含abilityName、moduleName、bundleName、deviceId、parameters(可选),parameters缺省或为空表示后台启动Ability。

返回值:

类型 说明
Promise<Caller> 获取要通讯的caller对象。

错误码:

以下错误码详细介绍请参考通用错误码元能力子系统错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
16000001 The specified ability does not exist.
16000002 Incorrect ability type.
16000004 Can not start invisible component.
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.
16000018 The application is not allow jumping to other applications.
16000050 Internal error.
16000073 The app clone index is invalid.

示例:

后台启动:

import { UIAbility, Caller, Want } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

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}`);
    }
  }
}

前台启动:

import { UIAbility, Caller, Want } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  onForeground() {
    let caller: Caller;
    // 前台启动Ability,将parameters中的'ohos.aafwk.param.callAbilityToForeground'配置为true
    let wantForeground: Want = {
      bundleName: 'com.example.myapplication',
      moduleName: 'entry',
      abilityName: 'EntryAbility',
      deviceId: '',
      parameters: {
        'ohos.aafwk.param.callAbilityToForeground': true
      }
    };

    try {
      this.context.startAbilityByCall(wantForeground)
        .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}`);
    }
  }
}

UIAbilityContext.setMissionLabel

setMissionLabel(label: string, callback: AsyncCallback<void>): void

设置UIAbility在任务中显示的名称(callback形式)。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力:SystemCapability.Ability.AbilityRuntime.Core

参数:

参数名 类型 必填 说明
label string 显示名称。
callback AsyncCallback<void> 回调函数,返回接口调用是否成功的结果。

错误码:

以下错误码详细介绍请参考通用错误码元能力子系统错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
16000011 The context does not exist.
16000050 Internal error.

示例:

import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
    this.context.setMissionLabel('test', (result: BusinessError) => {
      console.info(`setMissionLabel: ${JSON.stringify(result)}`);
    });
  }
}

UIAbilityContext.setMissionLabel

setMissionLabel(label: string): Promise<void>

设置UIAbility在任务中显示的名称(promise形式)。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力:SystemCapability.Ability.AbilityRuntime.Core

参数:

参数名 类型 必填 说明
label string 显示名称。

返回值:

类型 说明
Promise<void> 返回一个Promise,包含接口的结果。

错误码:

以下错误码详细介绍请参考通用错误码元能力子系统错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
16000011 The context does not exist.
16000050 Internal error.

示例:

import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  onCreate(want: Want, launchParam: AbilityConstant.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}`);
    });
  }
}

UIAbilityContext.setMissionContinueState10+

setMissionContinueState(state: AbilityConstant.ContinueState, callback: AsyncCallback<void>): void

设置UIAbility任务中流转状态(callback形式)。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力:SystemCapability.Ability.AbilityRuntime.Core

参数:

参数名 类型 必填 说明
state AbilityConstant.ContinueState 流转状态。
callback AsyncCallback<void> 回调函数,返回接口调用是否成功的结果。

错误码:

错误码详细介绍请参考通用错误码元能力子系统错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
16000011 The context does not exist.
16000050 Internal error.

示例:

import { UIAbility, AbilityConstant } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  onForeground() {
    this.context.setMissionContinueState(AbilityConstant.ContinueState.INACTIVE, (result: BusinessError) => {
      console.info(`setMissionContinueState: ${JSON.stringify(result)}`);
    });
  }
}

UIAbilityContext.setMissionContinueState10+

setMissionContinueState(state: AbilityConstant.ContinueState): Promise<void>

设置UIAbility任务中流转状态(promise形式)。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力:SystemCapability.Ability.AbilityRuntime.Core

参数:

参数名 类型 必填 说明
state AbilityConstant.ContinueState 流转状态。

返回值:

类型 说明
Promise<void> 返回一个Promise,包含接口的结果。

错误码:

错误码详细介绍请参考通用错误码元能力子系统错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
16000011 The context does not exist.
16000050 Internal error.

示例:

import { UIAbility, AbilityConstant } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

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}`);
    });
  }
}

UIAbilityContext.restoreWindowStage

restoreWindowStage(localStorage: LocalStorage): void

恢复UIAbility中的WindowStage数据。仅支持在主线程调用。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力:SystemCapability.Ability.AbilityRuntime.Core

参数:

参数名 类型 必填 说明
localStorage LocalStorage 用于恢复window stage的存储数据。

错误码:

以下错误码详细介绍请参考通用错误码元能力子系统错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
16000011 The context does not exist.
16000050 Internal error.

示例:

import { UIAbility } from '@kit.AbilityKit';

export default class EntryAbility extends UIAbility {
  onForeground() {
    let storage = new LocalStorage();
    this.context.restoreWindowStage(storage);
  }
}

UIAbilityContext.isTerminating

isTerminating(): boolean

查询UIAbility是否在terminating状态。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力:SystemCapability.Ability.AbilityRuntime.Core

返回值:

类型 说明
boolean true:ability当前处于terminating状态;false:不处于terminating状态。

错误码:

以下错误码详细介绍请参考元能力子系统错误码

错误码ID 错误信息
16000011 The context does not exist.

示例:

import { UIAbility } from '@kit.AbilityKit';

export default class EntryAbility extends UIAbility {
  onForeground() {
    let isTerminating: boolean = this.context.isTerminating();
    console.info(`ability state is ${isTerminating}`);
  }
}

UIAbilityContext.requestDialogService

requestDialogService(want: Want, result: AsyncCallback<dialogRequest.RequestResult>): void

启动一个支持模态弹框的ServiceExtensionAbility。ServiceExtensionAbility被启动后,应用弹出模态弹框,通过调用setRequestResult接口返回结果给调用者。仅支持在主线程调用。

说明:

组件启动规则详见:组件启动规则(Stage模型)

系统能力:SystemCapability.Ability.AbilityRuntime.Core

参数:

参数名 类型 必填 说明
want Want 启动ServiceExtensionAbility的want信息。
result AsyncCallback<dialogRequest.RequestResult> 执行结果回调函数。

错误码:

以下错误码详细介绍请参考通用错误码元能力子系统错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
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.

示例:

import { UIAbility, Want, dialogRequest } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

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}`);
    }
  }
}

UIAbilityContext.requestDialogService

requestDialogService(want: Want): Promise<dialogRequest.RequestResult>

启动一个支持模态弹框的ServiceExtensionAbility。ServiceExtensionAbility被启动后,应用弹出模态弹框,通过调用setRequestResult接口返回结果给调用者(promise形式)。仅支持在主线程调用。

说明:

组件启动规则详见:组件启动规则(Stage模型)

系统能力:SystemCapability.Ability.AbilityRuntime.Core

参数:

参数名 类型 必填 说明
want Want 启动ServiceExtensionAbility的want信息。

返回值:

类型 说明
Promise<dialogRequest.RequestResult> Promise形式返回执行结果。

错误码:

以下错误码详细介绍请参考通用错误码元能力子系统错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
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.

示例:

import { UIAbility, Want, dialogRequest } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

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}`);
    }
  }
}

UIAbilityContext.reportDrawnCompleted10+

reportDrawnCompleted(callback: AsyncCallback<void>): void

当页面加载完成(loadContent成功)时,为开发者提供打点功能(callback形式)。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力:SystemCapability.Ability.AbilityRuntime.Core

参数:

参数名 类型 必填 说明
callback AsyncCallback<void> 页面加载完成打点的回调函数。

错误码:

以下错误码详细介绍请参考元能力子系统错误码

错误码ID 错误信息
16000011 The context does not exist.
16000050 Internal error.

示例:

import { UIAbility } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';

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");
  }
};

UIAbilityContext.startAbilityByType11+

startAbilityByType(type: string, wantParam: Record<string, Object>, abilityStartCallback: AbilityStartCallback, callback: AsyncCallback<void>) : void

通过type隐式启动UIExtensionAbility。使用callback异步回调。仅支持在主线程调用。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力:SystemCapability.Ability.AbilityRuntime.Core

参数:

参数名 类型 必填 说明
type string 显示拉起的UIExtensionAbility类型,取值详见通过startAbilityByType拉起特定场景的意图面板
wantParam Record<string, Object> 表示扩展参数。
abilityStartCallback AbilityStartCallback 执行结果回调函数。
callback AsyncCallback<void> 回调函数,返回接口调用是否成功的结果。

错误码:

以下错误码详细介绍请参考通用错误码元能力子系统错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
16000050 Internal error.

示例:

import { UIAbility, common } from '@kit.AbilityKit';

export default class EntryAbility extends UIAbility {
  onForeground() {
    let wantParam: Record<string, Object> = {
      'time': '2023-10-23 20:45'
    };
    let abilityStartCallback: common.AbilityStartCallback = {
      onError: (code: number, name: string, message: string) => {
        console.log(`code:` + code + `name:` + name + `message:` + message);
      },
      onResult: (abilityResult: common.AbilityResult) => {
        console.log(`resultCode:` + abilityResult.resultCode + `bundleName:` + abilityResult.want?.bundleName);
      }
    };

    this.context.startAbilityByType("photoEditor", wantParam, abilityStartCallback, (err) => {
      if (err) {
        console.error(`startAbilityByType fail, err: ${JSON.stringify(err)}`);
      } else {
        console.log(`success`);
      }
    });
  }
}

UIAbilityContext.startAbilityByType11+

startAbilityByType(type: string, wantParam: Record<string, Object>, abilityStartCallback: AbilityStartCallback) : Promise<void>

通过type隐式启动UIExtensionAbility。使用Promise异步回调。仅支持在主线程调用。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力:SystemCapability.Ability.AbilityRuntime.Core

参数:

参数名 类型 必填 说明
type string 显示拉起的UIExtensionAbility类型,取值详见通过startAbilityByType拉起特定场景的意图面板
wantParam Record<string, Object> 表示扩展参数。
abilityStartCallback AbilityStartCallback 执行结果回调函数。

返回值:

类型 说明
Promise<void> Promise对象。无返回结果的Promise对象。

错误码:

以下错误码详细介绍请参考通用错误码元能力子系统错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
16000050 Internal error.

示例:

import { UIAbility, common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  onForeground() {
    let wantParam: Record<string, Object> = {
      'time': '2023-10-23 20:45'
    };
    let abilityStartCallback: common.AbilityStartCallback = {
      onError: (code: number, name: string, message: string) => {
        console.log(`code:` + code + `name:` + name + `message:` + message);
      },
      onResult: (abilityResult: common.AbilityResult) => {
        console.log(`resultCode:` + abilityResult.resultCode + `bundleName:` + abilityResult.want?.bundleName);
      }
    };

    this.context.startAbilityByType("photoEditor", wantParam, abilityStartCallback).then(() => {
      console.log(`startAbilityByType success`);
    }).catch((err: BusinessError) => {
      console.error(`startAbilityByType fail, err: ${JSON.stringify(err)}`);
    });
  }
}

UIAbilityContext.showAbility12+

showAbility(): Promise<void>

显示当前Ability。使用Promise异步回调。仅在平板类设备上生效。

调用此接口要求当前Ability必须通过UIAbilityContext.startAbility启动,且启动入参中options.processMode必须设置为NEW_PROCESS_ATTACH_TO_STATUS_BAR_ITEM或者ATTACH_TO_STATUS_BAR_ITEM。仅支持在主线程调用。

系统能力:SystemCapability.Ability.AbilityRuntime.Core

返回值:

类型 说明
Promise<void> Promise对象。无返回结果的Promise对象。

错误码:

以下错误码详细介绍请参考元能力子系统错误码

错误码ID 错误信息
16000050 Internal error.
16000067 Start options check failed.

示例:

// Index.ets
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  @State showAbility: string = 'showAbility'

  build() {
    Row() {
      Column() {
        Text(this.showAbility)
          .fontSize(30)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            let context = getContext(this) as common.UIAbilityContext;

            context.showAbility().then(() => {
              console.log(`showAbility success`);
            }).catch((err: BusinessError) => {
              console.error(`showAbility fail, err: ${JSON.stringify(err)}`);
            });
          });
      }
      .width('100%')
    }
    .height('100%')
  }
}
// EntryAbility.ts
import { UIAbility, Want, StartOptions, contextConstant } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  onForeground() {
    let want: Want = {
      deviceId: '',
      bundleName: 'com.example.myapplication',
      abilityName: 'EntryAbility'
    };
    let options: StartOptions = {
      displayId: 0,
      processMode: contextConstant.ProcessMode.NEW_PROCESS_ATTACH_TO_STATUS_BAR_ITEM
    };

    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}`);
    }
  }
}

UIAbilityContext.hideAbility12+

hideAbility(): Promise<void>

隐藏当前Ability。使用Promise异步回调。仅在平板类设备上生效。

调用此接口要求当前Ability必须通过UIAbilityContext.startAbility启动,且启动入参中options.processMode必须设置为NEW_PROCESS_ATTACH_TO_STATUS_BAR_ITEM或者ATTACH_TO_STATUS_BAR_ITEM。仅支持在主线程调用。

系统能力:SystemCapability.Ability.AbilityRuntime.Core

返回值:

类型 说明
Promise<void> Promise对象。无返回结果的Promise对象。

错误码:

以下错误码详细介绍请参考元能力子系统错误码

错误码ID 错误信息
16000050 Internal error.
16000067 Start options check failed.

示例:

// Index.ets
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  @State hideAbility: string = 'hideAbility'

  build() {
    Row() {
      Column() {
        Text(this.hideAbility)
          .fontSize(30)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            let context = getContext(this) as common.UIAbilityContext;

            context.hideAbility().then(() => {
              console.log(`hideAbility success`);
            }).catch((err: BusinessError) => {
              console.error(`hideAbility fail, err: ${JSON.stringify(err)}`);
            });
          });
      }
      .width('100%')
    }
    .height('100%')
  }
}
// EntryAbility.ts
import { UIAbility, Want, StartOptions, contextConstant } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  onForeground() {
    let want: Want = {
      deviceId: '',
      bundleName: 'com.example.myapplication',
      abilityName: 'EntryAbility'
    };
    let options: StartOptions = {
      displayId: 0,
      processMode: contextConstant.ProcessMode.NEW_PROCESS_ATTACH_TO_STATUS_BAR_ITEM
    };

    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}`);
    }
  }
}

UIAbilityContext.moveAbilityToBackground12+

moveAbilityToBackground(): Promise<void>

将处于前台的Ability移动到后台。使用Promise异步回调。仅支持在主线程调用。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力:SystemCapability.Ability.AbilityRuntime.Core

返回值:

类型 说明
Promise<void> Promise对象。无返回结果的Promise对象。

错误码:

以下错误码详细介绍请参考[元能力子系统错误码]。

错误码ID 错误信息
16000011 The context does not exist.
16000050 Internal error.
16000061 Operation not supported.
16000065 The interface can be called only when ability is foreground.
16000066 An ability cannot move to foreground or background in Wukong mode.

示例:

import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  @State moveAbilityToBackground: string = 'Move To Background'

  build() {
    Row() {
      Column() {
        Text(this.moveAbilityToBackground)
          .fontSize(30)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            let context = getContext(this) as common.UIAbilityContext;

            context.moveAbilityToBackground().then(() => {
              console.log(`moveAbilityToBackground success.`);
            }).catch((err: BusinessError) => {
              console.log(`moveAbilityToBackground error: ${JSON.stringify(err)}.`);
            });
          });
      }
      .width('100%')
    }
    .height('100%')
  }
}

UIAbilityContext.openAtomicService12+

openAtomicService(appId: string, options?: AtomicServiceOptions): Promise<AbilityResult>

跳出式启动EmbeddableUIAbility,并返回结果。使用Promise异步回调。 分为以下几种情况:

  • 正常情况下可通过调用terminateSelfWithResult接口使之终止并且返回结果给调用方。
  • 异常情况下比如杀死EmbeddableUIAbility会返回异常信息给调用方,异常信息中resultCode为-1。
  • 如果不同应用多次调用该接口启动同一个EmbeddableUIAbility,当这个EmbeddableUIAbility调用terminateSelfWithResult接口使之终止时,只将正常结果返回给最后一个调用方, 其它调用方返回异常信息,异常信息中resultCode为-1。仅支持在主线程调用。

说明:

组件启动规则详见:组件启动规则(Stage模型)

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力:SystemCapability.Ability.AbilityRuntime.Core

参数:

参数名 类型 必填 说明
appId string 应用的唯一标识,由云端统一分配。
options AtomicServiceOptions 跳出式启动原子化服务所携带的参数。

返回值:

类型 说明
Promise<AbilityResult> Promise对象。返回AbilityResult对象。

错误码:

以下错误码详细介绍请参考通用错误码元能力子系统错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
16000002 Incorrect ability type.
16000003 The appId does not exist.
16000004 Can not start invisible component.
16000011 The context does not exist.
16000012 The application is controlled.
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.

示例:

import { UIAbility, common, AtomicServiceOptions } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  onForeground() {
    let appId: string = '6918661953712445909';
    let options: AtomicServiceOptions = {
      displayId: 0
    };

    try {
      this.context.openAtomicService(appId, options)
        .then((result: common.AbilityResult) => {
          // 执行正常业务
          console.info('openAtomicService succeed');
        })
        .catch((err: BusinessError) => {
          // 处理业务逻辑错误
          console.error(`openAtomicService 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(`openAtomicService failed, code is ${code}, message is ${message}`);
    }
  }
}

UIAbilityContext.openLink12+

openLink(link: string, options?: OpenLinkOptions, callback?: AsyncCallback<AbilityResult>): Promise<void>

通过AppLinking启动UIAbility,使用Promise异步回调。

通过在link字段中传入标准格式的URL,基于隐式want匹配规则拉起目标UIAbility。目标方必须具备以下过滤器特征,才能处理AppLinking链接:

  • "actions"列表中包含"ohos.want.action.viewData"。
  • "entities"列表中包含"entity.system.browsable"。
  • "uris"列表中包含"scheme"为"https"且"domainVerify"为true的元素。

如果希望获取被拉起方终止后的结果,可以设置callback参数,此参数的使用可参照startAbilityForResult接口。 传入的参数不合法时,如未设置必选参数或link字符串不是标准格式的URL,接口会直接抛出异常。参数校验通过,拉起目标方时出现的错误通过promise返回错误信息。仅支持在主线程调用。

说明:

组件启动规则详见:组件启动规则(Stage模型)

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力:SystemCapability.Ability.AbilityRuntime.Core

参数:

参数名 类型 必填 说明
link string 指示要打开的标准格式URL。
options OpenLinkOptions 打开URL的选项参数。
callback AsyncCallback<AbilityResult> 执行结果回调函数。

返回值:

类型 说明
Promise<void> Promise对象。无返回结果的Promise对象。

错误码:

以下错误码详细介绍请参考通用错误码元能力子系统错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
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.
16000019 Can not match any component.
16200001 The caller has been released.

示例:

import { common, OpenLinkOptions } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';

const DOMAIN = 0xeeee;
const TAG: string = '[openLinkDemo]';

@Entry
@Component
struct Index {
  @State message: string = 'I am caller';

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
        Button('start browser', { type: ButtonType.Capsule, stateEffect: true })
          .width('87%')
          .height('5%')
          .margin({ bottom: '12vp' })
          .onClick(() => {
            let context = getContext(this) as common.UIAbilityContext;
            let link: string = 'https://www.example.com';
            let openLinkOptions: OpenLinkOptions = {
              appLinkingOnly: true,
              parameters: { demo_key: 'demo_value' }
            };

            try {
              context.openLink(
                link,
                openLinkOptions,
                (err, result) => {
                  hilog.error(DOMAIN, TAG, `openLink callback error.code: ${JSON.stringify(err)}`);
                  hilog.info(DOMAIN, TAG, `openLink callback result: ${JSON.stringify(result.resultCode)}`);
                  hilog.info(DOMAIN, TAG, `openLink callback result data: ${JSON.stringify(result.want)}`);
                }
              ).then(() => {
                hilog.info(DOMAIN, TAG, `open link success.`);
              }).catch((err: BusinessError) => {
                hilog.error(DOMAIN, TAG, `open link failed, errCode ${JSON.stringify(err.code)}`);
              });
            }
            catch (e) {
              hilog.error(DOMAIN, TAG, `exception occured, errCode ${JSON.stringify(e.code)}`);
            }
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
其他
1
https://gitee.com/openharmony/docs.git
git@gitee.com:openharmony/docs.git
openharmony
docs
docs
master

搜索帮助

344bd9b3 5694891 D2dac590 5694891