鸿蒙中位置权限和相机权限

1.module.json5中添加相关权限和string.json中配置信息

复制代码
import { hilog } from '@kit.PerformanceAnalysisKit';
import { TAG } from '@ohos/hypium/src/main/Constant';
import { bundleManager, common } from '@kit.AbilityKit';
import { abilityAccessCtrl } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { geoLocationManager } from '@kit.LocationKit';
import { intl } from '@kit.LocalizationKit';

@Entry
@Component
struct Index {
  @State locale: string = new intl.Locale().language;
  @State currentLocation: string = '';
  @State latitude: number = 0;
  @State longitude: number = 0;
  @State permissionsMessage: string | Resource = "\"获取当前位置\"需获取定位权限才能正常使用"
  @State locationServiceMessage: string | Resource =  "\"获取当前位置\"需获取定位权限才能正常使用"
  private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;


  // 相机权限-------start
  // 用户申请权限
  async reqPermissionsFromUser(): Promise<number[]> {
    hilog.info(0x0001, TAG, 'reqPermissionsFromUser start');
    let context = getContext() as common.UIAbilityContext;
    let atManager = abilityAccessCtrl.createAtManager();
    let grantStatus = await atManager.requestPermissionsFromUser(context, ['ohos.permission.CAMERA']);
    return grantStatus.authResults;
  }
  // 用户申请相机权限
  async requestCameraPermission() {
    let grantStatus = await this.reqPermissionsFromUser();
    for (let i = 0; i < grantStatus.length; i++) {
      if (grantStatus[i] === 0) {
        // 用户授权,可以继续访问目标操作
        hilog.info(0x0001, TAG, 'Succeeded in getting permissions.');
        AlertDialog.show({message:"相机权限已开启"})
      }
    }
  }
  // 相机权限-------end

  // 位置权限----------start
  checkPermissionGrant(): void {
    let hasPermission = false;
    let tokenId: number = 0;
    try {
      let bundleInfo: bundleManager.BundleInfo =
        bundleManager.getBundleInfoForSelfSync(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
      let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo;
      tokenId = appInfo.accessTokenId;
    } catch (error) {
      const err: BusinessError = error as BusinessError;
      hilog.error(0x0000, 'Index',
        `Failed to get bundle info for self. Code is ${err.code}, message is ${err.message}`);
    }

    try {
      let atManager = abilityAccessCtrl.createAtManager();
      let approximatelyLocation = atManager.checkAccessTokenSync(tokenId, 'ohos.permission.APPROXIMATELY_LOCATION');
      let location = atManager.checkAccessTokenSync(tokenId, 'ohos.permission.LOCATION');
      hasPermission = approximatelyLocation === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED &&
        location === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED;
    } catch (error) {
      const err: BusinessError = error as BusinessError;
      hilog.error(0x0000, 'Index', `Failed to check access token. Code is ${err.code}, message is ${err.message}`);
    }
    if (hasPermission) {
      this.isLocationToggle();
    } else {
      this.requestPermissions();
    }
  }
  isLocationToggle(): void {
    let atManager = abilityAccessCtrl.createAtManager();
    let isLocationEnabled = geoLocationManager.isLocationEnabled();
    if (!isLocationEnabled) {
      atManager.requestGlobalSwitch(this.context, abilityAccessCtrl.SwitchType.LOCATION).then((data: boolean) => {
        if (data) {
          // this.isShowLocation = false;
          this.getLocation();
        } else {
          // this.isShowLocation = true;
          this.locationServiceMessage = "\"获取当前位置\"需打开设备位置服务才能获取当前位置。"
        }
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, 'Index', 'data:' + JSON.stringify(err));
      });
    } else {
      // this.isShowLocation = false;
      this.getLocation();
    }
  }

  requestPermissions(): void {
    let atManager = abilityAccessCtrl.createAtManager();
    try {
      atManager.requestPermissionsFromUser(this.context, ['ohos.permission.APPROXIMATELY_LOCATION',
        'ohos.permission.LOCATION']).then((data) => {
        if (data.authResults[0] === -1 || data.authResults[1] === -1) {
          if (data.dialogShownResults && (data.dialogShownResults[0] || data.dialogShownResults[1])) {
            // this.isShowPermissions = true;
            if(data.authResults[0] === -1){
              this.permissionsMessage =  "\"获取当前位置\"需获取定位权限才能正常使用"
            } else {
              this.permissionsMessage = "\"获取当前位置\"需获取精确定位权限才能获取精确位置。"
            }
          } else {
            this.openPermissionsSetting();
            return;
          }
        } else {
          // this.isShowPermissions = false;
        }
        if (data.authResults[0] !== 0) {
          return;
        }
        this.isLocationToggle();
      }).catch((err: Error) => {
        hilog.error(0x0000, 'Index', 'requestPermissionsFromUser err:' + JSON.stringify(err));
      });
    } catch (err) {
      hilog.error(0x0000, 'Index', 'requestPermissionsFromUser err:' + JSON.stringify(err));
    }
  }
  private openPermissionsSetting(): void {
    let atManager = abilityAccessCtrl.createAtManager();
    atManager.requestPermissionOnSetting(this.context, ['ohos.permission.APPROXIMATELY_LOCATION',
      'ohos.permission.LOCATION']).then((data: Array<abilityAccessCtrl.GrantStatus>) => {
      if (data[0] === -1 && data[1] === -1) {
        // this.isShowPermissions = true;
        this.permissionsMessage = "\"获取当前位置\"需获取定位权限才能正常使用"
        return;
      } else if (data[0] === 0 && data[1] === -1) {
        // this.isShowPermissions = true;
        this.permissionsMessage = "\"获取当前位置\"需获取精确定位权限才能获取精确位置。"
      } else {
        // this.isShowPermissions = false;
      }
      this.isLocationToggle();
    }).catch((err: BusinessError) => {
      hilog.error(0x0000, 'Index', 'data:' + JSON.stringify(err));
    });
  }

  getLocation(): void {
    let request: geoLocationManager.SingleLocationRequest = {
      'locatingTimeoutMs': 10000,
      'locatingPriority': geoLocationManager.LocatingPriority.PRIORITY_LOCATING_SPEED
    };
    // Get current location.
    geoLocationManager.getCurrentLocation(request).then((location) => {
      this.latitude = location.latitude;
      this.longitude = location.longitude;
      let reverseGeocodeRequest: geoLocationManager.ReverseGeoCodeRequest = {
        'locale': this.locale.toString().includes('zh') ? 'zh' : 'en',
        'latitude': this.latitude,
        'longitude': this.longitude,
        'maxItems': 1
      };
      // Call the inverse geocoding service to convert coordinates into geographic descriptions.
      geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest).then((data) => {
        if (data[0].placeName) {
          this.currentLocation = data[0].placeName;
          AlertDialog.show({message:this.currentLocation})
        }
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, 'Index', 'GetAddressesFromLocation err:' + JSON.stringify(err));
      });
    }).catch((err: BusinessError) => {
      hilog.error(0x0000, 'Index', 'Promise getCurrentLocation err:' + JSON.stringify(err));
    })
  }
  // 位置权限----------end
  build() {
Column(){
  Button('位置权限').onClick((event: ClickEvent) => {
    this.checkPermissionGrant();
  })
  Button('相机权限').onClick(async ()=>{
    await this.requestCameraPermission();
  })
}
  }
}
相关推荐
JasonYin~34 分钟前
HarmonyOS NEXT 实战之元服务:静态案例效果---查看国际航班服务
华为·harmonyos
深海的鲸同学 luvi1 小时前
【HarmonyOS NEXT】hdc环境变量配置
linux·windows·harmonyos
Freerain996 小时前
鸿蒙Next ArkTS语法适配背景概述
华为·harmonyos
他的猫哎6 小时前
鸿蒙 Navigation组件下的组件获取pageStack问题
harmonyos·鸿蒙
雨汨6 小时前
鸿蒙之路的坑
华为·harmonyos
轻口味8 小时前
【每日学点鸿蒙知识】沙箱目录、图片压缩、characteristicsArray、gm-crypto 国密加解密、通知权限
pytorch·华为·harmonyos
资源补给站9 小时前
大恒相机开发(2)—Python软触发调用采集图像
开发语言·python·数码相机
xo1988201111 小时前
鸿蒙人脸识别
redis·华为·harmonyos
塞尔维亚大汉12 小时前
【OpenHarmony】 鸿蒙 UI开发之CircleIndicator
harmonyos·arkui
BisonLiu12 小时前
华为仓颉鸿蒙HarmonyOS NEXT仓颉原生数据网络HTTP请求(ohos.net.http)
harmonyos