問題描述
已經在config.json中加入了ohos.permission.LOCATION權限聲明,但是在實際開發中,我使用
geolocation.getCurrentLocation().then((result) => {
this.locationInfo = JSON.stringify(result);
this.blog.setTitle(this.locationInfo);
});
擷取位置資訊得不到結果
我使用的是API9FA模型,且手頭現沒有可供實機調試的API9裝置,遠端仿真裝置調試多次崩潰,是以我先将此錯誤情況梳理如下
我們使用了如下圖所示的兩種方式(注釋部分和未注釋部分,參考來源來自https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/security/accesstoken-guidelines.md#stage%E6%A8%A1%E5%9E%8B-1)均未能得到彈窗,經過實測在DevEco 3.1.0.500 Beta2版本中上述功能無法正常使用,且調試視窗在requestPermissionsFromUser()方法(經過調試運作已确認是執行到此函數時報錯)執行時傳回401錯誤
解決過程
與華為客戶服務工程師溝通後,梳理上述思路進行定位處理問題有三:
- 上述方法一中參考文檔來源于openHarmonyOS,與現行HarmonyOS不屬于同一部門維護,不保證可用性,例如上述方法在HarmonyOS内就無法正常使用
- HarmonyOS的SDK經過多次更新疊代,目前原先舊SDK已經全部棄用(401報錯原因)
- 上述問題僅屬于接口變更問題
解決方法
在SDK9版本中引入了geoLocationManager()的新調用方式,在config.json檔案中聲明ohos.permission.APPROXIMATELY_LOCATION和ohos.permission.LOCATION權限後,使用getCurrentLocation(request?: CurrentLocationRequest): Promise<Location>方法即可彈窗并獲得定位權限,下面給出我的例子,假設config.json中已經配置好所需權限和說明
擷取權限部分
let context = featureAbility.getContext();
let array:Array<string> = ["ohos.permission.APPROXIMATELY_LOCATION","ohos.permission.LOCATION"];
//requestPermissionsFromUser會判斷權限的授權狀态來決定是否喚起彈窗
context.requestPermissionsFromUser(array, 1).then(function(data) {
console.log("Permission data:" + JSON.stringify(data));
console.log("Permission data permissions:" + JSON.stringify(data.permissions));
console.log("Permission data result:" + JSON.stringify(data.authResults));
}, (err) => {
console.error('Failed to start ability', err.code);
});
擷取定位部分
try{
geoLocationManager.getCurrentLocation().then((result) => {
console.log('current location: ' + JSON.stringify(result));
}).catch((error) => {
console.error("locationerror=" + JSON.stringify(error));
});
}catch (err){
console.error("locationerrorCode:" + err.code + ",errMessage:" + err.message);
}
變更為上述函數與接口後順利彈窗并擷取到位置資訊
總結
- HarmonyOS接口變更還較為頻繁,文檔内部将各個SDK版本接口均羅列了出來,還需進一步完善分類
- ArkTS異步執行,擷取權限時需要處理好權限授權以及擷取定位的先後同步順序關系
- 通過側載JS的方式也可以利用第三方API擷取大緻的經緯度資訊,留給各位自行探究