汕尾海湾 发表于 2024-12-19 12:33:58

鸿蒙5.0开发进阶:ArkTS API-UIExtensionContext

往期鸿蒙全套实战文章必看:(文中附带全栈鸿蒙学习资料)



[*] 鸿蒙开发核心知识点,看这篇文章就够了
[*] 最新版!鸿蒙HarmonyOS Next应用开发实战学习路线
[*] 鸿蒙HarmonyOS NEXT开发技术最全学习路线指南
[*] 鸿蒙应用开发实战项目,看这一篇文章就够了(部门项目附源码)
UIExtensionContext

UIExtensionContext是UIExtensionAbility的上下文环境,继承自ExtensionContext,提供UIExtensionAbility的相关配置信息以及利用UIAbility的方法,如启动UIAbility等。
说明
   

[*]本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标志接口的起始版本。
[*]本模块接口仅可在Stage模子下使用。
[*]本模块接口需要在主线程中使用,不要在Worker、TaskPool等子线程中使用。
导入模块

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

startAbility(want: Want, callback: AsyncCallback<void>): void
启动Ability。使用callback异步回调。
   说明
组件启动规则详见:组件启动规则(Stage模子)。
系统能力:SystemCapability.Ability.AbilityRuntime.Core
参数:
参数名类型必填说明wantWant是启动Ability的want信息。callbackAsyncCallback<void>是回调函数。当启动Ability成功,err为undefined,否则为错误对象。 错误码:
以下错误码具体先容。
错误码ID错误信息201The application does not have permission to call the interface.401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.16000001The specified ability does not exist.16000002Incorrect ability type.16000004Can not start invisible component.16000005The specified process does not have the permission.16000006Cross-user operations are not allowed.16000008The crowdtesting application expires.16000009An ability cannot be started or stopped in Wukong mode.16000010The call with the continuation flag is forbidden.16000011The context does not exist.16000012The application is controlled.16000013The application is controlled by EDM.16000018The application is not allow jumping to other applications.16000019Can not match any component.16000050Internal error.16000053The ability is not on the top of the UI.16000055Installation-free timed out.16000069The extension cannot start the third party application.16000070The extension cannot start the service.16200001The caller has been released.16000073The app clone index is invalid. 示例:
import { UIExtensionAbility, Want } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIExtensionAbility {

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

startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void
启动Ability。使用callback异步回调。
   说明
组件启动规则详见:组件启动规则(Stage模子)。
系统能力:SystemCapability.Ability.AbilityRuntime.Core
参数:
参数名类型必填说明wantWant是启动Ability的want信息。optionsStartOptions是启动Ability所携带的参数。callbackAsyncCallback<void>是回调函数。当启动Ability成功,err为undefined,否则为错误对象。 错误码:
以下错误码具体先容。
错误码ID错误信息201The application does not have permission to call the interface.401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.16000001The specified ability does not exist.16000004Can not start invisible component.16000005The specified process does not have the permission.16000006Cross-user operations are not allowed.16000008The crowdtesting application expires.16000009An ability cannot be started or stopped in Wukong mode.16000011The context does not exist.16000012The application is controlled.16000013The application is controlled by EDM.16000018The application is not allow jumping to other applications.16000019Can not match any component.16000050Internal error.16000053The ability is not on the top of the UI.16000055Installation-free timed out.16000069The extension cannot start the third party application.16000070The extension cannot start the service.16200001The caller has been released.16000073The app clone index is invalid. 示例:
import { UIExtensionAbility, Want, StartOptions } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIExtensionAbility {
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}`);
    }
}
} UIExtensionContext.startAbility

startAbility(want: Want, options?: StartOptions): Promise<void>
启动Ability。使用Promise异步回调。
   说明
组件启动规则详见:组件启动规则(Stage模子)。
系统能力:SystemCapability.Ability.AbilityRuntime.Core
参数:
参数名类型必填说明wantWant是启动Ability的want信息。optionsStartOptions否启动Ability所携带的参数。 返回值:
类型说明Promise<void>Promise对象。无返回结果的Promise对象。 错误码:
以下错误码具体先容。
错误码ID错误信息201The application does not have permission to call the interface.401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.16000001The specified ability does not exist.16000002Incorrect ability type.16000004Can not start invisible component.16000005The specified process does not have the permission.16000006Cross-user operations are not allowed.16000008The crowdtesting application expires.16000009An ability cannot be started or stopped in Wukong mode.16000010The call with the continuation flag is forbidden.16000011The context does not exist.16000012The application is controlled.16000013The application is controlled by EDM.16000018The application is not allow jumping to other applications.16000019Can not match any component.16000050Internal error.16000053The ability is not on the top of the UI.16000055Installation-free timed out.16000069The extension cannot start the third party application.16000070The extension cannot start the service.16200001The caller has been released.16000073The app clone index is invalid. 示例:
import { UIExtensionAbility, Want, StartOptions } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIExtensionAbility {
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}`);
    }
}
} UIExtensionContext.startAbilityForResult

startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void
启动一个Ability。使用callback异步回调。Ability被启动后,有如下环境:


[*]正常环境下可通过调用terminateSelfWithResult接口使之停止而且返回结果给调用方。
[*]非常环境下好比杀死Ability会返回非常信息给调用方, 非常信息中resultCode为-1。
[*]如果被启动的Ability模式是单实例模式, 不同应用多次调用该接口启动这个Ability,当这个Ability调用terminateSelfWithResult接口使之停止时,只将正常结果返回给最后一个调用方, 别的调用方返回非常信息, 非常信息中resultCode为-1。
   说明
组件启动规则详见:组件启动规则(Stage模子)。
系统能力:SystemCapability.Ability.AbilityRuntime.Core
参数:
参数名类型必填说明wantWant是启动Ability的want信息。callbackAsyncCallback<AbilityResult>是回调函数,返回启动Ability的结果。 错误码:
以下错误码具体先容。
错误码ID错误信息201The application does not have permission to call the interface.401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.16000001The specified ability does not exist.16000002Incorrect ability type.16000004Can not start invisible component.16000005The specified process does not have the permission.16000006Cross-user operations are not allowed.16000008The crowdtesting application expires.16000009An ability cannot be started or stopped in Wukong mode.16000010The call with the continuation flag is forbidden.16000011The context does not exist.16000012The application is controlled.16000013The application is controlled by EDM.16000018The application is not allow jumping to other applications.16000019Can not match any component.16000050Internal error.16000053The ability is not on the top of the UI.16000055Installation-free timed out.16000069The extension cannot start the third party application.16000070The extension cannot start the service.16200001The caller has been released.16000073The app clone index is invalid. 示例:
import { UIExtensionAbility, Want, common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

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

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

startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>): void
启动一个Ability。使用callback异步回调。Ability被启动后,有如下环境:


[*]正常环境下可通过调用terminateSelfWithResult接口使之停止而且返回结果给调用方。
[*]非常环境下好比杀死Ability会返回非常信息给调用方,非常信息中resultCode为-1。
[*]如果被启动的Ability模式是单实例模式, 不同应用多次调用该接口启动这个Ability,当这个Ability调用terminateSelfWithResult接口使之停止时,只将正常结果返回给最后一个调用方,别的调用方返回非常信息, 非常信息中resultCode为-1。
   说明
组件启动规则详见:组件启动规则(Stage模子)。
系统能力:SystemCapability.Ability.AbilityRuntime.Core
参数:
参数名类型必填说明wantWant是启动Ability的want信息。optionsStartOptions是启动Ability所携带的参数。callbackAsyncCallback<AbilityResult>是回调函数,返回启动Ability的结果。 错误码:
以下错误码具体先容。
错误码ID错误信息201The application does not have permission to call the interface.401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.16000001The specified ability does not exist.16000004Can not start invisible component.16000005The specified process does not have the permission.16000006Cross-user operations are not allowed.16000008The crowdtesting application expires.16000009An ability cannot be started or stopped in Wukong mode.16000011The context does not exist.16000012The application is controlled.16000013The application is controlled by EDM.16000018The application is not allow jumping to other applications.16000019Can not match any component.16000050Internal error.16000053The ability is not on the top of the UI.16000055Installation-free timed out.16000069The extension cannot start the third party application.16000070The extension cannot start the service.16200001The caller has been released.16000073The app clone index is invalid. 示例:
import { UIExtensionAbility, Want, common, StartOptions } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIExtensionAbility {
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}`);
    }
}
} UIExtensionContext.startAbilityForResult

startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityResult>
启动一个Ability。使用Promise异步回调。Ability被启动后,有如下环境:


[*]正常环境下可通过调用terminateSelfWithResult接口使之停止而且返回结果给调用方。
[*]非常环境下好比杀死Ability会返回非常信息给调用方, 非常信息中resultCode为-1。
[*]如果被启动的Ability模式是单实例模式, 不同应用多次调用该接口启动这个Ability,当这个Ability调用terminateSelfWithResult接口使之停止时,只将正常结果返回给最后一个调用方, 别的调用方返回非常信息, 非常信息中resultCode为-1。
   说明
组件启动规则详见:组件启动规则(Stage模子)。
系统能力:SystemCapability.Ability.AbilityRuntime.Core
参数:
参数名类型必填说明wantWant是启动Ability的want信息。optionsStartOptions否启动Ability所携带的参数。 返回值:
类型说明Promise<AbilityResult>Promise对象,返回启动Ability的结果。 错误码:
以下错误码具体先容。
错误码ID错误信息201The application does not have permission to call the interface.401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.16000001The specified ability does not exist.16000002Incorrect ability type.16000004Can not start invisible component.16000005The specified process does not have the permission.16000006Cross-user operations are not allowed.16000008The crowdtesting application expires.16000009An ability cannot be started or stopped in Wukong mode.16000010The call with the continuation flag is forbidden.16000011The context does not exist.16000012The application is controlled.16000013The application is controlled by EDM.16000018The application is not allow jumping to other applications.16000019Can not match any component.16000050Internal error.16000053The ability is not on the top of the UI.16000055Installation-free timed out.16000069The extension cannot start the third party application.16000070The extension cannot start the service.16200001The caller has been released.16000073The app clone index is invalid. 示例:
import { UIExtensionAbility, Want, common, StartOptions } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIExtensionAbility {
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}`);
}
}
} UIExtensionContext.connectServiceExtensionAbility

connectServiceExtensionAbility(want: Want, options: ConnectOptions): number
将当前Ability毗连到一个ServiceExtensionAbility。
   说明
组件启动规则详见:组件启动规则(Stage模子)。
系统能力:SystemCapability.Ability.AbilityRuntime.Core
参数:
参数名类型必填说明wantWant是毗连ServiceExtensionAbility的want信息。optionsConnectOptions是与ServiceExtensionAbility建立毗连后回调函数的实例。 返回值:
类型说明number返回Ability毗连的结果code。 错误码:
以下错误码具体先容。
错误码ID错误信息201The application does not have permission to call the interface.401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.16000001The specified ability does not exist.16000002Incorrect ability type.16000004Can not start invisible component.16000005The specified process does not have the permission.16000006Cross-user operations are not allowed.16000008The crowdtesting application expires.16000011The context does not exist.16000050Internal error.16000053The ability is not on the top of the UI.16000055Installation-free timed out.16000070The extension cannot start the service. 示例:
import { UIExtensionAbility, Want, common } from '@kit.AbilityKit';
import { rpc } from '@kit.IPCKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIExtensionAbility {
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}`);
}
}
} UIExtensionContext.disconnectServiceExtensionAbility

disconnectServiceExtensionAbility(connection: number): Promise<void>
断开与ServiceExtensionAbility的毗连,断开毗连之后需要将毗连成功时返回的remote对象置空。使用Promise异步回调。
系统能力:SystemCapability.Ability.AbilityRuntime.Core
参数:
参数名类型必填说明connectionnumber是毗连的ServiceExtensionAbility的数字代码,即connectServiceExtensionAbility返回的connectionId。 返回值:
类型说明Promise<void>Promise对象。无返回结果的Promise对象。 错误码:
以下错误码具体先容。
错误码ID错误信息401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.16000011The context does not exist.16000050Internal error. 示例:
import { UIExtensionAbility } from '@kit.AbilityKit';
import { rpc } from '@kit.IPCKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIExtensionAbility {
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}`);
}
}
} UIExtensionContext.disconnectServiceExtensionAbility

disconnectServiceExtensionAbility(connection: number, callback: AsyncCallback<void>): void
断开与ServiceExtensionAbility的毗连,断开毗连之后需要将毗连成功时返回的remote对象置空。使用callback异步回调。
系统能力:SystemCapability.Ability.AbilityRuntime.Core
参数:
参数名类型必填说明connectionnumber是毗连的ServiceExtensionAbility的数字代码,即connectServiceExtensionAbility返回的connectionId。callbackAsyncCallback<void>是回调函数。当断开与ServiceExtensionAbility的毗连成功,err为undefined,否则为错误对象。 错误码:
以下错误码具体先容。
错误码ID错误信息401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.16000011The context does not exist.16000050Internal error. 示例:
import { UIExtensionAbility } from '@kit.AbilityKit';
import { rpc } from '@kit.IPCKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIExtensionAbility {
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}`);
}
}
} UIExtensionContext.terminateSelf12+

terminateSelf(callback: AsyncCallback<void>): void
停止UIExtensionContext对应的窗口界面对象。使用callback异步回调。
系统能力:SystemCapability.Ability.AbilityRuntime.Core
参数:
参数名类型必填说明callbackAsyncCallback<void>是回调函数。当停止UIExtensionContext对应的窗口界面对象成功,err为undefined,否则为错误对象。 错误码:
以下错误码具体先容。
错误码ID错误信息401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 示例:
import { UIExtensionAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIExtensionAbility {
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}`);
    }
}
} UIExtensionContext.terminateSelf12+

terminateSelf(): Promise<void>
停止UIExtensionContext对应的窗口界面对象。使用Promise异步回调。
系统能力:SystemCapability.Ability.AbilityRuntime.Core
返回值:
类型说明Promise<void>Promise对象。无返回结果的Promise对象。 示例:
import { UIExtensionAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIExtensionAbility {
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}`);
}
}
} UIExtensionContext.terminateSelfWithResult12+

terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>): void
停止UIExtensionContext对应的窗口界面对象,并将结果返回给UIExtensionComponent控件。使用callback异步回调。
系统能力:SystemCapability.Ability.AbilityRuntime.Core
参数:
参数名类型必填说明parameterAbilityResult是返回给UIExtensionComponent控件的信息。callbackAsyncCallback<void>是回调函数。当停止成功,err为undefined,否则为错误对象。 错误码:
以下错误码具体先容。
错误码ID错误信息401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 示例:
import { UIExtensionAbility, Want, common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIExtensionAbility {
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}`);
}
}
} UIExtensionContext.terminateSelfWithResult12+

terminateSelfWithResult(parameter: AbilityResult): Promise<void>
停止UIExtensionContext对应的窗口界面对象,并将结果返回给UIExtensionComponent控件。使用Promise异步回调。
系统能力:SystemCapability.Ability.AbilityRuntime.Core
参数:
参数名类型必填说明parameterAbilityResult是返回给UIExtensionComponent控件的信息。 返回值:
类型说明Promise<void>Promise对象。无返回结果的Promise对象。 错误码:
以下错误码具体先容。
错误码ID错误信息401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. import { UIExtensionAbility, Want, common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIExtensionAbility {
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}`);
    }
}
} UIExtensionContext.reportDrawnCompleted12+

reportDrawnCompleted(callback: AsyncCallback<void>): void
当页面加载完成(onSessionCreate成功)时,为开发者提供打点功能。使用callback异步回调。
系统能力:SystemCapability.Ability.AbilityRuntime.Core
参数:
参数名类型必填说明callbackAsyncCallback<void>是回调函数。当打点成功,err为undefined,否则为错误对象。 错误码:
以下错误码具体先容。
错误码ID错误信息16000011The context does not exist.16000050Internal error. 示例:
import { UIExtensionAbility, Want, UIExtensionContentSession } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

const TAG: string = ' UIExtAbility';

export default class UIExtAbility extends UIExtensionAbility {
onSessionCreate(want: Want, session: UIExtensionContentSession) {
    console.info(TAG, `onSessionCreate, want: ${JSON.stringify(want)}`);
    let data: Record<string, UIExtensionContentSession> = {
      'session': session
    };
    let storage: LocalStorage = new LocalStorage(data);
    session.loadContent('pages/extension', storage);
    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}`);
    }
}
} UIExtensionContext.openAtomicService12+

openAtomicService(appId: string, options?: AtomicServiceOptions): Promise<AbilityResult>
跳出式启动EmbeddableUIAbility,并返回结果。使用Promise异步回调。
分为以下几种环境:


[*]正常环境下可通过调用terminateSelfWithResult接口使之停止而且返回结果给调用方。
[*]非常环境下好比杀死EmbeddableUIAbility会返回非常信息给调用方,非常信息中resultCode为-1。
[*]如果不同应用多次调用该接口启动同一个EmbeddableUIAbility,当这个EmbeddableUIAbility调用terminateSelfWithResult接口使之停止时,只将正常结果返回给最后一个调用方, 别的调用方返回非常信息,非常信息中resultCode为-1。
   说明
组件启动规则详见:组件启动规则(Stage模子)。
系统能力:SystemCapability.Ability.AbilityRuntime.Core
参数:
参数名类型必填说明appIdstring是应用的唯一标识,由云端统一分配。optionsAtomicServiceOptions否跳出式启动元服务所携带的参数。 返回值:
类型说明Promise<AbilityResult>Promise对象。返回AbilityResult对象。 错误码:
以下错误码具体先容。
错误码ID错误信息401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.16000002Incorrect ability type.16000003The appId does not exist.16000004Can not start invisible component.16000011The context does not exist.16000012The application is controlled.16000050Internal error.16000069The extension cannot start the third party application.16200001The caller has been released. 示例:
import { UIExtensionAbility, common, AtomicServiceOptions } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIExtensionAbility {
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}`);
}
}
} UIExtensionContext.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参数。
传入的参数不正当时,如未设置必选参数或link字符串不是标准格式的URL,接口会直接抛出非常。参数校验通过,拉起目的方时出现的错误通过promise返回错误信息。
   说明
组件启动规则详见:组件启动规则(Stage模子)。
系统能力:SystemCapability.Ability.AbilityRuntime.Core
参数:
参数名类型必填说明linkstring是指示要打开的标准格式URL。optionsOpenLinkOptions否打开URL的选项参数。callbackAsyncCallback<AbilityResult>否执行结果回调函数。 返回值:
类型说明Promise<void>Promise对象。无返回结果的Promise对象。 错误码:
以下错误码具体先容。
错误码ID错误信息201The application does not have permission to call the interface.401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.16000001The specified ability does not exist.16000002Incorrect ability type.16000004Can not start invisible component.16000005The specified process does not have the permission.16000006Cross-user operations are not allowed.16000008The crowdtesting application expires.16000009An ability cannot be started or stopped in Wukong mode.16000010The call with the continuation flag is forbidden.16000011The context does not exist.16000012The application is controlled.16000013The application is controlled by EDM.16000019Can not match any component.16000069The extension cannot start the third party application.16200001The caller has been released.16000053The ability is not on the top of the UI. 示例:
import { UIExtensionAbility, Want, UIExtensionContentSession, OpenLinkOptions } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

function log(info: string) {
console.error(`MyUIExtension:: ${JSON.stringify(info)}`);
}

export default class UIExtAbility extends UIExtensionAbility {
onCreate() {
log(`UIExtAbility onCreate`);
}

onForeground() {
log(`UIExtAbility onForeground`);
}

onBackground() {
log(`UIExtAbility onBackground`);
}

onDestroy() {
log(`UIExtAbility onDestroy`);
}

onSessionCreate(want: Want, session: UIExtensionContentSession) {
log(`UIExtAbility onSessionCreate`);
log(`UIExtAbility onSessionCreate, want: ${JSON.stringify(want)}`);
let record: Record<string, UIExtensionContentSession> = {
'session': session
};
let storage: LocalStorage = new LocalStorage(record);
session.loadContent('pages/UIExtensionIndex', storage);

let link: string = 'https://www.example.com';
let openLinkOptions: OpenLinkOptions = {
appLinkingOnly: true
};
try {
this.context.openLink(
link,
openLinkOptions,
(err, result) => {
log(`openLink callback error.code: ${JSON.stringify(err)}`);
log(`openLink callback result: ${JSON.stringify(result.resultCode)}`);
log(`openLink callback result data: ${JSON.stringify(result.want)}`);
}
).then(() => {
log(`open link success.`);
}).catch((err: BusinessError) => {
log(`open link failed, errCode ${JSON.stringify(err.code)}`);
});
}
catch (e) {
log(`exception occured, errCode ${JSON.stringify(e.code)}`);
}

}

onSessionDestroy(session: UIExtensionContentSession) {
log(`UIExtAbility onSessionDestroy`);
}
}
  https://i-blog.csdnimg.cn/direct/06f1cc0b375e455296ba10c75a2b64a3.png


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: 鸿蒙5.0开发进阶:ArkTS API-UIExtensionContext