HarmonyOS使用Java獲取位置信息
作者:王國菊
隨著科技時代的發展,生活中每個人都離不開手機,今天我們就來講解一下HarmonyOS 如何使用Java UI框架獲取手機位置權限并拿到位置信息。
前言
隨著科技時代的發展,生活中每個人都離不開手機,當我們去一個陌生的地方,不認識路怎么辦,大家都會想到手機里的百度地圖、高德地圖等等。生活中我們不想做飯也不想出門的時候,我們會想到美團,那么美團APP怎么知道你的位置信息呢?當你進入app時,頁面中就會提示你是否允許獲取位置信息,當你點擊允許時,就會把位置信息展示在頁面中。今天我們就來講解一下HarmonyOS 如何使用Java UI框架獲取手機位置權限并拿到位置信息。
使用DevEco Studio 創建空項目,選擇java模板
File => New Project


編寫基礎布局
- <?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="點擊獲取定位"
- ohos:padding="10vp"
- ohos:background_element="green"
- ohos:text_alignment="vertical_center"
- ohos:text_size="28fp"/>
- </DirectionalLayout>
日志工具類 LogUtil
寫好布局后,我們先準備一個日志工具類,用于打印日志。
- /**
- *日志工具類
- */
- 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);
- }
- }
配置位置權限 config.js
位置信息屬于敏感信息,使用之前我們需要申請權限
- "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; // 定義常量 用來表示請求碼
- // 創建一個靜態成員變量 數據共享
- public static Location location = null;
- @Override
- public void onStart(Intent intent) {
- super.onStart(intent);
- super.setMainRoute(MainAbilitySlice.class.getName());
- // 動態判斷權限
- if (verifySelfPermission("ohos.permission.LOCATION") != IBundleManager.PERMISSION_GRANTED) {
- // 應用未被授予權限
- if (canRequestPermission("ohos.permission.LOCATION")) {
- // 是否可以申請彈框授權(首次申請或者用戶未選擇禁止且不再提示)
- requestPermissionsFromUser(new String[]{"ohos.permission.LOCATION"}, REQUEST_LOCATION_CODE);
- LogUtil.info("canRequestPermission() running");
- } else {
- // 顯示應用需要權限的理由,提示用戶進入設置授權
- LogUtil.info("顯示應用需要權限的理由");
- }
- } else {
- initLocator();
- // 權限已被授予
- LogUtil.info("權限已被授予,直接啟動服務");
- }
- }
- @Override // 權限操作調用的方法
- 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權限被授予");
- // 權限被授予
- // 注意:因時間差導致接口權限檢查時有無權限,所以對那些因無權限而拋異常的接口進行異常捕獲處理
- initLocator();
- } else {
- // 權限被拒絕
- LogUtil.info("onRequestPermissionsFromUserResult權限被拒絕");
- }
- return;
- }
- }
- }
- private void initLocator() {
- locator = new Locator(this); // 創建local對象
- // 實例化RequestParam對象,用于告知系統該向應用提供何種類型的位置服務,以及位置結果上報的頻率。
- requestParam = new RequestParam(RequestParam.SCENE_NAVIGATION);
- // 實現 locatorCallback 接口對象
- locatorCallback = new MyLocatorCallback();
- // locator.requestOnce(requestParam, locatorCallback); // 請求一次
- locator.startLocating(requestParam, locatorCallback); // 多次請求 直接啟動服務
- }
- @Override
- protected void onStop() {
- super.onStop();
- locator.stopLocating(locatorCallback); // 程序結束 停止服務
- }
- // 創建MyLocatorCallback類,實現LocatorCallback接口,用于執行定位過程的回調方法
- public class MyLocatorCallback implements LocatorCallback {
- @Override // 獲取定位結果
- public void onLocationReport(Location location) { // 使用靜態成員變量 進行分享
- LogUtil.info("onLocationReport:" + location.getLongitude() + "," + location.getLatitude());
- if (location != null) {
- MainAbility.location = location;
- }
- }
- @Override // 獲取定位過程中的狀態信息
- public void onStatusChanged(int type) {
- LogUtil.info("onStatusChanged:" + type);
- }
- @Override // 獲取定位過程中的錯誤信息
- 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,用于數據綁定
- 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("經度:"+location.getLongitude() +"");
- t_Latitude.setText("緯度:"+location.getLatitude() +"");
- // (逆)地理編碼轉換
- 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);
- }
- }
實現效果圖如下:

責任編輯:jianghua
來源:
鴻蒙社區