HarmonyOS Development: Apply for Authorization

AbnerMingAbnerMing
4 min read

Foreword

this paper is based on api13.

Through the overview of the previous two chapters, the basic knowledge points about permissions have been outlined in 7788, so in this article, we focus on how to apply for permissions.

Let me ask you a question. Which kind of authorization method is it to authorize users? Obviously, the answer to the riddle is on the riddle, using user_grant (user authorization), when when an application applies for user_grant permission, the following two steps must be completed.

1. Declare permissions in the requestPermissions tab of the module.json5 configuration file.

2, associates the target objects that need to apply for permissions in the application with the corresponding target permissions, so that users can clearly know which operations require users to grant specified permissions to the application.

Constraint Limits

first of all, user_grant permission authorization must be clearly known to users. It is necessary to apply for permission at the required location when the application is running. It is not allowed to apply when it is not in use. For example, a camera that takes a picture needs to call the system, instead of directly applying as soon as it enters the application, it is necessary to apply when the permission to take a picture is needed.

Second, when applying for permission, if the user refuses to authorize, the pop-up window cannot be pulled up again. At this time, the user needs to be correctly guided to manually grant permission in the "Settings" interface of the system application.

Third, the priority of the system permission pop-up window is the highest and cannot be blocked. The pop-up window information needs to be fully displayed so that the user can identify and complete the authorization action.

Fourth, every time you want to authorize permission, you must first check whether you have the permission, and if you don't go through the application logic.

Fifth, if you apply for authorization in the onWindowStageCreate() callback, you need to wait for the asynchronous interface loadContent()/setuicontrot () to be executed or apply for permission in the loadContent()/settent () callback. Otherwise, the call fails to apply for permission before the Content is loaded.

Permission Application Process

let's take the application for camera permission as a code case and look at the process of permission authorization.

1. Authority Statement

in module.json5 to configure.

"requestPermissions": [
      {
        "name": "ohos.permission.CAMERA",
        "reason": "$string:reason",
        "usedScene": {
          "abilities": [
            "EntryAbility"
          ],
          "when": "always"
        }
      }
    ]

2. Inspection authorization

use the checkaccessstoken () asynchronous function or the checkaccessstokensync synchronous function, checks whether the user has been granted permissions.

 /**
   *AUTHOR:AbnerMing
   *INTRODUCE:
   */
  private getGrantStatus(permissionName: Permissions): abilityAccessCtrl.GrantStatus {
    let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager()
    // accessTokenID
    let bundleInfo = bundleManager.getBundleInfoForSelfSync(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION)
    let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo
    let tokenId: number = appInfo.accessTokenId

    let grantStatus = atManager.checkAccessTokenSync(tokenId, permissionName)
    return grantStatus
  }

The above method, returns the PERMISSION_GRANTED or PERMISSION_DENIED status:

name

value

description

PERMISSION_DENIED

-1

indicates not authorized.

PERMISSION_GRANTED

0

indicates authorized.

3. Apply to the user for authorization

make Use the requestPermissionsFromUser() function to request the appropriate permission:

/**
   *AUTHOR:AbnerMing
   *INTRODUCE:
   */
  requestPermissionsFromUser(permissions: Array<Permissions>) {
    let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager()
    atManager.requestPermissionsFromUser(getContext(), 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) {

          } else {

            return
          }
        }
       //SUCCESS
      })
  }

check permissions process:

  /**
   *AUTHOR:AbnerMing
   *INTRODUCE:
   */
  checkPermissions() {
    let permission: Permissions = "ohos.permission.CAMERA"
    let grantStatus = this.getGrantStatus(permission)
    if (grantStatus == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {

    } else {
      this.requestPermissionsFromUser([permission])
    }
  }

after running the program, the following permission application pop-up window will pop up. This pop-up window is systematic and cannot be modified.

4. Processing authorization results

if the permission has been authorized, the subsequent normal functions can be performed here. If the permission is not authorized, we can continue to prompt the user and let the user go. Open the corresponding permission in the system application "Settings", the path is: Settings> Privacy> Permission Management> Application> Target Application.

Generally, we can call requestpermission onsetting () to perform secondary authorization of permissions.

  /**
   *AUTHOR:AbnerMing
   *INTRODUCE:
   */
  private requestPermissionOnSetting(permissions: Array<Permissions>) {
    abilityAccessCtrl.createAtManager().requestPermissionOnSetting(getContext(), permissions)
      .then((data: Array<abilityAccessCtrl.GrantStatus>) => {
        if (data[0] == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {

        }
      })
  }

in the same sentence, when applying for permission, we should strictly follow the principle of minimum permission, combine dynamic application and clear user guidance, so as to avoid bringing bad experience to users. Similarly, follow, apply again when using permission, remember, apply before passing.

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