鸿蒙中位置权限和相机权限
1.module.json5中添加相关权限和string.json中配置信息
2.
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(); }) } } }
原文地址:https://blog.csdn.net/2302_79548774/article/details/143858748
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!