From cb6fe1576346cf9178d8608440c17f053b4bef31 Mon Sep 17 00:00:00 2001 From: zhouyan Date: Wed, 30 Aug 2023 14:43:59 +0800 Subject: [PATCH] =?UTF-8?q?=E8=AE=BF=E9=97=AE=E6=8E=A7=E5=88=B6permissionr?= =?UTF-8?q?equestresult.md=E5=91=8A=E8=AD=A6=E6=95=B4=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: zhouyan Change-Id: Iaaa670feab210293cd181e57674b61b905ea455b --- .../apis/js-apis-permissionrequestresult.md | 54 ++++++++++++++++++- 1 file changed, 52 insertions(+), 2 deletions(-) diff --git a/zh-cn/application-dev/reference/apis/js-apis-permissionrequestresult.md b/zh-cn/application-dev/reference/apis/js-apis-permissionrequestresult.md index 948eb9a341..25a6f0c8a0 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-permissionrequestresult.md +++ b/zh-cn/application-dev/reference/apis/js-apis-permissionrequestresult.md @@ -21,15 +21,65 @@ 通过atManager实例来获取。 **示例:** + +ArkTS语法不支持直接使用globalThis,需要通过一个单例的map来做中转。开发者需要: + +a. 在EntryAbility.ets中导入构建的单例对象GlobalThis。 + ```typescript + import { GlobalThis } from '../utils/globalThis'; // 需要根据globalThis.ets的路径自行适配 + ``` +b. 在onCreate中添加: + ```typescript + GlobalThis.getInstance().setContext('context', this.context); + ``` + +> **说明:** +> +> 由于在ts中引入ets文件会有告警提示,需要将EntryAbility.ts的文件后缀修改为EntryAbility.ets,并在module.json5中同步修改。 + +**globalThis.ets示例代码如下:** +```typescript +import common from '@ohos.app.ability.common'; + +// 构造单例对象 +export class GlobalThis { + private constructor() {} + private static instance: GlobalThis; + private _uiContexts = new Map(); + + public static getInstance(): GlobalThis { + if (!GlobalThis.instance) { + GlobalThis.instance = new GlobalThis(); + } + return GlobalThis.instance; + } + + getContext(key: string): common.UIAbilityContext | undefined { + return this._uiContexts.get(key); + } + + setContext(key: string, value: common.UIAbilityContext): void { + this._uiContexts.set(key, value); + } + + // 其他需要传递的内容依此扩展 +} +``` + ```ts +import { BusinessError } from '@ohos.base'; import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +import common from '@ohos.app.ability.common'; +import { GlobalThis } from '../utils/globalThis'; + let atManager = abilityAccessCtrl.createAtManager(); try { - atManager.requestPermissionsFromUser(this.context, ["ohos.permission.CAMERA"]).then((data) => { + let context: common.UIAbilityContext = GlobalThis.getInstance().getContext('context'); + atManager.requestPermissionsFromUser(context, ["ohos.permission.CAMERA"]).then((data) => { console.info("data:" + JSON.stringify(data)); console.info("data permissions:" + data.permissions); console.info("data authResults:" + data.authResults); - }).catch((err) => { + }).catch((err: BusinessError) => { console.info("data:" + JSON.stringify(err)); }) } catch(err) { -- GitLab