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

news/2024/11/19 17:42:05/

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// 位置权限----------startcheckPermissionGrant(): 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));})}// 位置权限----------endbuild() {
Column(){Button('位置权限').onClick((event: ClickEvent) => {this.checkPermissionGrant();})Button('相机权限').onClick(async ()=>{await this.requestCameraPermission();})
}}
}

http://www.ppmy.cn/news/1548280.html

相关文章

HarmonyOs学习笔记-布局单位

鸿蒙开发中布局存在很多单位 鸿蒙的默认单位是vp 下方先展示一下在RrkTsUI中我们应该怎么书写&#xff0c;然后讲一下各大单位具体的含义。 Text("这是一个文本, 用默认单位进行展示&#xff0c;也就是vp") .width(100) .height(100);//此段代码与上方代码是一样的…

药香代码:Spring Boot实现中药实验管理

2相关技术 2.1 MYSQL数据库 MySQL是一个真正的多用户、多线程SQL数据库服务器。 是基于SQL的客户/服务器模式的关系数据库管理系统&#xff0c;它的有点有有功能强大、使用简单、管理方便、安全可靠性高、运行速度快、多线程、跨平台性、完全网络化、稳定性等&#xff0c;非常…

git-.git目录解析

目录 .git目录下的文件信息 logs&#xff1a;记录各个分支日志记录 refs&#xff1a;记录本地分支、远程分支、tag标签最新commitID config: 配置信息&#xff0c;详细内容解析看下面介绍HEAD: 工作空间当前所在分支 inde文件: 它又常被称为“暂存区”或“缓存区”。这个文件…

gitlab容器的迁移(部署)并配置自动备份

gitlab容器的迁移&#xff08;部署&#xff09;并配置自动备份 本文背景为从Ubuntu服务器上迁移gitlab容器到windows并备份&#xff0c;若要直接拉取镜直接安装配置可直接从第二小标题参考 1、原Ubuntu的gitlab容器制作为镜像 2.1 将运行的容器制为镜像 #镜像&#xff1a;i…

C#设计模式(12)——享元模式(Flyweight Pattern)

前言 享元模式通过共享对象来减少内存使用和提高性能。 代码 public abstract class Flyweight {public abstract void Control(); }public class ComputerFlyweight : Flyweight {private string _operator;public ComputerFlyweight(string name){_operator name;}public o…

第十六届蓝桥杯模拟赛(第一期)-c++/c

前面填空参考https://blog.csdn.net/2301_76891851/article/details/143448411 后面大题code&#xff1a; 停车场停车 #include <bits/stdc.h> #define int long long using namespace std; int tmp; signed main() {int n;cin>>n;if(n<15)cout<<"…

威胁驱动的网络安全方法论

摘要 目前的网络安全风险管理实践很大程度上是由合规性要求驱动的&#xff0c;这使得公司/组织不得不在安全控制和漏洞上投入人力/物力。&#xff08;风险管理涉及多个方面&#xff0c;包括资产、威胁、漏洞和控制&#xff0c;并根据事故发生的可能性及造成的影响进行评估。威…

dnaMethyAge包学习笔记

1.introduction 许多对甲基化年龄进行计算的文章都是采用网站实现计算的&#xff0c;能够实现对甲基化年龄的计算的R包相对比较少&#xff0c;其中应用最广的是dnaMethyAge包。作者本想寻找能够计算Grimage和Grimage2的R包&#xff0c;奈何没有寻找到&#xff0c;因此只能记录一…