配置声明权限
在module.json5配置文件中声明权限。不论是system_grant还是user_grant类型都需要声明权限,否则应用将无法获得授权。
{"module" : {// ..."requestPermissions":[{"name": "ohos.permission.DISCOVER_BLUETOOTH",//权限名称。"reason":"$string:need_ble",//描述申请权限的原因。 当申请的权限为user_grant权限时,此字段必填。"usedScene": { //描述权限使用的场景和时机。当申请的权限为user_grant权限时,此字段必填。"abilities": [ //标识需要使用到该权限的Ability,标签为数组形式"EntryAbility"],"when": "always"//标识权限使用的时机 - inuse:表示为仅允许前台使用。- always:表示前后台都可使用。}},{"name": "ohos.permission.LOCATION","reason":"$string:need_ble","usedScene": {"abilities": ["EntryAbility"],"when": "always"}},{"name": "ohos.permission.APPROXIMATELY_LOCATION","reason":"$string:need_ble","usedScene": {"abilities": ["EntryAbility"],"when": "always"}}]}
}
权限校验(可略)
- 获取调用者的身份标识:tokenId。
- 待校验的权限名:ohos.permission.xxx。
- 使用checkAccessToken接口对当前调用者进行权限校验。
class RequestPermission {async checkAccessToken(permissions: Array<Permissions>/*权限名*/): Promise<boolean> {//获取调用者的身份标识let callerTokenId = rpc.IPCSkeleton.getCallingTokenId();console.log("RequestPermission RpcServer: getCallingTokenId result: " + callerTokenId);var atManager = abilityAccessCtrl.createAtManager();try {const promises = permissions.map( (permission, index) => {//进行权限校验return atManager.checkAccessToken(callerTokenId, permission).then((data) => {console.log(`RequestPermission checkAccessToken success, data->${JSON.stringify(data)}`);if( index >= permissions.length - 1 ) {return true;}}).catch((err) => {console.log(`RequestPermission checkAccessToken fail, err->${JSON.stringify(err)}`);return false;});});const results = await Promise.all(promises);// 检查所有 Promise 的结果return results.every(result => result);} catch(err) {console.log(`RequestPermission catch err->${JSON.stringify(err)}`);return false;}} }export default new RequestPermission()
例:有 'ohos.permission.APPROXIMATELY_LOCATION', 'ohos.permission.LOCATION', 'ohos.permission.CAMERA'三个权限 已授权前两个调用结果如下
RequestPermission.checkAccessToken(permissions).then(results => {console.log('RequestPermission checked successfully:', results);}).catch(error => {console.error('RequestPermission check failed:', error);});打印如下I 0FEFE/JsApp: RequestPermission RpcServer: getCallingTokenId result: 537654415I 0FEFE/JsApp: RequestPermission checkAccessToken success, data->-1I 0FEFE/JsApp: RequestPermission checkAccessToken success, data->-1I 0FEFE/JsApp: RequestPermission checked successfully: false
向用户申请权限
class RequestPermission {async reqPermissionsFromUser(permissions: Array<Permissions>): Promise<boolean> {let context = getContext(this) as common.UIAbilityContext;let atManager = abilityAccessCtrl.createAtManager();try {const data = await atManager.requestPermissionsFromUser(context, permissions);let grantStatus: Array<number> = data.authResults;let length: number = grantStatus.length;for (let i = 0; i < length; i++) {if (grantStatus[i] !== 0) {// 如果有任何一个权限没有被授权,立即返回 falsereturn false;}}// 所有权限都被授权,返回 truereturn true;} catch (err) {console.error(`RequestPermission requestPermissionsFromUser failed, code is ${err.code}, message is ${err.message}`);// 如果发生异常,也返回 falsereturn false;}}
}
回调版
import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
import common from '@ohos.app.ability.common';
import rpc from '@ohos.rpc';class RequestPermission {/**** @param permissions 需要请求的权限数组* @param callback 权限结果 true/false*/reqPermissionsFromUser(permissions: Array<Permissions>, callback:(result:boolean)=>void) {let context = getContext(this) as common.UIAbilityContext;let atManager = abilityAccessCtrl.createAtManager();try {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[i] !== 0) {callback(false);}}callback(true);})} catch (err) {console.error(`requestPermissionsFromUser failed, code is ${err.code}, message is ${err.message}`);callback(false);}}/**** @param permissions 需要检查的权限数组* @param callback*/checkAccessToken(permissions: Array<Permissions>, callback:(result:boolean)=>void) {let callerTokenId = rpc.IPCSkeleton.getCallingTokenId();var atManager = abilityAccessCtrl.createAtManager();try {permissions.map((permission, index) => {return atManager.checkAccessToken(callerTokenId, permission).then((data) => {console.log(`checkAccessToken success, data->${JSON.stringify(data)}`);if( index >= permissions.length - 1 ) {callback(true);}}).catch(() => {callback(false);});});} catch(err) {console.log(`RequestPermission catch err->${JSON.stringify(err)}`);callback(false,);}}
}export default new RequestPermission()