当前位置: 首页 > backend >正文

鸿蒙NEXT开发权限工具类(申请授权相关)(ArkTs)

import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
import { bundleManager, common, PermissionRequestResult } from '@kit.AbilityKit';
import { BusinessError } from '@ohos.base';
import { ToastUtil } from './ToastUtil';/*** 权限工具类(申请授权相关)* author: CSDN-鸿蒙布道师* since: 2025/04/22*/
export class PermissionUtil {/*** 获取应用上下文*/private static getContext(): common.UIAbilityContext {return getContext() as common.UIAbilityContext;}/*** 创建权限管理器实例*/private static createAtManager(): abilityAccessCtrl.AtManager {return abilityAccessCtrl.createAtManager();}/*** 校验当前是否已经授权* @param permission 待判断的权限* @returns 已授权 true,未授权 false*/static async checkPermissions(permission: Permissions): Promise<boolean> {const grantStatus = await PermissionUtil.checkAccessToken(permission);return grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED;}/*** 校验并申请权限* @param permissions 需要授权的权限* @returns true 表示授权成功,false 表示用户拒绝授权*/static async checkAndRequestPermissions(permissions: Permissions | Array<Permissions>): Promise<boolean> {const isGranted = await PermissionUtil.checkPermissions(permissions as Permissions);if (isGranted) {return true;}return PermissionUtil.requestPermissionsEasy(permissions);}/*** 申请权限(支持单个或多个权限组合)* @param permissions 需要授权的权限* @returns true 表示授权成功,false 表示用户拒绝授权*/static async requestPermissions(permissions: Permissions | Array<Permissions>): Promise<boolean> {const atManager = PermissionUtil.createAtManager();const context = PermissionUtil.getContext();const permissionArray = Array.isArray(permissions) ? [...permissions] : [permissions];try {const result = await atManager.requestPermissionsFromUser(context, permissionArray);return PermissionUtil.isPermissionGranted(result);} catch (error) {PermissionUtil.handleError(error, '申请权限失败');return false;}}/*** 申请权限并提供二次授权机会(推荐使用此方法)* @param permissions 需要授权的权限* @returns true 表示授权成功,false 表示用户拒绝授权*/static async requestPermissionsEasy(permissions: Permissions | Array<Permissions>): Promise<boolean> {const granted = await PermissionUtil.requestPermissions(permissions);if (granted) {return true;}return PermissionUtil.requestPermissionOnSettingEasy(Array.isArray(permissions) ? [...permissions] : [permissions]);}/*** 二次向用户申请权限(适用于单个权限或读写权限组)* @param permissions 需要授权的权限集合* @returns true 表示授权成功,false 表示用户拒绝授权*/static async requestPermissionOnSetting(permissions: Permissions | Array<Permissions>): Promise<boolean> {const atManager = PermissionUtil.createAtManager();const context = PermissionUtil.getContext();const permissionArray = Array.isArray(permissions) ? [...permissions] : [permissions];try {const result = await atManager.requestPermissionOnSetting(context, permissionArray);return PermissionUtil.isPermissionGranted(result);} catch (error) {PermissionUtil.handleError(error, '二次申请权限失败');return false;}}/*** 二次向用户申请权限(适用于多个权限)* @param permissions 需要授权的权限集合* @returns true 表示授权成功,false 表示用户拒绝授权*/static async requestPermissionOnSettingEasy(permissions: Array<Permissions>): Promise<boolean> {for (const permission of permissions) {const isGranted = await PermissionUtil.checkPermissions(permission);if (!isGranted) {const granted = await PermissionUtil.requestPermissionOnSetting(permission);if (!granted) {return false;}}}return true;}/*** 检查权限是否已授予* @param data 授权结果* @returns true 表示所有权限均已授予,false 表示存在未授予权限*/private static isPermissionGranted(data: PermissionRequestResult | Array<number>): boolean {const authResults = Array.isArray(data) ? data : data.authResults;return authResults.every((status) => status === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED);}/*** 校验访问令牌是否已授权* @param permission 待检查权限* @returns 授权状态*/private static async checkAccessToken(permission: Permissions): Promise<abilityAccessCtrl.GrantStatus> {const atManager = PermissionUtil.createAtManager();let tokenId = 0;try {const bundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);tokenId = bundleInfo.appInfo.accessTokenId;} catch (error) {PermissionUtil.handleError(error, '获取应用信息失败');return abilityAccessCtrl.GrantStatus.PERMISSION_DENIED;}try {return await atManager.checkAccessToken(tokenId, permission);} catch (error) {PermissionUtil.handleError(error, '校验授权信息失败');return abilityAccessCtrl.GrantStatus.PERMISSION_DENIED;}}/*** 错误处理方法* @param error 错误对象(明确指定为 BusinessError 类型)* @param message 提示信息*/private static handleError(error: BusinessError, message: string): void {console.error(`${message}: ${error.message}`);ToastUtil.showToast(`${message}: ${error.message}`);}
}代码如下:
import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
import { bundleManager, common, PermissionRequestResult } from '@kit.AbilityKit';
import { BusinessError } from '@ohos.base';
import { ToastUtil } from './ToastUtil';/*** 权限工具类(申请授权相关)* author: CSDN-鸿蒙布道师* since: 2025/04/22*/
export class PermissionUtil {/*** 获取应用上下文*/private static getContext(): common.UIAbilityContext {return getContext() as common.UIAbilityContext;}/*** 创建权限管理器实例*/private static createAtManager(): abilityAccessCtrl.AtManager {return abilityAccessCtrl.createAtManager();}/*** 校验当前是否已经授权* @param permission 待判断的权限* @returns 已授权 true,未授权 false*/static async checkPermissions(permission: Permissions): Promise<boolean> {const grantStatus = await PermissionUtil.checkAccessToken(permission);return grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED;}/*** 校验并申请权限* @param permissions 需要授权的权限* @returns true 表示授权成功,false 表示用户拒绝授权*/static async checkAndRequestPermissions(permissions: Permissions | Array<Permissions>): Promise<boolean> {const isGranted = await PermissionUtil.checkPermissions(permissions as Permissions);if (isGranted) {return true;}return PermissionUtil.requestPermissionsEasy(permissions);}/*** 申请权限(支持单个或多个权限组合)* @param permissions 需要授权的权限* @returns true 表示授权成功,false 表示用户拒绝授权*/static async requestPermissions(permissions: Permissions | Array<Permissions>): Promise<boolean> {const atManager = PermissionUtil.createAtManager();const context = PermissionUtil.getContext();const permissionArray = Array.isArray(permissions) ? [...permissions] : [permissions];try {const result = await atManager.requestPermissionsFromUser(context, permissionArray);return PermissionUtil.isPermissionGranted(result);} catch (error) {PermissionUtil.handleError(error, '申请权限失败');return false;}}/*** 申请权限并提供二次授权机会(推荐使用此方法)* @param permissions 需要授权的权限* @returns true 表示授权成功,false 表示用户拒绝授权*/static async requestPermissionsEasy(permissions: Permissions | Array<Permissions>): Promise<boolean> {const granted = await PermissionUtil.requestPermissions(permissions);if (granted) {return true;}return PermissionUtil.requestPermissionOnSettingEasy(Array.isArray(permissions) ? [...permissions] : [permissions]);}/*** 二次向用户申请权限(适用于单个权限或读写权限组)* @param permissions 需要授权的权限集合* @returns true 表示授权成功,false 表示用户拒绝授权*/static async requestPermissionOnSetting(permissions: Permissions | Array<Permissions>): Promise<boolean> {const atManager = PermissionUtil.createAtManager();const context = PermissionUtil.getContext();const permissionArray = Array.isArray(permissions) ? [...permissions] : [permissions];try {const result = await atManager.requestPermissionOnSetting(context, permissionArray);return PermissionUtil.isPermissionGranted(result);} catch (error) {PermissionUtil.handleError(error, '二次申请权限失败');return false;}}/*** 二次向用户申请权限(适用于多个权限)* @param permissions 需要授权的权限集合* @returns true 表示授权成功,false 表示用户拒绝授权*/static async requestPermissionOnSettingEasy(permissions: Array<Permissions>): Promise<boolean> {for (const permission of permissions) {const isGranted = await PermissionUtil.checkPermissions(permission);if (!isGranted) {const granted = await PermissionUtil.requestPermissionOnSetting(permission);if (!granted) {return false;}}}return true;}/*** 检查权限是否已授予* @param data 授权结果* @returns true 表示所有权限均已授予,false 表示存在未授予权限*/private static isPermissionGranted(data: PermissionRequestResult | Array<number>): boolean {const authResults = Array.isArray(data) ? data : data.authResults;return authResults.every((status) => status === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED);}/*** 校验访问令牌是否已授权* @param permission 待检查权限* @returns 授权状态*/private static async checkAccessToken(permission: Permissions): Promise<abilityAccessCtrl.GrantStatus> {const atManager = PermissionUtil.createAtManager();let tokenId = 0;try {const bundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);tokenId = bundleInfo.appInfo.accessTokenId;} catch (error) {PermissionUtil.handleError(error, '获取应用信息失败');return abilityAccessCtrl.GrantStatus.PERMISSION_DENIED;}try {return await atManager.checkAccessToken(tokenId, permission);} catch (error) {PermissionUtil.handleError(error, '校验授权信息失败');return abilityAccessCtrl.GrantStatus.PERMISSION_DENIED;}}/*** 错误处理方法* @param error 错误对象(明确指定为 BusinessError 类型)* @param message 提示信息*/private static handleError(error: BusinessError, message: string): void {console.error(`${message}: ${error.message}`);ToastUtil.showToast(`${message}: ${error.message}`);}
}

http://www.xdnf.cn/news/1209.html

相关文章:

  • 如何给pip命令国内镜像源
  • Python 简介与入门
  • 轻量级别的htpp客户端--Forest
  • “多模态SCA+DevSecOps+SBOM风险情报预警 “数字供应链安全最佳管理体系!悬镜安全如何用AI守护万亿数字中国?
  • KUKA机器人KR 3 D1200 HM介绍
  • JDK版本与Spring Boot版本之间对应关系
  • 【RK3588 嵌入式图形编程】-SDL2-扫雷游戏-放置标记
  • day3 打卡训练营
  • 多表查询之嵌套查询
  • 深圳有哪些有名的PCB设计的培训班
  • 4.LinkedList的模拟实现:
  • 实践项目开发-hbmV4V20250407-Taro项目构建优化
  • 瓦瑟斯坦差分隐私中命题7对总变差TV的应用
  • vue3 组件传参
  • 2025软件测试常用面试问题及参考答案(附文档)
  • 计算机组成与体系结构:缓存(Cache)
  • TCP和UDP
  • Windows 同步-Windows 单向链表和互锁链表
  • Typebot:开源、强大、可自托管的聊天机器人构建工具
  • DES、3DES、SM4 加密算法简介
  • 查看Spring Boot项目所有配置信息的几种方法,包括 Actuator端点、日志输出、代码级获取 等方式,附带详细步骤和示例
  • 第十五届蓝桥杯 2024 C/C++组 下一次相遇
  • Uniapp:navigator(页面跳转)
  • 【飞渡科技数字孪生虚拟环境部署与集成教程 - CloudMaster实战指南】
  • KDD Cup 2017 数据集分析
  • G1 人形机器人软件系统架构与 Python SDK
  • BeeWorks:专业的企业Im即时通讯平台
  • PyTorch深度学习框架60天进阶学习计划 - 第48天:移动端模型优化(二)
  • flutter 插件收集
  • 15openlayers获取VectorLayer上的数据