一. 权限分类
1. system_grant
system_grant 为系统授权,无需询问用户,常用的权限包括网络请求、获取网络信息、获取wifi信息、获取传感器数据等。
/* system_grant(系统授权)*/static readonly INTERNET = 'ohos.permission.INTERNET' // 网路请求static readonly GET_NETWORK_INFO = 'ohos.permission.GET_NETWORK_INFO' // 网络信息-读static readonly GET_WIFI_INFO = 'ohos.permission.GET_WIFI_INFO' // WIFI信息-读static readonly GYROSCOPE = 'ohos.permission.GYROSCOPE' // 陀螺仪传感器static readonly ACCELEROMETER = 'ohos.permission.ACCELEROMETER' // 加速度传感器
2. user_grant
user_grant 是需要用户授权的权限,常用的权限包括定位、相机、麦克风、日历、文件读写等。
/* user_grant(用户授权)*/static readonly LOCATION = 'ohos.permission.LOCATION' // 定位-精确static readonly APPROXIMATELY_LOCATION = 'ohos.permission.APPROXIMATELY_LOCATION' // 定位-模糊static readonly LOCATION_IN_BACKGROUND = 'ohos.permission.LOCATION_IN_BACKGROUND' // 定位-后台static readonly CAMERA = 'ohos.permission.CAMERA' // 相机static readonly MICROPHONE = 'ohos.permission.MICROPHONE' // 麦克风static readonly READ_CONTACTS = 'ohos.permission.READ_CONTACTS' // 通讯录-读static readonly WRITE_CONTACTS = 'ohos.permission.WRITE_CONTACTS' // 通讯录-写static readonly READ_CALENDAR = 'ohos.permission.READ_CALENDAR' // 日历-读static readonly WRITE_CALENDAR = 'ohos.permission.WRITE_CALENDAR' // 日历-写static readonly WRITE_IMAGEVIDEO = 'ohos.permission.WRITE_IMAGEVIDEO' // 图片视频-写static readonly READ_IMAGEVIDEO = 'ohos.permission.READ_IMAGEVIDEO' // 图片视频-读static readonly MEDIA_LOCATION = 'ohos.permission.MEDIA_LOCATION' // 多媒体-本地static readonly WRITE_AUDIO = 'ohos.permission.WRITE_AUDIO' // 音频-写static readonly READ_AUDIO = 'ohos.permission.READ_AUDIO' // 音频-读static readonly READ_MEDIA = 'ohos.permission.READ_MEDIA' // 文件-读static readonly WRITE_MEDIA = 'ohos.permission.WRITE_MEDIA' // 文件-写static readonly APP_TRACKING_CONSENT = 'ohos.permission.APP_TRACKING_CONSENT' // 广告标识符static readonly DISTRIBUTED_DATASYNC = 'ohos.permission.DISTRIBUTED_DATASYNC' // 多设备协同static readonly ACCESS_BLUETOOTH = 'ohos.permission.ACCESS_BLUETOOTH' // 使用蓝牙能力static readonly READ_PASTEBOARD = 'ohos.permission.READ_PASTEBOARD' // 剪贴板static readonly READ_HEALTH_DATA = 'ohos.permission.READ_HEALTH_DATA' // 健康数据static readonly ACTIVITY_MOTION = 'ohos.permission.ACTIVITY_MOTION' // 健身运动
二. 权限声明
1. system_grant
在应用 entry 模块的 module.json5 中添加权限声明。
"requestPermissions": [{"name": "ohos.permission.INTERNET"}, {"name": "ohos.permission.GET_NETWORK_INFO"}, {"name": "ohos.permission.GET_WIFI_INFO"}
]
2. user_grant
在应用 entry 模块的 module.json5 中添加权限声明。
"requestPermissions": [{"name": "ohos.permission.LOCATION","reason": "$string:PERMISSION_LOCATION","usedScene": {"abilities": ["EntryAbility"],"when":"inuse"}},{"name": "ohos.permission.APP_TRACKING_CONSENT","reason": "$string:PERMISSION_TRACKING_CONSENT","usedScene": {"abilities": ["EntryAbility"],"when":"inuse"}}
]
三. 权限应用
1. system_grant
使用该类权限不需要弹窗让用户授权,只需要判断一下该权限在应用中是否声明。
import { abilityAccessCtrl, bundleManager, PermissionRequestResult, Permissions, Want } from '@kit.AbilityKit';export class PermissionManager {async checkPermissions(): void {const bundleInfo: bundleManager.BundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION)const tokenId = bundleInfo.appInfo.accessTokenIdconst atManager = abilityAccessCtrl.createAtManager()const state = atManager.checkAccessTokenSync(tokenId, 'ohos.permission.INTERNET')if (state === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {console.log('网络请求可用')} else {console.log('网络请求不可用')}}
}
2. user_grant
使用该类权限需要先判断用户是否授权,先由用户授权之后再使用该类权限相关的能力。
import { abilityAccessCtrl, bundleManager, PermissionRequestResult, Permissions, common } from '@kit.AbilityKit';export class PermissionManager {async checkPermissions(): Promise<void> {const bundleInfo: bundleManager.BundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION)const tokenId = bundleInfo.appInfo.accessTokenIdconst atManager = abilityAccessCtrl.createAtManager()const state = atManager.checkAccessTokenSync(tokenId, 'ohos.permission.LOCATION')if (state === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {console.log('定位权限已开启')} else {const context = AppStorage.get('ability_context') as common.UIAbilityContext // 在EntryAbility中存储AbilityContextconst result: PermissionRequestResult = await atManager.requestPermissionsFromUser(context, ['ohos.permission.LOCATION', 'ohos.permission.APPROXIMATELY_LOCATION'])const authResults: Array<number> = result.authResultsconst grantStatus: boolean = (authResults[0] === 0)if (grantStatus) {console.log('定位权限已开启')} else {console.log('定位权限未开启')} }}
}
3. notification
推送通知的权限是基于 notificationMananger 服务实现,不同于 system_agent 和 user_agent。
import notificationManager from '@ohos.notificationManager';export class PermissionManager {async checkNotificationPermissions(): Promise<void> {let grantStatus = await notificationManager.isNotificationEnabled()if (!grantStatus) {await notificationManager.requestEnableNotification()grantStatus = await notificationManager.isNotificationEnabled()if (!grantStatus) {console.log('通知权限未开启')} else {console.log('通知权限已开启')}} else {console.log('通知权限已开启')}}
}
4. 跳转到APP设置页
import bundleManager from '@ohos.bundle.bundleManager';
import { common, Want } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';export class PermissionManager {async gotoSetting(): Promise<void> {const bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATIONconst bundleParam = bundleManager.getBundleInfoForSelfSync(bundleFlags)const bundleId = bundleParam.namelet wantInfo: Want = {bundleName: 'com.huawei.hmos.settings',abilityName: 'com.huawei.hmos.settings.MainAbility',uri: 'application_info_entry',parameters: {pushParams: bundleId}}const context = AppStorage.get('ability_context') as common.UIAbilityContext // 在EntryAbility中存储AbilityContextcontext.startAbility(wantInfo).catch((error: BusinessError) => {console.error(`startAbility-error: ${JSON.stringify(error)}`)})}
}
源码参考: harmonyos-permission