HarmonyOS使用Java获取位置信息

开发 后端 OpenHarmony
随着科技时代的发展,生活中每个人都离不开手机,今天我们就来讲解一下HarmonyOS 如何使用Java UI框架获取手机位置权限并拿到位置信息。

[[419999]]

想了解更多内容,请访问:

51CTO和华为官方合作共建的鸿蒙技术社区

https://harmonyos.51cto.com

前言

随着科技时代的发展,生活中每个人都离不开手机,当我们去一个陌生的地方,不认识路怎么办,大家都会想到手机里的百度地图、高德地图等等。生活中我们不想做饭也不想出门的时候,我们会想到美团,那么美团APP怎么知道你的位置信息呢?当你进入app时,页面中就会提示你是否允许获取位置信息,当你点击允许时,就会把位置信息展示在页面中。今天我们就来讲解一下HarmonyOS 如何使用Java UI框架获取手机位置权限并拿到位置信息。

使用DevEco Studio 创建空项目,选择java模板

File => New Project

【中软国际】HarmonyOS  使用Java获取位置信息-鸿蒙HarmonyOS技术社区
【中软国际】HarmonyOS  使用Java获取位置信息-鸿蒙HarmonyOS技术社区

编写基础布局

  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="点击获取定位" 
  55.         ohos:padding="10vp" 
  56.         ohos:background_element="green" 
  57.         ohos:text_alignment="vertical_center" 
  58.         ohos:text_size="28fp"/> 
  59. </DirectionalLayout> 

日志工具类 LogUtil

写好布局后,我们先准备一个日志工具类,用于打印日志。

  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.     } 

配置位置权限 config.js

位置信息属于敏感信息,使用之前我们需要申请权限

  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; // 定义常量 用来表示请求码 
  6.     // 创建一个静态成员变量 数据共享 
  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.         // 动态判断权限 
  14.         if (verifySelfPermission("ohos.permission.LOCATION") != IBundleManager.PERMISSION_GRANTED) { 
  15.             // 应用未被授予权限 
  16.             if (canRequestPermission("ohos.permission.LOCATION")) { 
  17.                 // 是否可以申请弹框授权(首次申请或者用户未选择禁止且不再提示) 
  18.                 requestPermissionsFromUser(new String[]{"ohos.permission.LOCATION"}, REQUEST_LOCATION_CODE); 
  19.                 LogUtil.info("canRequestPermission() running"); 
  20.             } else { 
  21.                 // 显示应用需要权限的理由,提示用户进入设置授权 
  22.                 LogUtil.info("显示应用需要权限的理由"); 
  23.             } 
  24.         } else { 
  25.             initLocator(); 
  26.             // 权限已被授予 
  27.             LogUtil.info("权限已被授予,直接启动服务"); 
  28.         } 
  29.  
  30.     } 
  31.  
  32.     @Override // 权限操作调用的方法 
  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权限被授予"); 
  41.                     // 权限被授予 
  42.                     // 注意:因时间差导致接口权限检查时有无权限,所以对那些因无权限而抛异常的接口进行异常捕获处理 
  43.                     initLocator(); 
  44.                 } else { 
  45.                     // 权限被拒绝 
  46.                     LogUtil.info("onRequestPermissionsFromUserResult权限被拒绝"); 
  47.                 } 
  48.                 return
  49.             } 
  50.         } 
  51.     } 
  52.  
  53.     private void initLocator() { 
  54.         locator = new Locator(this); // 创建local对象 
  55.         // 实例化RequestParam对象,用于告知系统该向应用提供何种类型的位置服务,以及位置结果上报的频率。 
  56.         requestParam = new RequestParam(RequestParam.SCENE_NAVIGATION); 
  57.         // 实现 locatorCallback 接口对象 
  58.         locatorCallback = new MyLocatorCallback(); 
  59.         // locator.requestOnce(requestParam, locatorCallback); // 请求一次 
  60.         locator.startLocating(requestParam, locatorCallback); // 多次请求 直接启动服务 
  61.     } 
  62.  
  63.     @Override 
  64.     protected void onStop() { 
  65.         super.onStop(); 
  66.         locator.stopLocating(locatorCallback); // 程序结束 停止服务 
  67.     } 
  68.  
  69.     // 创建MyLocatorCallback类,实现LocatorCallback接口,用于执行定位过程的回调方法 
  70.     public class MyLocatorCallback implements LocatorCallback { 
  71.         @Override // 获取定位结果 
  72.         public void onLocationReport(Location location) { // 使用静态成员变量 进行分享 
  73.             LogUtil.info("onLocationReport:" + location.getLongitude() + "," + location.getLatitude()); 
  74.             if (location != null) { 
  75.                 MainAbility.location = location; 
  76.             } 
  77.         } 
  78.  
  79.         @Override // 获取定位过程中的状态信息 
  80.         public void onStatusChanged(int type) { 
  81.             LogUtil.info("onStatusChanged:" + type); 
  82.  
  83.         } 
  84.  
  85.         @Override // 获取定位过程中的错误信息 
  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,用于数据绑定 
  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("经度:"+location.getLongitude() +""); 
  33.                 t_Latitude.setText("纬度:"+location.getLatitude() +""); 
  34.                 // (逆)地理编码转换 
  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.     } 

实现效果图如下:

【中软国际】HarmonyOS  使用Java获取位置信息-鸿蒙HarmonyOS技术社区

想了解更多内容,请访问:

51CTO和华为官方合作共建的鸿蒙技术社区

https://harmonyos.51cto.com

 

责任编辑:jianghua 来源: 鸿蒙社区
相关推荐

2011-10-05 02:16:02

苹果iOSFamily and

2012-03-01 10:28:09

2019-03-26 08:18:44

位置信息物联网IOT

2011-04-27 15:32:27

用户地理位置信息苹果谷歌

2018-01-16 16:01:10

Google Chro手动位置

2021-03-13 09:43:45

Find My漏洞网络安全

2013-04-15 17:18:51

微信公众平台Android开发位置信息识别

2014-09-29 16:39:43

儿童智能手环智能设备安全

2011-05-03 09:28:26

位置信息LBSAndroid

2011-05-11 09:33:09

位置信息LBSWindows Pho

2011-10-11 10:56:45

北京一卡通用户信息

2020-06-12 16:13:23

物联网设备地理位置物联网

2010-09-30 15:24:31

滚动条Javascript

2017-10-31 14:58:11

Spring Clou配置信息问题

2022-08-25 21:46:51

网络通讯应用开发

2016-10-24 08:43:36

2011-08-08 18:26:52

UIWebView图片

2019-09-24 16:15:03

架构配置代码

2010-02-04 16:57:40

Android配置信息

2017-08-14 18:40:07

大数据数据可视化
点赞
收藏

51CTO技术栈公众号