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

HarmonyOS
2024-12-19 15:37:21
浏览
收藏 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))
      }
    })
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128.
  • 129.
  • 130.
  • 131.
  • 132.
  • 133.
  • 134.
  • 135.
  • 136.
  • 137.
  • 138.
  • 139.
  • 140.
  • 141.
  • 142.
  • 143.
  • 144.
  • 145.
  • 146.
  • 147.
  • 148.
  • 149.
  • 150.
  • 151.
  • 152.
  • 153.
  • 154.
  • 155.
  • 156.
  • 157.
  • 158.
  • 159.
  • 160.
  • 161.
  • 162.
  • 163.
  • 164.
  • 165.
  • 166.
  • 167.
  • 168.
  • 169.
  • 170.
  • 171.
  • 172.
  • 173.
  • 174.
  • 175.
  • 176.
  • 177.
  • 178.
  • 179.
  • 180.
  • 181.
  • 182.
  • 183.
  • 184.
  • 185.
  • 186.
  • 187.
  • 188.
  • 189.
  • 190.
  • 191.
  • 192.
  • 193.
  • 194.
  • 195.
  • 196.
  • 197.
  • 198.
  • 199.
  • 200.
  • 201.
  • 202.
  • 203.
  • 204.
  • 205.
  • 206.
  • 207.
  • 208.
  • 209.
  • 210.
  • 211.
  • 212.
  • 213.
  • 214.
  • 215.
  • 216.
  • 217.
  • 218.
  • 219.
  • 220.
  • 221.
分享
微博
QQ
微信
回复
2024-12-19 18:00:47


相关问题
如何申请组合授权权限
1202浏览 • 1回复 待解决
HarmonyOS 位置权限申请
951浏览 • 1回复 待解决
app如何申请位置权限
1333浏览 • 1回复 待解决
Web组件如何申请位置权限
1330浏览 • 1回复 待解决
HarmonyOS 申请定位权限失败问题
1192浏览 • 1回复 待解决
Web中网页如何申请位置权限
1528浏览 • 1回复 待解决
HarmonyOS申请用户位置权限问题
1292浏览 • 1回复 待解决
定位授权 直接提示用户拒绝授权
1042浏览 • 1回复 待解决
HarmonyOS 访问控制授权申请如何处理
661浏览 • 1回复 待解决
Web中如何创建定位授权弹窗
2774浏览 • 1回复 待解决
HarmonyOS 动态申请权限申请不了
835浏览 • 1回复 待解决
求大佬告知如何向用户申请授权
1190浏览 • 2回复 待解决
如何实现向用户申请授权的功能
2582浏览 • 1回复 待解决
HarmonyOS webview权限授权被拒绝
908浏览 • 1回复 待解决
HarmonyOS定位权限问题
1320浏览 • 1回复 待解决