HarmonyOS 申请位置权限代码,如何调起定位授权

HarmonyOS
3天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
fox280

可参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/location-permission-guidelines-V5

import geoLocationManager from '@ohos.geoLocationManager';
import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
import bundleManager from '@ohos.bundle.bundleManager';
import common from '@ohos.app.ability.common';
import Want from '@ohos.app.ability.Want';
import { BusinessError } from '@kit.BasicServicesKit';
import connection from '@ohos.net.connection';

@Entry
@Component
struct OfficialLocationPage {
  @State message: string = '开始定位'

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(18)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            this.startLocate()
          })
      }
      .width('100%')
    }
    .height('100%')
  }

  async accessToken(permission: Permissions): Promise<abilityAccessCtrl.GrantStatus> {
    let atManager = abilityAccessCtrl.createAtManager()
    let grantStatus: abilityAccessCtrl.GrantStatus = 100

    let tokenID: number = 0
    try {
      let bundleInfo =
        await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION)
      tokenID = bundleInfo.appInfo.accessTokenId
    } catch (err) {
      console.log('location 获取地理位置token失败')
    }

    try {
      grantStatus = await atManager.checkAccessToken(tokenID, permission)
    } catch (err) {
      console.log('获取地理位置token检测失败')
    }

    return grantStatus
  }

  async accessTokenNet(permission: Permissions): Promise<abilityAccessCtrl.GrantStatus> {
    let atManager = abilityAccessCtrl.createAtManager()
    let grantStatus: abilityAccessCtrl.GrantStatus = 1000

    let tokenID: number = 0
    try {
      let bundleInfo =
        await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION)
      tokenID = bundleInfo.appInfo.accessTokenId
    } catch (err) {
      console.log('Net 获取token失败')
    }

    try {
      grantStatus = await atManager.checkAccessToken(tokenID, permission)
    } catch (err) {
      console.log('获取Net token检测失败')
    }

    return grantStatus
  }

  async checkPermission() {

    let permissions: Array<Permissions> = ['ohos.permission.LOCATION', 'ohos.permission.APPROXIMATELY_LOCATION']
    let locationStatus = await this.accessToken(permissions[0])
    let roximateyStatus = await this.accessToken(permissions[1])
    if (locationStatus == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED &&
      roximateyStatus == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
      console.log('location 已经申请完权限了')

    } else {
      console.log('location 需要申请权限')
      this.requestPermission()
    }
  }

  async checkNetPermission() {

    let permissions: Array<Permissions> = ['ohos.permission.GET_NETWORK_INFO']
    let NetStatus = await this.accessToken(permissions[0])

    //使用getDefaultNetSync
    if (NetStatus == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
      console.log('Net 已经申请完权限了')
      let netHandler = connection.getDefaultNetSync().netId
      console.log(netHandler.toString())

    } else {
      console.log('Net 需要申请权限')
      let atManager = abilityAccessCtrl.createAtManager()
      atManager.requestPermissionsFromUser(getContext(this), permissions, (err, permissionResult) => {
        if (err) {
          console.log('申请权限失败')
          return
        }

        let grantStatus: Array<number> = permissionResult.authResults
        let grantPermissions: Array<string> = permissionResult.permissions
        let length: number = grantStatus.length
        console.log('net user permissioned length' + JSON.stringify(grantPermissions) + length)
        for (let i = 0; i < length; i++) {
          if (grantStatus[i] === 0) {
            console.log('net user has agreed permissioned')
          } else {
            console.log('net user has disagree permissioned')
            this.openPermissionSettings()
          }
        }
      })
    }
  }

  requestPermission() {
    let atManager = abilityAccessCtrl.createAtManager()
    let permissions: Array<Permissions> = ['ohos.permission.LOCATION', 'ohos.permission.APPROXIMATELY_LOCATION']
    atManager.requestPermissionsFromUser(getContext(this), permissions, (err, permissionResult) => {
      if (err) {
        console.log('申请权限失败')
        return
      }

      let grantStatus: Array<number> = permissionResult.authResults
      let grantPermissions: Array<string> = permissionResult.permissions
      let length: number = grantStatus.length
      console.log('location user permissioned length' + JSON.stringify(grantPermissions) + length)
      for (let i = 0; i < length; i++) {
        if (grantStatus[i] === 0) {
          console.log('location user has agreed permissioned')
        } else {
          console.log('location user has disagree permissioned')
          this.openPermissionSettings()
        }
      }
    })
  }

  /*
 * 跳转到权限设置页面
 * */
  openPermissionSettings() {
    let context = getContext(this) as common.UIAbilityContext
    let wantInfo: Want = {
      action: 'action.settings.app.info',
      parameters: {
        settingsParamBundleName: 'com.example.myapplication'
      }
    }
    context.startAbility(wantInfo, (err: BusinessError) => {
      if (err.code) {
        // 处理业务逻辑错误
        console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`);
        return;
      }

      // 执行正常业务
      console.info('startAbility succeed');
    });
  }

  startLocate() {

    this.checkPermission().then(() => {
      let requestInfo: geoLocationManager.LocationRequest = {
        'priority': 0x203,
        'scenario': 0x300,
        'timeInterval': 0,
        'distanceInterval': 0,
        'maxAccuracy': 0
      };
      let locationChange = (location: geoLocationManager.Location) => {
        console.log('location change:data = ' + JSON.stringify(location))
      }
      try {
        geoLocationManager.on('locationChange', requestInfo, locationChange)
      } catch (err) {
        console.error("location change errCode:" + err.code + ",errMessage:" + err.message)
      }

      try {
        //获取当前的地理位置
        geoLocationManager.getCurrentLocation((err, location) => {
          if (err) {
            console.log('location getCurrentLocation err = ' + JSON.stringify(err))
          }
          if (location) {
            console.log('location getCurrentLocation = ' + JSON.stringify(location))
            //{"latitude":40,"longitude":116,"altitude":43.5,"accuracy":5,"speed":0,"timeStamp":1704176491,"direction":45,"timeSinceBoot":13563917977759,"additions":"","additionSize":0,"isFromMock":false}
            let latitude = location.latitude
            let longitude = location.longitude
            let maxItems = 1
            let reverseGeocodeReq: geoLocationManager.ReverseGeoCodeRequest =
              { 'latitude': latitude, 'longitude': longitude, 'maxItems': maxItems }
            //根据坐标转化为地理描述
            geoLocationManager.getAddressesFromLocation(reverseGeocodeReq, (err, val) => {
              if (err) {
                console.log('location getAddressesFromLocation err = ' + JSON.stringify(err))
                //{"code":3301300,"message":"BussinessError 3301300: Reverse geocoding query failed."}
              }
              if (val) {
                console.log('location getAddressesFromLocation = ' + JSON.stringify(val))
              }
            })
          }
        })
      } catch (err) {
        console.log('location getCurrentLocation catch err = ' + JSON.stringify(err))
      }
    })
  }
}
分享
微博
QQ
微信
回复
3天前
相关问题
如何申请组合授权权限
427浏览 • 1回复 待解决
app如何申请位置权限
429浏览 • 1回复 待解决
Web组件如何申请位置权限
450浏览 • 1回复 待解决
HarmonyOS申请用户位置权限问题
478浏览 • 1回复 待解决
Web中网页如何申请位置权限
616浏览 • 1回复 待解决
定位授权 直接提示用户拒绝授权
364浏览 • 1回复 待解决
Web中如何创建定位授权弹窗
1873浏览 • 1回复 待解决
HarmonyOS定位权限问题
428浏览 • 1回复 待解决
如何实现向用户申请授权的功能
1861浏览 • 1回复 待解决
求大佬告知如何向用户申请授权
532浏览 • 2回复 待解决
如何申请广告跟踪权限
437浏览 • 1回复 待解决
HarmonyOS权限申请问题
424浏览 • 1回复 待解决
如何向用户请求授权广告跟踪权限
381浏览 • 1回复 待解决
检查某个权限是否已经授权
489浏览 • 1回复 待解决
HarmonyOS crash日志如何定位问题代码
583浏览 • 1回复 待解决