前言:鸿蒙权限请求也是必不可少的,安卓如果在清单文件中申请了,就可以手动打开权限,但是鸿蒙却有一丢丢不一样,权限管控的很严格,如果你的应用不符合一些权限申请的范围,就会被告知为高危权限申请,不能上架的,所以鸿蒙申请权限要看你的应用类型去申请相对应的权限。
一:在 entry 里面的 module.json 声明所需要申请的权限,在 requestPermissions 标签下声明:
二:以下是封装好的工具类
import { abilityAccessCtrl, bundleManager, common, Permissions } from '@kit.AbilityKit';class PermissionManager {// 检查是否授权checkPermissions(permissions: Permissions[]) {// ['ohos.permission.READ_CONTACTS', 'ohos.permission.WRITE_CONTACTS']// 程序访问控制管理const atManager = abilityAccessCtrl.createAtManager();const bundleInfo = bundleManager.getBundleInfoForSelfSync(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION)// 提取 tokenID 标识const tokenID = bundleInfo.appInfo.accessTokenId;//检查是否已授权const grantStatusList = permissions.map(item => atManager.checkAccessTokenSync(tokenID, item))return grantStatusList.every(value => value === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED)}// 动态申请授权(首次弹窗申请)async requestPermissions(permissions: Permissions[]) {const atManager = abilityAccessCtrl.createAtManager()//弹起弹窗const permissionRequestResult = await atManager.requestPermissionsFromUser(getContext(), permissions)//检查权限的结果const res = permissionRequestResult.authResults.every(value => value === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED)return res === true ? Promise.resolve(true) : Promise.reject(false)}// 打开系统设置的权限管理页(处理授权结果)openPermissionSettingsPage() {const context = getContext() as common.UIAbilityContext// 获取包信息const bundleInfo = bundleManager.getBundleInfoForSelfSync(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION)context.startAbility({bundleName: 'com.huawei.hmos.settings',abilityName: 'com.huawei.hmos.settings.MainAbility',uri: 'application_info_entry',parameters: {pushParams: bundleInfo.name}})} }export const permissionManager = new PermissionManager()