欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 名人名企 > HarmonyOS 鸿蒙获取微信授权和持续获取位置信息

HarmonyOS 鸿蒙获取微信授权和持续获取位置信息

2024/11/30 12:40:20 来源:https://blog.csdn.net/weixin_43073383/article/details/141565481  浏览:    关键词:HarmonyOS 鸿蒙获取微信授权和持续获取位置信息

获取授权
PermissionManager.ets

import { BusinessError } from "@kit.BasicServicesKit";
import { abilityAccessCtrl, bundleManager, PermissionRequestResult, Permissions, common ,Want} from "@kit.AbilityKit";/*** 查询是否有单个权限* @param permission 单个权限字符串* @returns*/
export async function checkAccessToken(permission: Permissions): Promise<boolean> {let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();let grantStatus: abilityAccessCtrl.GrantStatus = abilityAccessCtrl.GrantStatus.PERMISSION_DENIED;// 获取应用程序的accessTokenIDlet 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 === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED;
}/*** 用于UIAbility拉起弹框请求用户授权* 如果用户拒绝授权,将无法再次拉起弹窗,需要用户在系统应用“设置”的界面中手动授予权限。* @param permissions 权限数组* @returns*/
export async function requestPermissions(permissions: Permissions []): Promise<boolean> {const context = getContext();let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();let ret = true;try {let data: PermissionRequestResult = await atManager.requestPermissionsFromUser(context, permissions);let grantStatus: Array<number> = data.authResults;let permissions1 = data.permissions;let length: number = grantStatus.length;for (let i = 0; i < length; i++) {if (grantStatus[i] === 0) {ret = trueconsole.log(`${permissions1} permissions is success`);break;} else {console.log(`${permissions1} permissions is failed`);ret = false;}}} catch (e) {console.log(e.message);ret = false;}return ret;
}export async function openPermissionSettingsPage() {// 获取上下文const context = getContext() as common.UIAbilityContext// 获取包信息const bundleInfo = bundleManager.getBundleInfoForSelfSync(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION)// Want信息配置let wantInfo: Want = {bundleName: 'com.huawei.hmos.settings',abilityName: 'com.huawei.hmos.settings.MainAbility',uri: 'application_info_entry',parameters: {// 按照包名打开对应设置页pushParams: bundleInfo.name}}// 打开系统设置页context.startAbility(wantInfo)
}

获取定位
LocationService.ets

import { geoLocationManager } from '@kit.LocationKit';
import { AuthUtil } from './AuthUtil';
import { Permissions } from '@kit.AbilityKit';
import {checkAccessToken, requestPermissions,openPermissionSettingsPage} from  './PermissionManager'export default class LocationService {private locationCallback!: (location: geoLocationManager.Location) => void;async  requestLocationPermission(sucessPermission: (bol:boolean) => void) {const locationPermissions: Permissions[] = ['ohos.permission.LOCATION', 'ohos.permission.APPROXIMATELY_LOCATION'];try {// 检查定位权限是否已经授予const hasPermission = await checkAccessToken(locationPermissions[0]);console.log('hasPermission', hasPermission);if (hasPermission) {console.log('定位权限已经授予');sucessPermission(true)} else {console.log('定位权限未授予,请求权限');const isGranted = await requestPermissions(locationPermissions);if (isGranted) {console.log('定位权限请求成功');sucessPermission(true)} else {console.log('定位权限请求失败,需要用户手动授予权限');openPermissionSettingsPage();}}} catch (error) {console.error('定位权限请求失败:', error);openPermissionSettingsPage();}
}//// public async requestLocationPermission( sucessPermission: (bol:boolean) => void) {//   const locationPermissions: Permissions[] = ['ohos.permission.LOCATION', 'ohos.permission.APPROXIMATELY_LOCATION'];// 根据实际权限名称修改//   try {//     // 检查定位权限是否已经授予//     const hasPermission = PermissionManager.checkAccessToken(locationPermissions);//     if (hasPermission) {//       console.log('定位权限已经授予');//       // 继续其他业务逻辑//       sucessPermission(true)//     } else {//       console.log('定位权限未授予,请求权限');//       // 请求定位权限//       await PermissionManager.requestPermissions(locationPermissions);//       console.log('定位权限请求成功');//       // 继续其他业务逻辑//       sucessPermission(true)//     }//   } catch (error) {//     console.error('定位权限请求失败:', error);//     sucessPermission(false)//     // 引导用户到系统设置页面手动开启权限//     PermissionManager.openPermissionSettingsPage();//   }// }/*** 开启持续定位* @param onStart 开启定位的回调函数* @param onLocationUpdate 位置更新的回调函数*/public openContinuousLocation(onStart: () => void,onLocationUpdate: (location: geoLocationManager.Location) => void) {this.requestLocationPermission((bol)=>{if(bol){let request: geoLocationManager.ContinuousLocationRequest = {'interval': 1,'locationScenario': geoLocationManager.UserActivityScenario.NAVIGATION}this.locationCallback = (location: geoLocationManager.Location): void => {console.log('定位信息: ' + JSON.stringify(location));onLocationUpdate(location);};try {geoLocationManager.on('locationChange', request, this.locationCallback);onStart(); // 调用开启定位的回调函数} catch (err) {console.error("开启持续定位错误: " + JSON.stringify(err));}}else{onStart(); // 调用开启定位的回调函数}})}/*** 关闭持续定位* @param onStop 关闭定位的回调函数*/public closeContinuousLocation(onStop: () => void) {console.log('关闭持续定位');try {geoLocationManager.off('locationChange', this.locationCallback);onStop(); // 调用关闭定位的回调函数} catch (err) {console.error('关闭持续定位错误: ' + err);}}}

调用,必须封装的closeContinuousLocation才生效

import LocationService from '../../Util/LocationService'OpenContinuosLocation() {// 开启持续定位this.locationService.openContinuousLocation(() => {console.log('定位已开启');this.calculateDrivingInfo(null)},(location) => {console.log('位置更新: ' + JSON.stringify(location));});}/*** 关闭持续定位*/ClosedContinuosLocation() {console.log(' 定位关闭 ClosedContinuosLocation')// 关闭持续定位this.locationService.closeContinuousLocation(() => {console.log('定位已关闭');});}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com