当前位置: 首页 > 科技观察

HarmonyOS使用Java获取位置信息_0

时间:2023-03-12 01:36:21 科技观察

更多信息请访问:Harmonyos技术社区https://harmonyos.51cto.com前言随着科技时代的发展,生活中的每个人都离不开手机。当我们去到一个陌生的地方,不认识路的时候,大家就会想到手机里的百度地图、高德地图等。生活中,不想做饭不想出门的时候就会想到美团,那么美团APP是怎么知道你的位置信息的呢?当您进入应用程序时,页面会提示您是否允许访问位置信息。当您单击“允许”时,位置信息将显示在页面上。今天我们就来讲解HarmonyOS是如何使用JavaUI框架获取手机定位权限,获取位置信息的。使用DevEcoStudio创建空间项目,选择java模板File=>NewProject编写基础布局日志工具类LogUtil写好布局后,我们先准备一个日志工具类,用于打印日志/***日志工具类*/publicclassLogUtil{staticHiLogLabelhiLogLabel=newHiLogLabel(HiLog.LOG_APP,233,"LOCATION_TAG");publicstaticvoidinfo(Stringcontent){HiLog.info(hiLogLabel,content);}publicstaticvoiderror(Stringcontent){HiLog.info(hiLogLabel,content);}publicstaticvoiddebug(Stringcontent){HiLog.info(hiLogLabel,content);}}配置位置权限config.js位置信息属于敏感信息,使用前需要申请权限"reqPermissions":[{“名称”:“ohos.permission.LOCATION”,“原因”:“”,“usedScene”:{“能力”:[“com.example.location.MainAbility”],“何时”:“使用”}}]获取MainAbility信息中的locationpublicclassMainAbilityextendsAbility{Locatorlocator;MyLocatorCallbacklocatorCallback;RequestParamrequestParam;finalintREQUEST_LOCATION_CODE=12;//定义常量表示请求码//创建静态成员变量数据共享publicstaticLocationlocation=null;@OverridepublicvoidonStart(Intentintent).superent.onStart(setMainRoute(主要技能Slice.class.getName());//动态判断权限if(verifySelfPermission("ohos.permission.LOCATION")!=IBundleManager.PERMISSION_GRANTED){//应用没有被授予权限if(canRequestPermission("ohos.permission.LOCATION")){//是否可以申请pop-up授权(第一次申请或者用户没有选择禁止不再提示)requestPermissionsFromUser(newString[]{"ohos.permission.LOCATION"},REQUEST_LOCATION_CODE);LogUtil.info("canRequestPermission()running");}else{//显示应用需要权限的原因,提示用户输入设置授权LogUtil.info("显示应用需要权限的原因");}}else{initLocator();//已授予权限LogUtil.info("权限已授权,直接启动服务");}}@Override//权限操作调用的方法publicvoidonRequestPermissionsFromUserResult(intrequestCode,String[]permissions,int[]grantResults){super.onRequestPermissionsFromUserResult(requestCode,permissions,grantResults);switch(requestCode){caseREQUEST_LOCATION_CODE:{//匹配sionrequestPermirequestCodeif(grantResults.length>0&&grantResults[0]==IBundleManager.PERMISSION_GRANTED){LogUtil.info("onRequestPermissionsFromUserResultpermissionisgranted");//Permissionisgranted//注意:由于时差原因,此时没有权限检查接口权限,所以出于这些原因未经许可抛出异常的接口执行异常捕获处理initLocator();}else{//PermissiondeniedLogUtil.info("onRequestPermissionsFromUserResultpermissiondenied");}return;}}}privatevoidinitLocator(){locator=newLocator(this);//创建本地对象//实例化RequestParam对象,用于告诉系统向应用程序提供什么类型的定位服务,以及定位结果上报的频率requestParam=newRequestParam(RequestParam.SCENE_NAVIGATION);//实现locatorCallback接口对象locatorCallback=newMyLocatorCallback();//locator.requestOnce(requestParam,locatorCallback);//请求一次locator.startLocating(requestParam,locatorCallback);//多次请求启动直接服务}@OverrideprotectedvoidonStop(){super.onStop();locator.stopLocating(locatorCallback);//程序结束时停止服务}//创建MyLocatorCallback类,实现LocatorCallback接口,使用回调执行定位过程的方法publicclassMyLocatorCallbackimplementsLocatorCallback{@Override//获取定位结果publicvoidonLocationReport(Locationlocation){//使用静态成员变量共享LogUtil.info("onLocationReport:"+location.getLongitude()+","+location.getLatitude());if(location!=null){MainAbility.location=location;}}@Override//获取定位过程中的状态信息publicvoidonStatusChanged(inttype){LogUtil.info("onStatusChanged:"+type);}@Override//获取定位过程中的错误信息publicvoidonErrorReport(inttype){LogUtil.info("onErrorReport:"+type);}}}更新视图通过以上操作,我们已经获取到了位置信息,接下来我们需要将位置信息渲染到视图publicclassMainAbilitySliceextendsAbilitySlice{Textt_Longitude;Textt_Latitude;Textt_country;Textt_PlaceName;@OverridepublicvoidonStart(Intentintent){super.onStart(intent);super.setUIContent(ResourceTable.Layout_ability_main);//获取数据绑定的UI布局中的idt_Longitude=(Text)findComponentById(ResourceTable.Id_T_Longitude);t_Latitude=(文本)findComponentById(ResourceTable.Id_T_Latitude);t_PlaceName=(文本)findComponentById(ResourceTable.Id_T_PlaceName);t_country=(文本)findComponentById(ResourceTable.Id_T_T_PlaceName);t_country=(文本)findComponentById(ResourceTable.Id_T_T_PlaceName);.setClickedListener(newComponent.ClickedListener(){@OverridepublicvoidonClick(Componentcomponent){loadLocation();}});}privatevoidloadLocation(){//在UI线程更新组件getUITaskDispatcher().asyncDispatch(newRunnable(){@Overridepublicvoidrun(){//是UI中的操作if(location==null)return;t_Longitude.setText("longitude:"+location.getLongitude()+"");t_Latitude.setText("latitude:"+location.getLatitude()+"");//(逆向)地理编码转换GeoConvertgeoConvert=newGeoConvert();try{Listlist=geoConvert.getAddressFromLocation(location.getLatitude(),location.getLongitude(),1);GeoAddressgeoAddress=list.get(0);if(geoAddress==null)返回;t_PlaceName.setText("Place:"+geoAddress.getPlaceName()+"");t_country.setText("Country:"+geoAddress.getCountryName()+"");}catch(IOExceptione){e.printStackTrace();}}});}@OverridepublicvoidonActive(){super.onActive();}@OverridepublicvoidonForeground(Intentintent){super.onForeground(intent);}}实现效果图如下:更多信息请访问:和华为Harmonyos官方技术社区https://harmonyos.51cto.com