#创作者激励#Stage模型中获取动态权限 原创

鸿蒙坚果派
发布于 2023-3-14 08:15
浏览
1收藏

Stage模型中动态获取权限

【本文正在参加2023年第一期优质创作者激励计划】

以允许应用读取位置信息等为例进行说明。

1.在module.json5配置文件中声明权限

使用Stage模型的应用,需要在module.json5配置文件中声明权限。

{
  "module" : {
    // ...
       "requestPermissions": [
      {
        "name": "ohos.permission.INTERNET"
      },
      {
        "name": "ohos.permission.READ_MEDIA",
        "reason": "$string:media_permission_reason",
        "usedScene": {
          "abilities": [
            "EntryAbility"
          ],
          "when": "inuse"
        }
      },
      {
        "name": "ohos.permission.MEDIA_LOCATION",
        "reason": "$string:media_permission_reason",
        "usedScene": {
          "abilities": [
            "EntryAbility"
          ],
          "when": "inuse"
        }
      },
      {
        "name": "ohos.permission.LOCATION",
        "reason": "$string:media_permission_reason",
        "usedScene": {
          "abilities": [
            "EntryAbility"
          ],
          "when": "inuse"
        }
      },
      {
        "name": "ohos.permission.CAMERA",
        "reason": "$string:media_permission_reason",
        "usedScene": {
          "abilities": [
            "EntryAbility"
          ],
          "when": "inuse"
        }
      },



    ]
  }
}

2.可以在UIAbility的onCreate/onWindowStageCreate()回调中requestPermissionsFromUser

可以在UIAbility的onCreate或者onWindowStageCreate()回调中调用requestPermissionsFromUser()接口动态申请权限,也可以根据业务需要在UI界面中向用户申请授权。根据requestPermissionsFromUser()接口返回值判断是否已获取目标权限,如果当前已经获取权限,则可以继续正常访问目标接口。

在UIAbility中动态申请授权。

import UIAbility from '@ohos.app.ability.UIAbility';
import Window from '@ohos.window';
import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
import { Permissions } from '@ohos.abilityAccessCtrl';

export default class EntryAbility extends UIAbility {
    // ...

      onCreate() {
        let AtManager = abilityAccessCtrl.createAtManager();
        AtManager.requestPermissionsFromUser(this.context, ['ohos.permission.READ_MEDIA', 'ohos.permission.MEDIA_LOCATION',"ohos.permission.LOCATION","ohos.permission.CAMERA"]).then((data) => {
            hilog.info(0x0000, 'testTag', '%{public}s', 'request permissions from user success' + data);
        }).catch((err) => {
            hilog.error(0x0000, 'testTag', 'Failed to request permissions from user. Cause: %{public}s', JSON.stringify(err) ?? '');
        });
        hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
    }
}

3.也可以在UI界面中向用户申请授权。

import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
import { Permissions } from '@ohos.abilityAccessCtrl';
import common from '@ohos.app.ability.common';

@Entry
@Component
struct Index {
  reqPermissions() {
    let context = getContext(this) as common.UIAbilityContext;
    let AtManager = abilityAccessCtrl.createAtManager();
    // requestPermissionsFromUser会判断权限的授权状态来决定是否唤起弹窗
    const permissions: Array<Permissions> = ['ohos.permission.READ_CALENDAR'];
    AtManager.requestPermissionsFromUser(context, permissions).then((data) => {
      console.info(`[requestPermissions] data: ${JSON.stringify(data)}`);
      let grantStatus: Array<number> = data.authResults;
      if (grantStatus[0] === -1) {
        // 授权失败
      } else {
        // 授权成功
      }
    }).catch((err) => {
      console.error(`[requestPermissions] Failed to start request permissions. Error: ${JSON.stringify(err)}`);
    })
  }

  // 页面展示
  build() {
    // ...
  }
}

最后来看一下效果:
https://ost.51cto.com/person/posts/14830231?tabIndex=2

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
收藏 1
回复
举报
回复
    相关推荐