非首次授权跳转设置,对于用户非第一次授权或者拒绝授权时,让用户选择跳转设置去手动授权或者忽略。

非首次授权跳转设置

HarmonyOS
2024-05-23 22:57:27
1545浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
好难的昵称

对于用户非第一次授权或者拒绝授权时,让用户选择跳转设置去手动授权或者忽略。

核心代码解释:

import abilityAccessCtrl, { Context, PermissionRequestResult, Permissions } from '@ohos.abilityAccessCtrl'; 
import { BusinessError } from '@ohos.base'; 
import common from '@ohos.app.ability.common'; 
import bundleManager from '@ohos.bundle.bundleManager'; 
import { Want } from '@kit.AbilityKit'; 
 
// const permissions: Array<Permissions> = ['ohos.permission.APPROXIMATELY_LOCATION', 'ohos.permission.ACCESS_BLUETOOTH', 'ohos.permission.CAMERA']; 
const permissions: Array<Permissions> = ['ohos.permission.APPROXIMATELY_LOCATION', 'ohos.permission.LOCATION']; 
// const permissions: Array<Permissions> = ['ohos.permission.READ_MEDIA', 'ohos.permission.WRITE_MEDIA']; 
const permissions1: Array<Permissions> = ['ohos.permission.ACCESS_BLUETOOTH']; // 蓝牙 
const permissions2: Array<Permissions> = ['ohos.permission.APPROXIMATELY_LOCATION']; // 模糊位置权限 
const permissions3: Array<Permissions> = ['ohos.permission.PRIVACY_WINDOW']; 
const permissions4: Array<Permissions> = ['ohos.permission.CAMERA']; // 相机 
const permissions5: Array<Permissions> = ['ohos.permission.READ_IMAGEVIDEO']; // 允许读取用户公共目录的图片或视频文件。 
const permissions6: Array<Permissions> = ['ohos.permission.LOCATION_IN_BACKGROUND']; // 允许读取用户公共目录的图片或视频文件。 
const permissions7: Array<Permissions> = ['ohos.permission.LOCATION_IN_BACKGROUND']; // 精确位置权限 
const permissions8: Array<Permissions> = ['ohos.permission.APPROXIMATELY_LOCATION', 'ohos.permission.LOCATION']; 
const context = getContext(this) 
const uiAbilityContext = context as common.UIAbilityContext; 
 
@CustomDialog 
struct CustomDialogExample { 
  @Link textValue: string 
  @Link inputValue: string 
  dialogControllerTwo: CustomDialogController | null = new CustomDialogController({ 
    builder: {}, 
    alignment: DialogAlignment.Bottom, 
    offset: { dx: 0, dy: -25 } 
  }) 
  controller?: CustomDialogController 
  // 若尝试在CustomDialog中传入多个其他的Controller,以实现在CustomDialog中打开另一个或另一些CustomDialog,那么此处需要将指向自己的controller放在所有controller的后面 
  cancel: () => void = () => { 
  } 
  confirm: () => void = () => { 
  } 
 
  build() { 
    Column() { 
      Flex({ justifyContent: FlexAlign.SpaceAround }) { 
        Button('忽略') 
          .onClick(() => { 
            if (this.controller != undefined) { 
              this.controller.close() 
              this.cancel() 
            } 
          }).backgroundColor(0xffffff).fontColor(Color.Black) 
        Button('跳转设置去授权') 
          .onClick(() => { 
            if (this.controller != undefined) { 
              let context = getContext(this) as common.UIAbilityContext; 
              context.startAbility({ 
                bundleName: 'com.huawei.hmos.settings', 
                abilityName: 'com.huawei.hmos.settings.MainAbility', 
              }); 
              this.controller.close() 
              this.confirm() 
            } 
          }).backgroundColor(0xffffff).fontColor(Color.Red) 
      }.margin({ bottom: 10 }) 
    }.borderRadius(10) 
  } 
} 
 
@Entry 
@Component 
struct PermissionBox { 
  @State textValue: string = '' 
  @State inputValue: string = 'click me' 
  dialogController: CustomDialogController | null = new CustomDialogController({ 
    builder: CustomDialogExample({ 
      cancel: this.onCancel, 
      confirm: this.onAccept, 
      textValue: $textValue, 
      inputValue: $inputValue 
    }), 
    cancel: this.exitApp, 
    autoCancel: true, 
    alignment: DialogAlignment.Bottom, 
    offset: { dx: 0, dy: -20 }, 
    gridCount: 4, 
    customStyle: false, 
    cornerRadius: 10, 
  }) 
 
  // 在自定义组件即将析构销毁时将dialogControlle置空 
  aboutToDisappear() { 
    this.dialogController = null // 将dialogController置空 
  } 
 
  onCancel() { 
    console.info('Callback when the first button is clicked') 
  } 
 
  onAccept() { 
    console.info('Callback when the second button is clicked') 
  } 
 
  exitApp() { 
    console.info('Click the callback in the blank area') 
  } 
 
  reqPermissionsFromUser(permissions: Array<Permissions>): void { 
    let context: Context = getContext(this) as common.UIAbilityContext; 
    let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); 
    // requestPermissionsFromUser会判断权限的授权状态来决定是否唤起弹窗 
    atManager.requestPermissionsFromUser(context, permissions).then((data: PermissionRequestResult) => { 
      let grantStatus: Array<number> = data.authResults; 
      let length: number = grantStatus.length; 
      for (let i = 0; i < length; i++) { 
        if (grantStatus[i] === 0) { 
          // 用户授权,可以继续访问目标操作 
        } else { 
          if (this.dialogController != null) { 
            this.dialogController.open() 
          } 
          // 用户拒绝授权,提示用户必须授权才能访问当前页面的功能,并引导用户到系统设置中打开相应的权限 
          if (grantStatus[i] === 0) { 
            let context = getContext(this) as common.UIAbilityContext; 
            context.startAbility({ 
              bundleName: 'com.huawei.hmos.settings', 
              abilityName: 'com.huawei.hmos.settings.MainAbility', 
            }); 
          } 
          return; 
        } 
      } 
      // 授权成功 
    }).catch((err: BusinessError) => { 
      console.error(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`); 
    }) 
  } 
 
  // 页面展示 
  build() { 
    Column() { 
      Button("三次申请授权") 
        .fontSize(30) 
        .onClick(() => { 
          this.reqPermissionsFromUser(permissions2) 
          this.reqPermissionsFromUser(permissions1) 
          this.reqPermissionsFromUser(permissions4) 
        }) 
      Blank().height(30) 
      Button("申请权限") 
        .fontSize(30) 
        .onClick(() => { 
          this.reqPermissionsFromUser(permissions8) 
        }) 
      Blank().height(30) 
      Button("三个权限一起获取") 
        .fontSize(30) 
        .onClick(() => { 
          this.reqPermissionsFromUser(permissions7) 
        }) 
      Blank().height('20') 
      Button("去校验权限") 
        .fontSize(30) 
        .onClick(async () => { 
          let grantStatus: abilityAccessCtrl.GrantStatus = await checkAccessToken(permissions2[0]); 
          AlertDialog.show({ message: grantStatus.toString() }) 
        }) 
      Button("跳转到设置").onClick(() => { 
        let context = getContext(this) as common.UIAbilityContext; 
        context.startAbility({ 
          bundleName: 'com.huawei.hmos.settings', 
          abilityName: 'com.huawei.hmos.settings.MainAbility', 
        }); 
      }) 
      Button("跳转到APP通知设置").onClick(() => { 
        let context = getContext(this) as common.UIAbilityContext; 
        context.startAbility({ 
          bundleName: 'com.huawei.hmos.settings', 
          abilityName: 'com.huawei.hmos.settings.MainAbility', 
          uri: 'application_info_entry', // application_settings application_info_entry 
          parameters: { 
            pushParams: uiAbilityContext.abilityInfo.bundleName // 应用包名com.example.tosettingdemo 
          } 
        }); 
      }) 
    }.width('100%') 
    .height('100%').justifyContent(FlexAlign.Center) 
  } 
} 
 
export async function checkAccessToken(permission: Permissions): Promise<abilityAccessCtrl.GrantStatus> { 
  let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); 
  let grantStatus: abilityAccessCtrl.GrantStatus = abilityAccessCtrl.GrantStatus.PERMISSION_DENIED; 
  // 获取应用程序的accessTokenID 
  let tokenId: number = 0; 
  try { 
    let bundleInfo: bundleManager.BundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION); 
    let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo; 
    tokenId = appInfo.accessTokenId; 
  } catch (error) { 
    let err: BusinessError = error as BusinessError; 
    console.error(`Failed to get bundle info for self. Code is ${err.code}, message is ${err.message}`); 
  } 
  // 校验应用是否被授予权限 
  try { 
    grantStatus = await atManager.checkAccessToken(tokenId, permission); 
  } catch (error) { 
    let err: BusinessError = error as BusinessError; 
    console.error(`Failed to check access token. Code is ${err.code}, message is ${err.message}`); 
  } 
  return grantStatus; 
} 
 
async function checkPermissions(): Promise<void> { 
  const permissions: Array<Permissions> = ['ohos.permission.ACCESS_BLUETOOTH']; 
  let grantStatus: abilityAccessCtrl.GrantStatus = await checkAccessToken(permissions[0]); 
  if (grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) { 
    // 已经授权 
  } else { 
    // 未授权 
  } 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128.
  • 129.
  • 130.
  • 131.
  • 132.
  • 133.
  • 134.
  • 135.
  • 136.
  • 137.
  • 138.
  • 139.
  • 140.
  • 141.
  • 142.
  • 143.
  • 144.
  • 145.
  • 146.
  • 147.
  • 148.
  • 149.
  • 150.
  • 151.
  • 152.
  • 153.
  • 154.
  • 155.
  • 156.
  • 157.
  • 158.
  • 159.
  • 160.
  • 161.
  • 162.
  • 163.
  • 164.
  • 165.
  • 166.
  • 167.
  • 168.
  • 169.
  • 170.
  • 171.
  • 172.
  • 173.
  • 174.
  • 175.
  • 176.
  • 177.
  • 178.
  • 179.
  • 180.
  • 181.
  • 182.
  • 183.
  • 184.
  • 185.
  • 186.
  • 187.
  • 188.
  • 189.
  • 190.
  • 191.
  • 192.
  • 193.
  • 194.
  • 195.
  • 196.
  • 197.
  • 198.
  • 199.
  • 200.
  • 201.
  • 202.
  • 203.
  • 204.
  • 205.
  • 206.
  • 207.
  • 208.
  • 209.
  • 210.
  • 211.
  • 212.
  • 213.
  • 214.
  • 215.
  • 216.
分享
微博
QQ
微信
回复
2024-05-24 22:30:29


相关问题
定位授权 直接提示用户拒绝授权
1055浏览 • 1回复 待解决
HarmonyOS 跳转应用授权页面白屏
850浏览 • 1回复 待解决
HarmonyOS webview权限授权拒绝
921浏览 • 1回复 待解决
如何实现向用户申请授权的功能
2597浏览 • 1回复 待解决
求大佬告知如何向用户申请授权
1210浏览 • 2回复 待解决
如何向用户请求授权广告跟踪权限
1034浏览 • 1回复 待解决
打开授权设置页Button的实现
1048浏览 • 1回复 待解决
取消Account Kit 获取用户头像昵称授权
1372浏览 • 1回复 待解决
些帐号授权相关问题
9540浏览 • 2回复 待解决
如何申请组合授权权限?
1226浏览 • 1回复 待解决
OAID授权问题有哪些?
1549浏览 • 1回复 待解决