位置服务
1、首先申请权限
在module.json5文件下申请位置权限
"requestPermissions": [
{
"name": "ohos.permission.LOCATION", // 权限名称,为系统已定义的权限
"reason": "$string:location_reason", // 申请权限的原因,当申请权限为user_grant权限时该字段为必填
"usedScene": {
// 用于描述权限使用场景,当申请权限为user_grant权限时该字段为必填
"abilities": [
"EntryAbility"
],
"when": "always" // 调用时机(inuse:使用时;always:始终)
}
},
{
"name": "ohos.permission.APPROXIMATELY_LOCATION",
"reason": "$string:location_reason",
"usedScene": {
"abilities": [
"EntryAbility"
],
"when": "always"
}
}
]
$string:location_reason
会爆红,就需要在
文件下定义一下,
2、导入需要的包
import {
abilityAccessCtrl, common, Permissions } from '@kit.AbilityKit';
import {
BusinessError } from '@kit.BasicServicesKit';
import {
geoLocationManager } from '@kit.LocationKit';
3、看一下用户是否授权,没有授权拉起弹窗让用户授权
const permissions: Array<Permissions> = ['ohos.permission.LOCATION'];
// 使用UIExtensionAbility:将common.UIAbilityContext 替换为common.UIExtensionContext
export function reqPermissionsFromUser(permissions: Array<Permissions>, context: common.UIAbilityContext): void {
let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
// requestPermissionsFromUser会判断权限的授权状态来决定是否唤起弹窗
atManager.requestPermissionsFromUser(context, permissions).then((data) => {
let grantStatus