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;

  // 获取应用程序的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 === 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 = true
        console.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('定位已关闭');
      }
    );
   
  }

你可能感兴趣的:(harmonyos,华为)