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"
}
}
]
- 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
- (!) 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
}
Key Takeaways
- Be sure to add the permission to the module.json5 file.
- Use requestPermissionFromUser() to ask for permission.
- If the user rejected the permission before, use the requestPermissionOnSetting().
Additional Resources
requestPermissionFromUser()
requestPermissionOnSetting()
Top comments (0)