```
import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
import bundleManager from '@ohos.bundle.bundleManager';
import common from '@ohos.app.ability.common';
```
获取访问控制模块对象实例:
```
let atManager = abilityAccessCtrl.createAtManager();
```
编写如下方法(这里我使用的是异步函数):
```
export async function checkAccessTokenID(permission: Array<ermissions>) {
// 获取应用程序的accessTokenID
let tokenId: number;
let grantStatus: Array<abilityAccessCtrl.GrantStatus> = []
try {
let bundleInfo: bundleManager.BundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo;
tokenId = appInfo.accessTokenId;
} catch (err) {
console.error(`getBundleInfoForSelf failed, code is ${err.code}, message is ${err.message}`);
}
// 校验应用是否被授予权限,若申请多个权限,建议循环检查多个权限
for (let index = 0;index < permission.length; index++) {
try {
grantStatus.push(await atManager.checkAccessToken(tokenId, permission[index]))
} catch (err) {
console.error(`checkAccessToken failed, code is ${err.code}, message is ${err.message}`);
}
}
return grantStatus;
}
export async function checkPermission(context: common.UIAbilityContext, permissions: Array<ermissions>) {
let grantStatus: Array<abilityAccessCtrl.GrantStatus> = await checkAccessTokenID(permissions)
for (let i = 0; i < grantStatus.length; i++) {
if (grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
console.info(`${permissions.toString()} 已授权`)
} else {
//申请权限
console.info('开始向用户申请权限')
requestPermissionFromUser(context, permissions)
}
}
}
export async function requestPermissionFromUser(context: common.UIAbilityContext, permissions: Array<ermissions>) {
// requestPermissionsFromUser会判断权限的授权状态来决定是否唤起弹窗
atManager.requestPermissionsFromUser(context, permissions).then((data) => {
let grantStatus: Array<number> = data.authResults
let length: number = grantStatus.length
for (let i = 0;i < length; i++) {
if (grantStatus === 0) {
// 用户授权,可以继续访问目标操作
console.info(`${permissions.toString()} 权限申请成功`)
} else {
// 用户拒绝授权,提示用户必须授权才能访问当前页面的功能,并引导用户到系统设置中打开相应的权限
console.info(`${permissions.toString()} 权限申请被用户拒绝`)
}
}
// 授权成功
})
}
```