自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

HarmonyOS使用Java獲取位置信息

開發(fā) 后端 OpenHarmony
隨著科技時(shí)代的發(fā)展,生活中每個(gè)人都離不開手機(jī),今天我們就來講解一下HarmonyOS 如何使用Java UI框架獲取手機(jī)位置權(quán)限并拿到位置信息。

[[419999]]

想了解更多內(nèi)容,請(qǐng)?jiān)L問:

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

https://harmonyos.51cto.com

前言

隨著科技時(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

【中軟國際】HarmonyOS  使用Java獲取位置信息-鴻蒙HarmonyOS技術(shù)社區(qū)
【中軟國際】HarmonyOS  使用Java獲取位置信息-鴻蒙HarmonyOS技術(shù)社區(qū)

編寫基礎(chǔ)布局

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <DirectionalLayout 
  3.     xmlns:ohos="http://schemas.huawei.com/res/ohos" 
  4.     ohos:height="match_parent" 
  5.     ohos:width="match_parent" 
  6.     ohos:alignment="top|center" 
  7.     ohos:orientation="vertical"
  8.  
  9.     <Text 
  10.         ohos:id="$+id:T_Longitude" 
  11.         ohos:height="match_content" 
  12.         ohos:width="match_parent" 
  13.         ohos:background_element="green" 
  14.         ohos:margin="10vp" 
  15.         ohos:padding="10vp" 
  16.         ohos:text="--" 
  17.         ohos:text_alignment="left|vertical_center" 
  18.         ohos:text_size="28fp"/> 
  19.     <Text 
  20.         ohos:id="$+id:T_Latitude" 
  21.         ohos:height="match_content" 
  22.         ohos:width="match_parent" 
  23.         ohos:margin="10vp" 
  24.         ohos:padding="10vp" 
  25.         ohos:background_element="green" 
  26.         ohos:text="--" 
  27.         ohos:text_alignment="left|vertical_center" 
  28.         ohos:text_size="28fp"/> 
  29.     <Text 
  30.         ohos:id="$+id:T_country" 
  31.         ohos:height="match_content" 
  32.         ohos:width="match_parent" 
  33.         ohos:margin="10vp" 
  34.         ohos:padding="10vp" 
  35.         ohos:background_element="green" 
  36.         ohos:text="--" 
  37.         ohos:text_alignment="left|vertical_center" 
  38.         ohos:text_size="28fp"/> 
  39.     <Text 
  40.         ohos:id="$+id:T_PlaceName" 
  41.         ohos:height="match_content" 
  42.         ohos:width="match_parent" 
  43.         ohos:margin="10vp" 
  44.         ohos:multiple_lines="true" 
  45.         ohos:padding="10vp" 
  46.         ohos:background_element="green" 
  47.         ohos:text="--" 
  48.         ohos:text_alignment="left|vertical_center" 
  49.         ohos:text_size="28fp"/> 
  50.     <Button 
  51.         ohos:id="$+id:btn_location" 
  52.         ohos:height="match_content" 
  53.         ohos:width="match_content" 
  54.         ohos:text="點(diǎn)擊獲取定位" 
  55.         ohos:padding="10vp" 
  56.         ohos:background_element="green" 
  57.         ohos:text_alignment="vertical_center" 
  58.         ohos:text_size="28fp"/> 
  59. </DirectionalLayout> 

日志工具類 LogUtil

寫好布局后,我們先準(zhǔn)備一個(gè)日志工具類,用于打印日志。

  1. /** 
  2.  *日志工具類 
  3.  */ 
  4. public class LogUtil { 
  5.    static HiLogLabel hiLogLabel = new HiLogLabel(HiLog.LOG_APP,233,"LOCATION_TAG"); 
  6.     public static void info(String content){ 
  7.         HiLog.info(hiLogLabel,content); 
  8.  
  9.     } public static void error(String content){ 
  10.         HiLog.info(hiLogLabel,content); 
  11.  
  12.     } public static void debug(String content){ 
  13.         HiLog.info(hiLogLabel,content); 
  14.     } 

配置位置權(quán)限 config.js

位置信息屬于敏感信息,使用之前我們需要申請(qǐng)權(quán)限

  1. "reqPermissions": [ 
  2.      { 
  3.        "name""ohos.permission.LOCATION"
  4.        "reason"""
  5.        "usedScene": { 
  6.          "ability": ["com.example.location.MainAbility"], 
  7.          "when""inuse" 
  8.        } 
  9.      } 
  10.    ] 

MainAbility 中獲取位置信息

  1. public class MainAbility extends Ability { 
  2.     Locator locator; 
  3.     MyLocatorCallback locatorCallback; 
  4.     RequestParam requestParam; 
  5.     final int REQUEST_LOCATION_CODE = 12; // 定義常量 用來表示請(qǐng)求碼 
  6.     // 創(chuàng)建一個(gè)靜態(tài)成員變量 數(shù)據(jù)共享 
  7.     public static Location location = null
  8.  
  9.     @Override 
  10.     public void onStart(Intent intent) { 
  11.         super.onStart(intent); 
  12.         super.setMainRoute(MainAbilitySlice.class.getName()); 
  13.         // 動(dòng)態(tài)判斷權(quán)限 
  14.         if (verifySelfPermission("ohos.permission.LOCATION") != IBundleManager.PERMISSION_GRANTED) { 
  15.             // 應(yīng)用未被授予權(quán)限 
  16.             if (canRequestPermission("ohos.permission.LOCATION")) { 
  17.                 // 是否可以申請(qǐng)彈框授權(quán)(首次申請(qǐng)或者用戶未選擇禁止且不再提示) 
  18.                 requestPermissionsFromUser(new String[]{"ohos.permission.LOCATION"}, REQUEST_LOCATION_CODE); 
  19.                 LogUtil.info("canRequestPermission() running"); 
  20.             } else { 
  21.                 // 顯示應(yīng)用需要權(quán)限的理由,提示用戶進(jìn)入設(shè)置授權(quán) 
  22.                 LogUtil.info("顯示應(yīng)用需要權(quán)限的理由"); 
  23.             } 
  24.         } else { 
  25.             initLocator(); 
  26.             // 權(quán)限已被授予 
  27.             LogUtil.info("權(quán)限已被授予,直接啟動(dòng)服務(wù)"); 
  28.         } 
  29.  
  30.     } 
  31.  
  32.     @Override // 權(quán)限操作調(diào)用的方法 
  33.     public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) { 
  34.         super.onRequestPermissionsFromUserResult(requestCode, permissions, grantResults); 
  35.         switch (requestCode) { 
  36.             case REQUEST_LOCATION_CODE: { 
  37.                 // 匹配requestPermissions的requestCode 
  38.                 if (grantResults.length > 0 
  39.                         && grantResults[0] == IBundleManager.PERMISSION_GRANTED) { 
  40.                     LogUtil.info("onRequestPermissionsFromUserResult權(quán)限被授予"); 
  41.                     // 權(quán)限被授予 
  42.                     // 注意:因時(shí)間差導(dǎo)致接口權(quán)限檢查時(shí)有無權(quán)限,所以對(duì)那些因無權(quán)限而拋異常的接口進(jìn)行異常捕獲處理 
  43.                     initLocator(); 
  44.                 } else { 
  45.                     // 權(quán)限被拒絕 
  46.                     LogUtil.info("onRequestPermissionsFromUserResult權(quán)限被拒絕"); 
  47.                 } 
  48.                 return
  49.             } 
  50.         } 
  51.     } 
  52.  
  53.     private void initLocator() { 
  54.         locator = new Locator(this); // 創(chuàng)建local對(duì)象 
  55.         // 實(shí)例化RequestParam對(duì)象,用于告知系統(tǒng)該向應(yīng)用提供何種類型的位置服務(wù),以及位置結(jié)果上報(bào)的頻率。 
  56.         requestParam = new RequestParam(RequestParam.SCENE_NAVIGATION); 
  57.         // 實(shí)現(xiàn) locatorCallback 接口對(duì)象 
  58.         locatorCallback = new MyLocatorCallback(); 
  59.         // locator.requestOnce(requestParam, locatorCallback); // 請(qǐng)求一次 
  60.         locator.startLocating(requestParam, locatorCallback); // 多次請(qǐng)求 直接啟動(dòng)服務(wù) 
  61.     } 
  62.  
  63.     @Override 
  64.     protected void onStop() { 
  65.         super.onStop(); 
  66.         locator.stopLocating(locatorCallback); // 程序結(jié)束 停止服務(wù) 
  67.     } 
  68.  
  69.     // 創(chuàng)建MyLocatorCallback類,實(shí)現(xiàn)LocatorCallback接口,用于執(zhí)行定位過程的回調(diào)方法 
  70.     public class MyLocatorCallback implements LocatorCallback { 
  71.         @Override // 獲取定位結(jié)果 
  72.         public void onLocationReport(Location location) { // 使用靜態(tài)成員變量 進(jìn)行分享 
  73.             LogUtil.info("onLocationReport:" + location.getLongitude() + "," + location.getLatitude()); 
  74.             if (location != null) { 
  75.                 MainAbility.location = location; 
  76.             } 
  77.         } 
  78.  
  79.         @Override // 獲取定位過程中的狀態(tài)信息 
  80.         public void onStatusChanged(int type) { 
  81.             LogUtil.info("onStatusChanged:" + type); 
  82.  
  83.         } 
  84.  
  85.         @Override // 獲取定位過程中的錯(cuò)誤信息 
  86.         public void onErrorReport(int type) { 
  87.             LogUtil.info("onErrorReport:" + type); 
  88.         } 
  89.     } 

更新視圖

通過以上操作,我們拿到了位置信息,接下來我們需要把位置信息渲染到視圖中

  1. public class MainAbilitySlice extends AbilitySlice { 
  2.     Text t_Longitude; 
  3.     Text t_Latitude; 
  4.     Text t_country; 
  5.     Text t_PlaceName; 
  6.  
  7.     @Override 
  8.     public void onStart(Intent intent) { 
  9.         super.onStart(intent); 
  10.         super.setUIContent(ResourceTable.Layout_ability_main); 
  11.         // 獲取UI布局中的id,用于數(shù)據(jù)綁定 
  12.         t_Longitude = (Text) findComponentById(ResourceTable.Id_T_Longitude); 
  13.         t_Latitude = (Text) findComponentById(ResourceTable.Id_T_Latitude); 
  14.         t_PlaceName = (Text) findComponentById(ResourceTable.Id_T_PlaceName); 
  15.         t_country = (Text) findComponentById(ResourceTable.Id_T_country); 
  16.  
  17.         findComponentById(ResourceTable.Id_btn_location).setClickedListener(new Component.ClickedListener() { 
  18.             @Override 
  19.             public void onClick(Component component) { 
  20.                 loadLocation(); 
  21.             } 
  22.         }); 
  23.     } 
  24.  
  25.     private void loadLocation(){ 
  26.         // 在UI線程中更新組件 
  27.         getUITaskDispatcher().asyncDispatch(new Runnable() { 
  28.             @Override 
  29.             public void run() { 
  30.                 // 是UI中的操作 
  31.                 if(location == null)return
  32.                 t_Longitude.setText("經(jīng)度:"+location.getLongitude() +""); 
  33.                 t_Latitude.setText("緯度:"+location.getLatitude() +""); 
  34.                 // (逆)地理編碼轉(zhuǎn)換 
  35.                 GeoConvert geoConvert = new GeoConvert(); 
  36.                 try { 
  37.                     List<GeoAddress> list = geoConvert.getAddressFromLocation(location.getLatitude(),location.getLongitude(),1); 
  38.                     GeoAddress geoAddress = list.get(0); 
  39.                     if(geoAddress == nullreturn
  40.                     t_PlaceName.setText("位置:"+geoAddress.getPlaceName()+""); 
  41.                     t_country.setText("國家:"+geoAddress.getCountryName()+""); 
  42.                 } catch (IOException e) { 
  43.                     e.printStackTrace(); 
  44.                 } 
  45.             } 
  46.         }); 
  47.     } 
  48.  
  49.     @Override 
  50.     public void onActive() { 
  51.         super.onActive(); 
  52.     } 
  53.  
  54.     @Override 
  55.     public void onForeground(Intent intent) { 
  56.         super.onForeground(intent); 
  57.     } 

實(shí)現(xiàn)效果圖如下:

【中軟國際】HarmonyOS  使用Java獲取位置信息-鴻蒙HarmonyOS技術(shù)社區(qū)

想了解更多內(nèi)容,請(qǐng)?jiān)L問:

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

https://harmonyos.51cto.com

 

責(zé)任編輯:jianghua 來源: 鴻蒙社區(qū)
相關(guān)推薦

2012-03-01 10:28:09

2019-03-26 08:18:44

位置信息物聯(lián)網(wǎng)IOT

2011-10-05 02:16:02

蘋果iOSFamily and

2021-03-13 09:43:45

Find My漏洞網(wǎng)絡(luò)安全

2011-04-27 15:32:27

用戶地理位置信息蘋果谷歌

2018-01-16 16:01:10

Google Chro手動(dòng)位置

2013-04-15 17:18:51

微信公眾平臺(tái)Android開發(fā)位置信息識(shí)別

2011-05-11 09:33:09

位置信息LBSWindows Pho

2011-05-03 09:28:26

位置信息LBSAndroid

2011-10-11 10:56:45

北京一卡通用戶信息

2014-09-29 16:39:43

兒童智能手環(huán)智能設(shè)備安全

2020-06-12 16:13:23

物聯(lián)網(wǎng)設(shè)備地理位置物聯(lián)網(wǎng)

2024-10-30 15:49:30

2010-09-30 15:24:31

滾動(dòng)條Javascript

2017-10-31 14:58:11

Spring Clou配置信息問題

2024-07-09 08:37:13

2019-09-24 16:15:03

架構(gòu)配置代碼

2010-02-04 16:57:40

Android配置信息

2016-10-24 08:43:36

2011-08-08 18:26:52

UIWebView圖片
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)