DEV Community

HarmonyOS
HarmonyOS

Posted on

requestPermissionsFromUser() does not work or directly returns without asking the user.

Read the original article:requestPermissionsFromUser() does not work or directly returns without asking the user.

Context

The error occurs when requesting permission from the user with the requestPermissionFromUser() function.

Description

The system does not display the permissions dialog box because the settings are missing or the user has previously declined the permission.

Solution

  • First, add required permissions to the module.json5 file. In this example, microphone permission is used.
"requestPermissions": [ // define permissions
  {
    "name": "ohos.permission.MICROPHONE",
    "reason": "$string:mic_reason", // permission usage reason
    "usedScene": {
      "when": "inuse"
    }
  }
]
Enter fullscreen mode Exit fullscreen mode
  • Use requestPermissionFromUser() to ask for permission.
const atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); // get ability manager
const context = this.getUIContext().getHostContext() as Context; // get context
const permissions: Permissions[] = ['ohos.permission.MICROPHONE']; // define permissions

// ask user for permission and get result
let granted = (await atManager.requestPermissionsFromUser(context, permissions)).authResults[0] == 0
Enter fullscreen mode Exit fullscreen mode
  • (!) If the user rejected the permission previously, requestPermissionsFromUser() will not display the permission dialog box. In such cases, use requestPermissionOnSetting().
if (!granted) { // if user did not give permission before
  // ask user for permission on settings
  granted = (await atManager.requestPermissionOnSetting(context, permissions))[0] == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED
}
Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  1. Be sure to add the permission to the module.json5 file.
  2. Use requestPermissionFromUser() to ask for permission.
  3. If the user rejected the permission before, use the requestPermissionOnSetting().

Additional Resources

requestPermissionFromUser()
requestPermissionOnSetting()

Written by Mehmet Karaaslan

Top comments (0)