当前位置:   article > 正文

鸿蒙开发之地理位置_鸿蒙开发 权限申请

鸿蒙开发 权限申请

一、权限申请

获取位置信息需要先在module.json5中申请权限,而权限的申请在API9版本发生了变动如下

  1. //API9之前只申请这个就可以米级定位
  2. {'name': 'ohos.permission.LOCATION'},//API9之前申请的权限
  3. //API9后两个权限同时申请才可以获取米级定位,只下边一个权限只能精准到5公里
  4. {'name': 'ohos.permission.APPROXIMATELY_LOCATION'},//API9及之后需要增加申请的权限

所以,如果是高精度的位置信息需要两个权限都申请,如果只是需要模糊定位为了节能只需要第二个权限就够了。

二、检测用户权限

1、检测用户权限需要先获取Token,token是异步回调的
import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
  1. async accessToken(permission: Permissions): Promise<abilityAccessCtrl.GrantStatus> {
  2. let atManager = abilityAccessCtrl.createAtManager()
  3. let grantStatus: abilityAccessCtrl.GrantStatus
  4. let tokenID: number
  5. try {
  6. let bundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION)
  7. tokenID = bundleInfo.appInfo.accessTokenId
  8. } catch (err) {
  9. console.log('location 获取地理位置token失败')
  10. }
  11. try {
  12. grantStatus = await atManager.checkAccessToken(tokenID,permission)
  13. } catch (err) {
  14. console.log('获取地理位置token检测失败')
  15. }
  16. return grantStatus
  17. }
2、获取token后,开始查询用户权限状态
  1. async checkPermission() {
  2. let permissions: Array<Permissions> = ['ohos.permission.LOCATION','ohos.permission.APPROXIMATELY_LOCATION']
  3. let locationStatus = await this.accessToken(permissions[0])
  4. let roximateyStatus = await this.accessToken(permissions[1])
  5. if (locationStatus == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED &&
  6. roximateyStatus == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
  7. console.log('location 已经申请完权限了')
  8. } else {
  9. console.log('location 需要申请权限')
  10. this.requestPermission()
  11. }
  12. }

三、申请权限

  1. //申请权限
  2. requestPermission() {
  3. let atManager = abilityAccessCtrl.createAtManager()
  4. let permissions: Array<Permissions> = ['ohos.permission.LOCATION','ohos.permission.APPROXIMATELY_LOCATION']
  5. atManager.requestPermissionsFromUser(getContext(this),permissions,(err,permissionResult) => {
  6. if (err) {
  7. console.log('申请权限失败')
  8. return
  9. }
  10. let grantStatus: Array<number> = permissionResult.authResults
  11. let grantPermissions: Array<string> = permissionResult.permissions
  12. let length: number = grantStatus.length
  13. console.log('location user permissioned length' + JSON.stringify(grantPermissions)+length)
  14. for(let i = 0; i<length; i++) {
  15. if (grantStatus[i] === 0) {
  16. console.log('location user has agreed permissioned')
  17. } else {//用户不同意,就跳转APP的设置页面方便用户设置权限
  18. console.log('location user has disagree permissioned')
  19. this.openPermissionSettings()
  20. }
  21. }
  22. })
  23. }
  24. /*
  25. * 跳转到权限设置页面
  26. * */
  27. openPermissionSettings() {
  28. let context = getContext(this) as common.UIAbilityContext
  29. let wantInfo = {
  30. action: 'action.settings.app.info',
  31. parameters: {
  32. settingsParamBundleName: 'com.example.myapplication'
  33. }
  34. }
  35. context.startAbility(wantInfo).then(() => {
  36. console.log('location open setting page')
  37. }).catch((err) => {
  38. console.log('location open setting page failed')
  39. })
  40. }

四、权限完成后,开启定位

  1. startLocate() {
  2. this.checkPermission().then(() => {
  3. let requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
  4. let locationChange = (location) => {
  5. console.log('location change:data = '+JSON.stringify(location))
  6. }
  7. try {
  8. //监听位置变化
  9. geoLocationManager.on('locationChange',requestInfo,locationChange)
  10. } catch (err) {
  11. console.error("location change errCode:" + err.code + ",errMessage:" + err.message)
  12. }
  13. try {
  14. //获取当前的地理位置(坐标等)
  15. geoLocationManager.getCurrentLocation((err,location) => {
  16. if (err) {
  17. console.log('location getCurrentLocation err = '+JSON.stringify(err))
  18. }
  19. if (location) {
  20. console.log('location getCurrentLocation = '+JSON.stringify(location))
  21. //{"latitude":40,"longitude":116,"altitude":43.5,"accuracy":5,"speed":0,"timeStamp":1704176491,"direction":45,"timeSinceBoot":13563917977759,"additions":"","additionSize":0,"isFromMock":false}
  22. let latitude = location.latitude
  23. let longitude = location.longitude
  24. let maxItems = 1
  25. let reverseGeocodeReq = {'latitude':latitude,'longitude':longitude,'maxItems':maxItems}
  26. //根据坐标转化为地理描述
  27. geoLocationManager.getAddressesFromLocation(reverseGeocodeReq,(err,val) => {
  28. if (err) {
  29. console.log('location getAddressesFromLocation err = '+JSON.stringify(err))
  30. //这里一直报错,怀疑是模拟器的问题。看错误code说可能网络问题需要重试,但是重试多次还是如下报错,如果可以还是用真机试试
  31. //{"code":3301300,"message":"BussinessError 3301300: Reverse geocoding query failed."}
  32. }
  33. if (val) {
  34. console.log('location getAddressesFromLocation = '+JSON.stringify(val))
  35. }
  36. })
  37. //获取国家码
  38. geoLocationManager.getCountryCode((err,val) => {
  39. if (err) {
  40. console.log('location getCountryCode err = '+JSON.stringify(err))
  41. }
  42. if (val) {
  43. console.log('location getCountryCode = '+JSON.stringify(val))
  44. //location getCountryCode = {"country":"CN","type":4}
  45. }
  46. })
  47. }
  48. })
  49. } catch (err) {
  50. console.log('location getCurrentLocation catch err = '+JSON.stringify(err))
  51. }
  52. }).catch(err => {
  53. console.error("location permission errCode:" + err.code + ",errMessage:" + err.message)
  54. })
  55. }

五、ets中全部代码

  1. import geoLocationManager from '@ohos.geoLocationManager';
  2. import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
  3. import bundleManager from '@ohos.bundle.bundleManager';
  4. import common from '@ohos.app.ability.common';
  5. @Entry
  6. @Component
  7. struct OfficialLocationPage {
  8. @State message: string = '开始定位'
  9. build() {
  10. Row() {
  11. Column() {
  12. Text(this.message)
  13. .fontSize(18)
  14. .fontWeight(FontWeight.Bold)
  15. .onClick(() => {
  16. this.startLocate()
  17. })
  18. }
  19. .width('100%')
  20. }
  21. .height('100%')
  22. }
  23. async accessToken(permission: Permissions): Promise<abilityAccessCtrl.GrantStatus> {
  24. let atManager = abilityAccessCtrl.createAtManager()
  25. let grantStatus: abilityAccessCtrl.GrantStatus
  26. let tokenID: number
  27. try {
  28. let bundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION)
  29. tokenID = bundleInfo.appInfo.accessTokenId
  30. } catch (err) {
  31. console.log('location 获取地理位置token失败')
  32. }
  33. try {
  34. grantStatus = await atManager.checkAccessToken(tokenID,permission)
  35. } catch (err) {
  36. console.log('获取地理位置token检测失败')
  37. }
  38. return grantStatus
  39. }
  40. async checkPermission() {
  41. let permissions: Array<Permissions> = ['ohos.permission.LOCATION','ohos.permission.APPROXIMATELY_LOCATION']
  42. let locationStatus = await this.accessToken(permissions[0])
  43. let roximateyStatus = await this.accessToken(permissions[1])
  44. if (locationStatus == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED &&
  45. roximateyStatus == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
  46. console.log('location 已经申请完权限了')
  47. } else {
  48. console.log('location 需要申请权限')
  49. this.requestPermission()
  50. }
  51. }
  52. requestPermission() {
  53. let atManager = abilityAccessCtrl.createAtManager()
  54. let permissions: Array<Permissions> = ['ohos.permission.LOCATION','ohos.permission.APPROXIMATELY_LOCATION']
  55. atManager.requestPermissionsFromUser(getContext(this),permissions,(err,permissionResult) => {
  56. if (err) {
  57. console.log('申请权限失败')
  58. return
  59. }
  60. let grantStatus: Array<number> = permissionResult.authResults
  61. let grantPermissions: Array<string> = permissionResult.permissions
  62. let length: number = grantStatus.length
  63. console.log('location user permissioned length' + JSON.stringify(grantPermissions)+length)
  64. for(let i = 0; i<length; i++) {
  65. if (grantStatus[i] === 0) {
  66. console.log('location user has agreed permissioned')
  67. } else {
  68. console.log('location user has disagree permissioned')
  69. this.openPermissionSettings()
  70. }
  71. }
  72. })
  73. }
  74. /*
  75. * 跳转到权限设置页面
  76. * */
  77. openPermissionSettings() {
  78. let context = getContext(this) as common.UIAbilityContext
  79. let wantInfo = {
  80. action: 'action.settings.app.info',
  81. parameters: {
  82. settingsParamBundleName: 'com.example.myapplication'
  83. }
  84. }
  85. context.startAbility(wantInfo).then(() => {
  86. console.log('location open setting page')
  87. }).catch((err) => {
  88. console.log('location open setting page failed')
  89. })
  90. }
  91. startLocate() {
  92. this.checkPermission().then(() => {
  93. let requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
  94. let locationChange = (location) => {
  95. console.log('location change:data = '+JSON.stringify(location))
  96. }
  97. try {
  98. geoLocationManager.on('locationChange',requestInfo,locationChange)
  99. } catch (err) {
  100. console.error("location change errCode:" + err.code + ",errMessage:" + err.message)
  101. }
  102. try {
  103. //获取当前的地理位置
  104. geoLocationManager.getCurrentLocation((err,location) => {
  105. if (err) {
  106. console.log('location getCurrentLocation err = '+JSON.stringify(err))
  107. }
  108. if (location) {
  109. console.log('location getCurrentLocation = '+JSON.stringify(location))
  110. //{"latitude":40,"longitude":116,"altitude":43.5,"accuracy":5,"speed":0,"timeStamp":1704176491,"direction":45,"timeSinceBoot":13563917977759,"additions":"","additionSize":0,"isFromMock":false}
  111. let latitude = location.latitude
  112. let longitude = location.longitude
  113. let maxItems = 1
  114. let reverseGeocodeReq = {'latitude':latitude,'longitude':longitude,'maxItems':maxItems}
  115. //根据坐标转化为地理描述
  116. geoLocationManager.getAddressesFromLocation(reverseGeocodeReq,(err,val) => {
  117. if (err) {
  118. console.log('location getAddressesFromLocation err = '+JSON.stringify(err))
  119. //{"code":3301300,"message":"BussinessError 3301300: Reverse geocoding query failed."}
  120. }
  121. if (val) {
  122. console.log('location getAddressesFromLocation = '+JSON.stringify(val))
  123. }
  124. })
  125. //获取国家码
  126. geoLocationManager.getCountryCode((err,val) => {
  127. if (err) {
  128. console.log('location getCountryCode err = '+JSON.stringify(err))
  129. }
  130. if (val) {
  131. console.log('location getCountryCode = '+JSON.stringify(val))
  132. //location getCountryCode = {"country":"CN","type":4}
  133. }
  134. })
  135. }
  136. })
  137. } catch (err) {
  138. console.log('location getCurrentLocation catch err = '+JSON.stringify(err))
  139. }
  140. }).catch(err => {
  141. console.error("location permission errCode:" + err.code + ",errMessage:" + err.message)
  142. })
  143. }
  144. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/247672
推荐阅读
相关标签
  

闽ICP备14008679号