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

非首次授权跳转设置

HarmonyOS
2024-05-23 22:57:27
浏览
收藏 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 { 
    // 未授权 
  } 
}
分享
微博
QQ
微信
回复
2024-05-24 22:30:29
相关问题
定位授权 直接提示用户拒绝授权
249浏览 • 1回复 待解决
如何向用户请求授权广告跟踪权限
258浏览 • 1回复 待解决
如何实现向用户申请授权的功能
1762浏览 • 1回复 待解决
求大佬告知如何向用户申请授权
434浏览 • 2回复 待解决
打开授权设置页Button的实现
309浏览 • 1回复 待解决
取消Account Kit 获取用户头像昵称授权
414浏览 • 1回复 待解决
如何申请组合授权权限?
315浏览 • 1回复 待解决
些帐号授权相关问题
8573浏览 • 2回复 待解决
鸿蒙是否有预授权机制?
3276浏览 • 1回复 待解决
检查某个权限是否已经授权
383浏览 • 1回复 待解决
OAID授权问题有哪些?
241浏览 • 1回复 待解决
Web中如何创建定位授权弹窗
1795浏览 • 1回复 待解决
是否支持动态授权,你知道多少?
2229浏览 • 1回复 待解决
为什么 QT 可以兼用 GPL 和商业授权
5293浏览 • 1回复 待解决
帐号授权相关问题,和大家讨论
12778浏览 • 3回复 待解决