OpenHarmony开源社区
直播中

soon顺soon

4年用户 306经验值
擅长:嵌入式技术
私信 关注
[经验]

【软通动力鸿湖万联扬帆系列“竞”开发板试用体验】eTS版本应用权限申请案例

本文主要分享在软通动力子公司扬帆系列“竞”OpenHarmony开发板上运行一个ets版本的应用权限申请并验证权限的案例。

1、新建工程

选择OpenHarmony中Empty Ability如图

输入Project name,Bundle Name 并选择Project type:Application,Compile SDK:9,Model:stage,Language:ets 如下图:
create_projecgt.png

Bundle Name在后续的权限申请中会用到可以先记下。

ets新建工程指导可参考:https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/quick-start/start-with-ets-stage.md

2、主要的代码修改说明

主要修改以下三个文件
src/main/ets/MainAbility/MainAbility.ts
src/main/ets/pages/index.ets
src/main/module.json5
详细说明如下

2.1 在module.json5中添加需要申请的权限

本文以申请MICROPHONE和READ_MEDIA为例,加入"requestPermissions"字段,修改后的src/main/module.json5文件如下:

{
  "module": {
    "name": "entry",
    "type": "entry",
    "srcEntrance": "./ets/Application/MyAbilityStage.ts",
    "description": "$string:entry_desc",
    "mainElement": "MainAbility",
    "deviceTypes": [
      "default",
      "tablet"
    ],
    "deliveryWithInstall": true,
    "installationFree": false,
    "pages": "$profile:main_pages",
    "abilities": [
      {
        "name": "MainAbility",
        "srcEntrance": "./ets/MainAbility/MainAbility.ts",
        "description": "$string:MainAbility_desc",
        "icon": "$media:icon",
        "label": "$string:MainAbility_label",
        "startWindowIcon": "$media:icon",
        "startWindowBackground": "$color:white",
        "visible": true,
        "skills": [
          {
            "entities": [
              "entity.system.home"
            ],
            "actions": [
              "action.system.home"
            ]
          }
        ]
      }
    ],
    "requestPermissions": [
      {
        "name": "ohos.permission.MICROPHONE"
      },
      {
        "name": "ohos.permission.READ_MEDIA"
      }
    ]
  }
}

2.2 在MainAbility.ts中保存ability的上下文context

src/main/ets/MainAbility/MainAbility.ts的 onWindowStageCreate 生命周期中添加globalThis.context = this.context以供在index.ets中调用,修改后的onWindowStageCreate如下:

onWindowStageCreate(windowStage: Window.WindowStage) {
        // Main window is created, set main page for this ability
        hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO);
        hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');

        windowStage.loadContent('pages/index', (err, data) => {
            if (err.code) {
                hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.ERROR);
                hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
                return;
            }
            hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO);
            hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
        });
        globalThis.context = this.context;
    }

这一步是比较关键的如果是在ets中通过featureAbility.getContext()是无法弹出权限申请框的。

2.3 在index.ets中申请并检查相关权限

在request的时候需要用到globalThis.context。在check中getApplicationInfo要填入应用的Bundle Name。src/main/ets/pages/index.ets完整内容如下:

import bundle from '@ohos.bundle'
import abilityAccessCtrl from '@ohos.abilityAccessCtrl'
import prompt from '@ohos.prompt'

@Entry
@Component
struct Index {
  private permissions =
      ["ohos.permission.MICROPHONE",
      "ohos.permission.READ_MEDIA",
      ]

  private async check(permission) {
    let bundleFlag = 0
    let userId = 100
    let appInfo = await bundle.getApplicationInfo('com.soon.testpermissions', bundleFlag, userId)
    let tokenId = appInfo.accessTokenId
    console.info(`soonpermissions grantPermission,tokenId=${tokenId}`)
    let atManager = abilityAccessCtrl.createAtManager()
    let result = await atManager.verifyAccessToken(tokenId, permission)
    console.info(`soonpermissions grantPermission,verifyPermission,result=${result}`)
    return result == abilityAccessCtrl.GrantStatus.PERMISSION_DENIED
  }

  private request(targetPermissionArray, callback) {
    if (targetPermissionArray instanceof Array && targetPermissionArray.length > 0) {
      console.info('soonpermissions SysPermissionUtils requestPermissionsFromUser start. length: ' + targetPermissionArray.length);
      globalThis.context.requestPermissionsFromUser(targetPermissionArray, (result) => {
        console.info('soonpermissions SysPermissionUtils featureAbility requestPermissionsFromUser successful. result: ' + JSON.stringify(result));
        callback(result.code === 0)
      })
    }
  }

  aboutToAppear() {
    this.check("ohos.permission.MICROPHONE").then((isNeedPermission) => {
      if (isNeedPermission) {

        this.request(this.permissions, (isAuth) => {
          console.info('soonpermissions request ')
        })
      } else {
        console.info('soonpermissions isNeedPermission false')
      }
    })
  }

  build() {
    Row() {
      Column() {
        Button($r('app.string.microphone'))
          .height('15%')
          .fontSize(30)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            this.check("ohos.permission.MICROPHONE").then((isNeedPermission) => {
              if (isNeedPermission) {
                prompt.showToast({ message: $r('app.string.unauthorization')})
              } else {
                prompt.showToast({ message: $r('app.string.authorization')})
              }
            })
          })

        Button($r('app.string.readmedia'))
          .margin('10pv')
          .height('15%')
          .fontSize(30)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            this.check("ohos.permission.READ_MEDIA").then((isNeedPermission) => {
              if (isNeedPermission) {
                prompt.showToast({ message: $r('app.string.unauthorization')})
              } else {
                prompt.showToast({ message: $r('app.string.authorization')})
              }
            })
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

以上有用到字符串资源另外需要在src/main/resources/base/element/string.json加入以下

,
    {
      "name": "authorization",
      "value": "Permissions have been granted"
    },
    {
      "name": "unauthorization",
      "value": "Permissions were not granted"
    },
    {
      "name": "microphone",
      "value": "Detect MICROPHONE Permissions"
    },
    {
      "name": "readmedia",
      "value": "Detect READ_MEDIA Permissions"
    }

预览效果如下:
previewer.png

至此代码修改完毕

3 运行测试

在软通动力子公司扬帆系列“竞”OpenHarmony开发板上进行测试,第一次运行hap的时候会弹出权限,申请对话框。
麦克风使用权限申请如下图:
MICROPHONE.jpg
访问媒体和文件权限申请如下图:
media.jpg

权限检查页面:
ui.jpg

主要源码:*附件:TestPermissions.zip

演示视频见底部视频

TestVideo

回帖(2)

打马过草原

2022-11-2 10:12:34
点赞
举报

爱与友人

2022-11-3 18:55:57
看着很不错呀
举报

更多回帖

发帖
×
20
完善资料,
赚取积分