HarmonyOS Development: Permission Authorization Package

AbnerMingAbnerMing
6 min read

Foreword

this paper is based on api13.

Three knowledge points related to permissions have been shared one after another. In the previous article, cases of native code have also been shared about the status acquisition of permissions and the application of permissions. In this article, we have encapsulated permission authorization for flexible use in actual development.

For the encapsulation of Permission authorization, the main function points are to obtain the current status of permission, that is, whether it has been authorized; And actively apply for permission authorization, that is, pop-up system permission application pop-up window; In addition to the above two functions, when the user rejects the permission, whether to prompt the system to set the page opening permission also needs to be encapsulated.

Permissions List

the permission list is the permission group that we apply to the user. For example, if you want to take a picture, you need to apply for camera permission. In the previous case, there was an overview, but each permission is a long string. Although there is an association function in the code, it is not very convenient to manage. Therefore, for the permission list, a constant management class is separately made here to facilitate subsequent use.

Permissions

overview

ohos.permission.ACCESS_BLUETOOTH

allows applications to access Bluetooth and use Bluetooth capabilities, such as pairing, connecting peripherals, etc.

ohos.permission.MEDIA_LOCATION

allows apps to access geolocation information in user media files

ohos.permission.APP_TRACKING_CONSENT

allow apps to read open anonymous device identifiers

ohos.permission.ACTIVITY_MOTION

allows the app to read the user's motion status

ohos.permission.CAMERA

allow the app to use the camera

ohos.permission.DISTRIBUTED_DATASYNC

allows data exchange between different devices

ohos.permission.LOCATION_IN_BACKGROUND

allow apps to get device location information while running in the background

ohos.permission.LOCATION

allow apps to get device location information

ohos.permission.APPROXIMATELY_LOCATION

allow the app to get the device's ambiguous location information

ohos.permission.MICROPHONE

allow the app to use the microphone

ohos.permission.READ_CALENDAR

allow the app to read calendar information

ohos.permission.WRITE_CALENDAR

allows the app to add, remove, or change calendar events.

ohos.permission.READ_HEALTH_DATA

Allows the app to read the user's health data

ohos.permission.ACCESS_NEARLINK

allows applications to access and use Starshine capabilities, such as pairing, connecting peripherals, etc.

Permission Constant Class

mainly use the commonly used permissions to generate the corresponding constants. When calling, use this constant directly.

import { Permissions } from '@kit.AbilityKit';
/**
 *AUTHOR:AbnerMing
 *DATE:2025/3/15
 *INTRODUCE:
 */

export class PermissionsConstant {
  static CAMERA: Permissions = "ohos.permission.CAMERA"
  static ACCESS_BLUETOOTH: Permissions = "ohos.permission.ACCESS_BLUETOOTH"
  static MEDIA_LOCATION: Permissions = "ohos.permission.MEDIA_LOCATION"
  static APP_TRACKING_CONSENT: Permissions = "ohos.permission.APP_TRACKING_CONSENT"
  static ACTIVITY_MOTION: Permissions = "ohos.permission.ACTIVITY_MOTION"
  static DISTRIBUTED_DATASYNC: Permissions = "ohos.permission.DISTRIBUTED_DATASYNC"
  static LOCATION_IN_BACKGROUND: Permissions = "ohos.permission.LOCATION_IN_BACKGROUND"
  static LOCATION: Permissions = "ohos.permission.LOCATION"
  static APPROXIMATELY_LOCATION: Permissions = "ohos.permission.APPROXIMATELY_LOCATION"
  static MICROPHONE: Permissions = "ohos.permission.MICROPHONE"
  static READ_CALENDAR: Permissions = "ohos.permission.READ_CALENDAR"
  static READ_HEALTH_DATA: Permissions = "ohos.permission.READ_HEALTH_DATA"
  static ACCESS_NEARLINK: Permissions = "ohos.permission.ACCESS_NEARLINK"
}

Permission Management

permission management includes three functions, namely, permission status check, permission application, and secondary permission verification prompt. At present, it simply encapsulates common calling methods and also provides asynchronous and synchronous calling methods.

import { abilityAccessCtrl, bundleManager, Permissions } from "@kit.AbilityKit"
/**
*AUTHOR:AbnerMing
*DATE:2025/3/15
*INTRODUCE: Permission Management Tool
*/
export class PermissionsUtil {
private constructor() {
}
private static mPermissionsUtil: PermissionsUtil
public static get(): PermissionsUtil {
if (PermissionsUtil.mPermissionsUtil == undefined) {
PermissionsUtil.mPermissionsUtil = new PermissionsUtil()
}
return PermissionsUtil.mPermissionsUtil
}
/**
*AUTHOR:AbnerMing
*INTRODUCE: Check and request permissions
*/
checkRequestPermission(permissions: Permissions[], success: () => void, error? : () => void) {
if (!this.checkPermissions(permissions)) {
this.requestPermission(permissions, () => {
success()
}, () => {
this.requestPermissionOnSetting(permissions, () => {
success()
}, error)
})
} else {
success()
}
}
/**
*AUTHOR:AbnerMing
*INTRODUCE: Check and request permissions
*/
async checkRequestPermissionPromise(permissions: Permissions[]): Promise<boolean> {
if (!this.checkPermissions(permissions)) {
let isBool = await this.requestPermissionPromise(permissions)
if (isBool) {
return true
}
let isSetting = await this.requestPermissionOnSettingPromise(permissions)
if (isSetting) {
return true
}
return false
} else {
return true
}
}
/**
*AUTHOR:AbnerMing
*INTRODUCE: Check user permissions, individual permissions
*/
checkPermission(permission: Permissions): boolean {
let grantStatus = this.getGrantStatus(permission)
if (grantStatus == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
//Already have permission
return true
} else {
//No permission
return false
}
}
/**
*AUTHOR:AbnerMing
*INTRODUCE: Check user permissions, multiple permissions, one without permission, all without permission
*/
checkPermissions(permissions: Permissions[]): boolean {
let isPermissions = true
permissions.forEach((item) => {
let grantStatus = this.getGrantStatus(item)
if (grantStatus != abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
isPermissions = false
}
})
return isPermissions
}
/**
*AUTHOR:AbnerMing
*INTRODUCE: Check user permissions, multiple permissions, return an array without permissions
*/
checkPermissionList(permissions: Permissions[]): Permissions[] {
let permissionArray: Permissions[] = []
permissions.forEach((item) => {
let grantStatus = this.getGrantStatus(item)
if (grantStatus != abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
permissionArray.push(item)
}
})
return permissionArray
}
/**
*AUTHOR:AbnerMing
*INTRODUCE: Permission Request
*/
requestPermission(permissions: Permissions[],
success: () => void, error? : (permissionArray: string[]) => void) {
this.getAtManager().requestPermissionsFromUser(getContext(), permissions)
.then((data) => {
let grantStatus: Array<number> = data.authResults
let tempPermissionList: Permissions[] = []
for (let i = 0; i < grantStatus.length; i++) {
if (grantStatus[i] != 0) {
tempPermissionList.push(permissions[i])
}
}
if (tempPermissionList.length == 0) {
success()
} else {
if (error != undefined) {
error(tempPermissionList)
}
}
})
}
/**
*AUTHOR:AbnerMing
*INTRODUCE: Permission Request
*/
async requestPermissionPromise(permissions: Permissions[]): Promise<boolean> {
let result = await this.getAtManager().requestPermissionsFromUser(getContext(), permissions)
let grantStatus: Array<number> = result.authResults
let tempPermissionList: Permissions[] = []
for (let i = 0; i < grantStatus.length; i++) {
if (grantStatus[i] != 0) {
tempPermissionList.push(permissions[i])
}
}
if (tempPermissionList.length == 0) {
return true
} else {
return false
}
}
/**
*AUTHOR:AbnerMing
*INTRODUCE: Apply for authorization from the user twice
*/
requestPermissionOnSetting(permissions: Array<Permissions>,
success: () => void, error? : () => void) {
abilityAccessCtrl.createAtManager().requestPermissionOnSetting(getContext(), permissions)
.then((data: Array<abilityAccessCtrl.GrantStatus>) => {
let isPermissions = true
data.forEach((status) => {
if (status != abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
//No permission
isPermissions = false
}
})
if (isPermissions) {
success()
} else {
if (error != undefined) {
error()
}
}
})
}
/**
*AUTHOR:AbnerMing
*INTRODUCE: Apply for authorization from the user twice
*/
async requestPermissionOnSettingPromise(permissions: Array<Permissions>): Promise<boolean> {
let result = await abilityAccessCtrl.createAtManager().requestPermissionOnSetting(getContext(), permissions)
let isPermissions = true
result.forEach((status) => {
if (status != abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
//No permission
is

Code call

asynchronous permission request

 PermissionsUtil.get().checkRequestPermission([PermissionsConstant.CAMERA], () => {
            console.log("======yes")
          }, () => {
            console.log("======no")
          })

synchronizable permission application

private async checkPermission() {
  let isPermission = await PermissionsUtil.get().checkRequestPermissionPromise([PermissionsConstant.CAMERA])
  if (isPermission) {
    console.log("======yes")
  } else {
    console.log("======no")
  }
}

if the above code does not have permission, the system pop-up window for permission application will pop up directly. After rejection, a second permission application will be made.

regarding permissions, including the content of this chapter, four chapters have been elaborated, from the relevant concepts to the authorization method of permissions management, to the application of permissions, to the final permission tool class encapsulation, basically covering 7788, hoping to help everyone.

0
Subscribe to my newsletter

Read articles from AbnerMing directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

AbnerMing
AbnerMing