前言
随着科技时代的发展,生活中每个人都离不开手机,当我们去一个陌生的地方,不认识路怎么办,大家都会想到手机里的百度地图、高德地图等等。生活中我们不想做饭也不想出门的时候,我们会想到美团,那么美团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);
- }
- }
实现效果图如下: