查询是否已授权,再获取位置
import { geoLocationManager } from '@kit.LocationKit';
import { BusinessError } from '@kit.BasicServicesKit';
import abilityAccessCtrl, { PermissionRequestResult } from '@ohos.abilityAccessCtrl';
import { bundleManager, common } from '@kit.AbilityKit';
获取AccessToken
可以去程序服务控制管理去查询
getTokenID(){
let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION | bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_METADATA;
try {
bundleManager.getBundleInfoForSelf(bundleFlags).then((data) => {
const bundleInfo = data
this.accessTokenId = bundleInfo.appInfo.accessTokenId;
this.checkAccessToken()
}).catch((err: BusinessError) => {
console.error('getBundleInfoForSelf error',JSON.stringify(err))
});
} catch (err) {
console.error('fail error')
}
}
查询是否已授权
checkAccessToken(){
let atManager = abilityAccessCtrl.createAtManager();
try {
atManager.checkAccessToken(this.accessTokenId, "ohos.permission.APPROXIMATELY_LOCATION").then((data) => {
console.log('checkAccessToken success',data);
// -1 未授权,0 已授权
if(data === 0){
this.getCurrentLocation()
}else {
this.requestPermissionsFromUser()
}
}).catch((err:ESObject) => {
console.log('checkAccessToken success',JSON.stringify(err));
});
} catch(err) {
console.log(`catch err->${JSON.stringify(err)}`);
}
}
未授权
拉起弹窗(这个需要去AGC官网项目应用那里配置)
requestPermissionsFromUser(){
let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
let context: Context = getContext(this) as common.UIAbilityContext;
atManager.requestPermissionsFromUser(context, ['ohos.permission.APPROXIMATELY_LOCATION']).then((data: PermissionRequestResult) => {
console.info('requestPermissionsFromUser:' + JSON.stringify(data));
}).catch((err: BusinessError) => {
console.error('requestPermissionsFromUser:' + JSON.stringify(err));
});
}
已授权
getCurrentLocation(){
geoLocationManager.getCurrentLocation().then((result) => {
console.log('current location latitude: ' , JSON.stringify(result));
}).catch((err: BusinessError ) => {
console.error(`getCurrentLocation failed. Code: ${err.code}, message: ${err.message}`);
});
}