HarmonyOS使用Java獲取位置信息
51CTO和華為官方合作共建的鴻蒙技術(shù)社區(qū)
前言
隨著科技時(shí)代的發(fā)展,生活中每個(gè)人都離不開手機(jī),當(dāng)我們?nèi)ヒ粋€(gè)陌生的地方,不認(rèn)識(shí)路怎么辦,大家都會(huì)想到手機(jī)里的百度地圖、高德地圖等等。生活中我們不想做飯也不想出門的時(shí)候,我們會(huì)想到美團(tuán),那么美團(tuán)APP怎么知道你的位置信息呢?當(dāng)你進(jìn)入app時(shí),頁面中就會(huì)提示你是否允許獲取位置信息,當(dāng)你點(diǎn)擊允許時(shí),就會(huì)把位置信息展示在頁面中。今天我們就來講解一下HarmonyOS 如何使用Java UI框架獲取手機(jī)位置權(quán)限并拿到位置信息。
使用DevEco Studio 創(chuàng)建空項(xiàng)目,選擇java模板
File => New Project


編寫基礎(chǔ)布局
- <?xml version="1.0" encoding="utf-8"?>
- <DirectionalLayout
- xmlns:ohos="http://schemas.huawei.com/res/ohos"
- ohos:height="match_parent"
- ohos:width="match_parent"
- ohos:alignment="top|center"
- ohos:orientation="vertical">
- <Text
- ohos:id="$+id:T_Longitude"
- ohos:height="match_content"
- ohos:width="match_parent"
- ohos:background_element="green"
- ohos:margin="10vp"
- ohos:padding="10vp"
- ohos:text="--"
- ohos:text_alignment="left|vertical_center"
- ohos:text_size="28fp"/>
- <Text
- ohos:id="$+id:T_Latitude"
- ohos:height="match_content"
- ohos:width="match_parent"
- ohos:margin="10vp"
- ohos:padding="10vp"
- ohos:background_element="green"
- ohos:text="--"
- ohos:text_alignment="left|vertical_center"
- ohos:text_size="28fp"/>
- <Text
- ohos:id="$+id:T_country"
- ohos:height="match_content"
- ohos:width="match_parent"
- ohos:margin="10vp"
- ohos:padding="10vp"
- ohos:background_element="green"
- ohos:text="--"
- ohos:text_alignment="left|vertical_center"
- ohos:text_size="28fp"/>
- <Text
- ohos:id="$+id:T_PlaceName"
- ohos:height="match_content"
- ohos:width="match_parent"
- ohos:margin="10vp"
- ohos:multiple_lines="true"
- ohos:padding="10vp"
- ohos:background_element="green"
- ohos:text="--"
- ohos:text_alignment="left|vertical_center"
- ohos:text_size="28fp"/>
- <Button
- ohos:id="$+id:btn_location"
- ohos:height="match_content"
- ohos:width="match_content"
- ohos:text="點(diǎn)擊獲取定位"
- ohos:padding="10vp"
- ohos:background_element="green"
- ohos:text_alignment="vertical_center"
- ohos:text_size="28fp"/>
- </DirectionalLayout>
日志工具類 LogUtil
寫好布局后,我們先準(zhǔn)備一個(gè)日志工具類,用于打印日志。
- /**
- *日志工具類
- */
- public class LogUtil {
- static HiLogLabel hiLogLabel = new HiLogLabel(HiLog.LOG_APP,233,"LOCATION_TAG");
- public static void info(String content){
- HiLog.info(hiLogLabel,content);
- } public static void error(String content){
- HiLog.info(hiLogLabel,content);
- } public static void debug(String content){
- HiLog.info(hiLogLabel,content);
- }
- }
配置位置權(quán)限 config.js
位置信息屬于敏感信息,使用之前我們需要申請(qǐng)權(quán)限
- "reqPermissions": [
- {
- "name": "ohos.permission.LOCATION",
- "reason": "",
- "usedScene": {
- "ability": ["com.example.location.MainAbility"],
- "when": "inuse"
- }
- }
- ]
MainAbility 中獲取位置信息
- public class MainAbility extends Ability {
- Locator locator;
- MyLocatorCallback locatorCallback;
- RequestParam requestParam;
- final int REQUEST_LOCATION_CODE = 12; // 定義常量 用來表示請(qǐng)求碼
- // 創(chuàng)建一個(gè)靜態(tài)成員變量 數(shù)據(jù)共享
- public static Location location = null;
- @Override
- public void onStart(Intent intent) {
- super.onStart(intent);
- super.setMainRoute(MainAbilitySlice.class.getName());
- // 動(dòng)態(tài)判斷權(quán)限
- if (verifySelfPermission("ohos.permission.LOCATION") != IBundleManager.PERMISSION_GRANTED) {
- // 應(yīng)用未被授予權(quán)限
- if (canRequestPermission("ohos.permission.LOCATION")) {
- // 是否可以申請(qǐng)彈框授權(quán)(首次申請(qǐng)或者用戶未選擇禁止且不再提示)
- requestPermissionsFromUser(new String[]{"ohos.permission.LOCATION"}, REQUEST_LOCATION_CODE);
- LogUtil.info("canRequestPermission() running");
- } else {
- // 顯示應(yīng)用需要權(quán)限的理由,提示用戶進(jìn)入設(shè)置授權(quán)
- LogUtil.info("顯示應(yīng)用需要權(quán)限的理由");
- }
- } else {
- initLocator();
- // 權(quán)限已被授予
- LogUtil.info("權(quán)限已被授予,直接啟動(dòng)服務(wù)");
- }
- }
- @Override // 權(quán)限操作調(diào)用的方法
- public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
- super.onRequestPermissionsFromUserResult(requestCode, permissions, grantResults);
- switch (requestCode) {
- case REQUEST_LOCATION_CODE: {
- // 匹配requestPermissions的requestCode
- if (grantResults.length > 0
- && grantResults[0] == IBundleManager.PERMISSION_GRANTED) {
- LogUtil.info("onRequestPermissionsFromUserResult權(quán)限被授予");
- // 權(quán)限被授予
- // 注意:因時(shí)間差導(dǎo)致接口權(quán)限檢查時(shí)有無權(quán)限,所以對(duì)那些因無權(quán)限而拋異常的接口進(jìn)行異常捕獲處理
- initLocator();
- } else {
- // 權(quán)限被拒絕
- LogUtil.info("onRequestPermissionsFromUserResult權(quán)限被拒絕");
- }
- return;
- }
- }
- }
- private void initLocator() {
- locator = new Locator(this); // 創(chuàng)建local對(duì)象
- // 實(shí)例化RequestParam對(duì)象,用于告知系統(tǒng)該向應(yīng)用提供何種類型的位置服務(wù),以及位置結(jié)果上報(bào)的頻率。
- requestParam = new RequestParam(RequestParam.SCENE_NAVIGATION);
- // 實(shí)現(xiàn) locatorCallback 接口對(duì)象
- locatorCallback = new MyLocatorCallback();
- // locator.requestOnce(requestParam, locatorCallback); // 請(qǐng)求一次
- locator.startLocating(requestParam, locatorCallback); // 多次請(qǐng)求 直接啟動(dòng)服務(wù)
- }
- @Override
- protected void onStop() {
- super.onStop();
- locator.stopLocating(locatorCallback); // 程序結(jié)束 停止服務(wù)
- }
- // 創(chuàng)建MyLocatorCallback類,實(shí)現(xiàn)LocatorCallback接口,用于執(zhí)行定位過程的回調(diào)方法
- public class MyLocatorCallback implements LocatorCallback {
- @Override // 獲取定位結(jié)果
- public void onLocationReport(Location location) { // 使用靜態(tài)成員變量 進(jìn)行分享
- LogUtil.info("onLocationReport:" + location.getLongitude() + "," + location.getLatitude());
- if (location != null) {
- MainAbility.location = location;
- }
- }
- @Override // 獲取定位過程中的狀態(tài)信息
- public void onStatusChanged(int type) {
- LogUtil.info("onStatusChanged:" + type);
- }
- @Override // 獲取定位過程中的錯(cuò)誤信息
- public void onErrorReport(int type) {
- LogUtil.info("onErrorReport:" + type);
- }
- }
- }
更新視圖
通過以上操作,我們拿到了位置信息,接下來我們需要把位置信息渲染到視圖中
- public class MainAbilitySlice extends AbilitySlice {
- Text t_Longitude;
- Text t_Latitude;
- Text t_country;
- Text t_PlaceName;
- @Override
- public void onStart(Intent intent) {
- super.onStart(intent);
- super.setUIContent(ResourceTable.Layout_ability_main);
- // 獲取UI布局中的id,用于數(shù)據(jù)綁定
- t_Longitude = (Text) findComponentById(ResourceTable.Id_T_Longitude);
- t_Latitude = (Text) findComponentById(ResourceTable.Id_T_Latitude);
- t_PlaceName = (Text) findComponentById(ResourceTable.Id_T_PlaceName);
- t_country = (Text) findComponentById(ResourceTable.Id_T_country);
- findComponentById(ResourceTable.Id_btn_location).setClickedListener(new Component.ClickedListener() {
- @Override
- public void onClick(Component component) {
- loadLocation();
- }
- });
- }
- private void loadLocation(){
- // 在UI線程中更新組件
- getUITaskDispatcher().asyncDispatch(new Runnable() {
- @Override
- public void run() {
- // 是UI中的操作
- if(location == null)return;
- t_Longitude.setText("經(jīng)度:"+location.getLongitude() +"");
- t_Latitude.setText("緯度:"+location.getLatitude() +"");
- // (逆)地理編碼轉(zhuǎn)換
- GeoConvert geoConvert = new GeoConvert();
- try {
- List<GeoAddress> list = geoConvert.getAddressFromLocation(location.getLatitude(),location.getLongitude(),1);
- GeoAddress geoAddress = list.get(0);
- if(geoAddress == null) return;
- t_PlaceName.setText("位置:"+geoAddress.getPlaceName()+"");
- t_country.setText("國家:"+geoAddress.getCountryName()+"");
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- });
- }
- @Override
- public void onActive() {
- super.onActive();
- }
- @Override
- public void onForeground(Intent intent) {
- super.onForeground(intent);
- }
- }
實(shí)現(xiàn)效果圖如下:

51CTO和華為官方合作共建的鴻蒙技術(shù)社區(qū)