1. HarmonyOS 获取位置信息
1.1. 官方文档
权限申请
位置服务
1.2. 权限申请
1.2.1. 配置位置权限信息
"requestPermissions": [
//API9之前只申请这个就可以米级定位
{'name': 'ohos.permission.LOCATION'},//API9之前申请的权限
//API9后两个权限同时申请才可以获取米级定位,只下边一个权限只能精准到5公里
{'name': 'ohos.permission.APPROXIMATELY_LOCATION'},//API9及之后需要增加申请的权限
{
"name": 'ohos.permission.LOCATION_IN_BACKGROUND'
}
],
1.2.2. 权限申请
访问设备的位置信息,必须申请权限,并且获得用户授权(src/main/ets/entryability/EntryAbility.ts里申请)
import abilityAccessCtrl from '@ohos.abilityAccessCtrl'
async onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): Promise<void> {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
let manger = abilityAccessCtrl.createAtManager()
try {
await manger.requestPermissionsFromUser(this.context,
[
'ohos.permission.MEDIA_LOCATION',
'ohos.permission.LOCATION',
'ohos.permission.APPROXIMATELY_LOCATION',
])
} catch (err) {
promptAction.showToast({ message: '获取位置信息失败!' })
}
}
1.3. 逻辑代码
import UIAbility from '@ohos.app.ability.UIAbility';
import hilog from '@ohos.hilog';
import window from '@ohos.window';
import abilityAccessCtrl from '@ohos.abilityAccessCtrl'
import promptAction from '@ohos.promptAction';
export default class EntryAbility extends UIAbility {
async onCreate(want, launchParam) {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
let manger = abilityAccessCtrl.createAtManager()
try {
await manger.requestPermissionsFromUser(this.context,
[
'ohos.permission.MEDIA_LOCATION',
'ohos.permission.LOCATION',
'ohos.permission.APPROXIMATELY_LOCATION',
])
} catch (err) {
console.log( '获取位置信息失败!'+err);
promptAction.showToast({ message: '获取位置信息失败!' })
}
}
onDestroy() {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
}
onWindowStageCreate(windowStage: window.WindowStage) {
// Main window is created, set main page for this ability
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
windowStage.loadContent('pages/Main', (err, data) => {
if (err.code) {
hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
return;
}
hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
});
}
onWindowStageDestroy() {
// Main window is destroyed, release UI related resources
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
}
onForeground() {
// Ability has brought to foreground
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
}
onBackground() {
// Ability has back to background
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
}
}