好好学习

扫一扫关注

HarmonyOS分布式应用智能三角警示牌解读

下载文本     硫磺君2022-09-28 12:41:26 25850

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

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

https://harmonyos.51cto.com

前言

HarmonyOS是 一款面向万物互联时代的、全新的分布式操作系统,其分布式技术能力(分布式软总线、分布式设备虚拟化、分布式数据管理、分布式任务调度)一直受到广大开发者的极大关注,使用户对HarmonyOS有着很高的赞许。

我们开发的《分布式智能三角警示牌应用》,以在日常生活中,公路上发生交通事故时通常是事故相关人员手持三角反光警示牌步行至目的地处放置,人为放置具有引发二次事故的风险,因此我们设计了智能移动三角警示牌以解决该问题。本智能三角警示牌通过手机HAP可以与其相连,控制运动方向和速度,使其停放在事故现场后方合适的位置,从而能够保障用户的人身和财产安全。

当在控制警示牌运动过程中,有紧急事情或其它情况,可以将当前的操作流转到另外一台设备中进行操作,其运动轨迹就是通过分布式数据服务来保证两台设备间数据的一致性。

效果展示
#星光计划2.0#HarmonyOS分布式应用智能三角警示牌解读-鸿蒙HarmonyOS技术社区
#星光计划2.0#HarmonyOS分布式应用智能三角警示牌解读-鸿蒙HarmonyOS技术社区
一、创建“智能三角警示牌”HAP工程1、安装和配置DevEco Studio

2.1 Release

安装的链接:https://developer.harmonyos.com/cn/develop/deveco-studio

IDE的使用指南,很详细:https://developer.harmonyos.com/cn/docs/documentation/doc-guides/tools_overview-0000001053582387

我的本案例使用的最新的 2.1.0.501版本,SDK:API Version 5

2、选择一个模版,创建一个Java Phone应用
#星光计划2.0#HarmonyOS分布式应用智能三角警示牌解读-鸿蒙HarmonyOS技术社区

==点击Next ==

#星光计划2.0#HarmonyOS分布式应用智能三角警示牌解读-鸿蒙HarmonyOS技术社区

点击Finish完成创建HAP工程

3、智能三角警示牌应用包结构

首先完成智能三角警示牌应用包结构设计,结构如下:

#星光计划2.0#HarmonyOS分布式应用智能三角警示牌解读-鸿蒙HarmonyOS技术社区 

二、智能三角警示牌应用核心代码实现1、config.json权限配置
  1. "reqPermissions": [       { 
  2.         "name": "ohos.permission.INTERNET"       }, 
  3.       {         "name": "ohos.permission.GET_NETWORK_INFO" 
  4.       },       { 
  5.         "name": "ohos.permission.MICROPHONE"       }, 
  6.       {         "name": "android.permission.RECORD_AUDIO" 
  7.       },       { 
  8.         "name": "ohos.permission.DISTRIBUTED_DATASYNC"       }, 
  9.       {         "name": "ohos.permission.servicebus.ACCESS_SERVICE" 
  10.       },       { 
  11.         "name": "com.huawei.hwddmp.servicebus.BIND_SERVICE"       }, 
  12.       {         "name": "ohos.permission.DISTRIBUTED_DEVICE_STATE_CHANGE" 
  13.       },       { 
  14.         "name": "ohos.permission.GET_DISTRIBUTED_DEVICE_INFO"       }, 
  15.       {         "name": "ohos.permission.GET_BUNDLE_INFO" 
  16.       },       { 
  17.         "name": "ohos.p ermission.LOCATION" 
  18.       }     ] 
2、分布式数据服务核心代码
  1. import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; 
  2. import com.isoftstone.smartcar.app.common.Constant; import com.isoftstone.smartcar.app.model.DrivingMap; 
  3. import com.isoftstone.smartcar.app.model.DrivingRecord; import com.isoftstone.smartcar.app.model.ReportRecord; 
  4. import com.isoftstone.smartcar.app.utils.DrivingReportComparator; import com.isoftstone.smartcar.app.utils.ReportRecordComparator; 
  5. import com.isoftstone.smartcar.app.utils.StringUtils; import ohos.app.Context; 
  6. import ohos.data.distributed.common.*; import ohos.data.distributed.device.DeviceFilterStrategy; 
  7. import ohos.data.distributed.device.DeviceInfo; import ohos.data.distributed.user.SingleKvStore; 
  8. import ohos.hiviewdfx.HiLog; import ohos.hiviewdfx.HiLogLabel; 
  9. import java.util.ArrayList; import java.util.List; 
  10.  public class SmartShareService { 
  11.     private static final HiLogLabel label = new HiLogLabel(HiLog.LOG_APP, 0x00201, "SmartshareService");     private static SmartShareService smartShareService; 
  12.     private static SingleKvStore singleKvStore;     private static KvManager kvManager; 
  13.     private final Context context;     public static SmartShareService getInstance(Context context) { 
  14.         if (smartShareService == null) {             smartShareService = new SmartShareService(context); 
  15.         }         return smartShareService; 
  16.     }     private SmartShareService(Context context){ 
  17.             this.context = context;     } 
  18.          public void init() { 
  19.         KvManagerConfig config = new KvManagerConfig(context);         kvManager = KvManagerFactory.getInstance().createKvManager(config); 
  20.         Options options = new Options();        options.setCreateIfMissing(true).setEncrypt(false).setKvStoreType(KvStoreType.SINGLE_VERSION).setAutoSync(true);         singleKvStore = kvManager.getKvStore(options, Constant.SMART_SHARE_NAME); 
  21.         HiLog.info(label,"初始化成功!");         //return singleKvStore; 
  22.     }          public void insertDrivingRecord(DrivingRecord drivingRecord){ 
  23.         Gson gson = new Gson();         String resultJson = gson.toJson(drivingRecord);        singleKvStore.putString(Constant.DRIVING_REPORT_PREFIX+drivingRecord.getId(),resultJson); 
  24.         HiLog.info(label,"新增行驶记录成功!");     } 
  25.          public void insertDrivingMap(String drivingId, List drivingMapLst){ 
  26.         Gson gson = new Gson();         String resultJson = gson.toJson(drivingMapLst);        singleKvStore.putString(Constant.DRIVING_MAP_PREFIX+drivingId,resultJson); 
  27.         HiLog.info(label,"批量新增行驶记录轨迹成功!");     } 
  28.          public void insertReportRecord(String drivingId, ReportRecord reportRecord){ 
  29.         Gson gson = new Gson();         List entrys = singleKvStore.getEntries(Constant.REPORT_RECORD_PREFIX+drivingId); 
  30.         if (entrys == null || entrys.size() == 0){             List reportRecordLst = new ArrayList<>(); 
  31.             reportRecordLst.add(reportRecord);             String resultJson1 = gson.toJson(reportRecordLst);            singleKvStore.putString(Constant.REPORT_RECORD_PREFIX+drivingId,resultJson1); 
  32.             HiLog.info(label,"新增上报记录成功!");         } else { 
  33.             String resultJson = entrys.get(0).getValue().getString();             List reportRecordLst = gson.fromJson(resultJson, new TypeToken>() {}.getType()); 
  34.             reportRecordLst.add(reportRecord);             String resultJson1 = gson.toJson(reportRecordLst); 
  35.             singleKvStore.putString(Constant.REPORT_RECORD_PREFIX+drivingId,resultJson1);             HiLog.info(label,"新增上报记录列表成功!"); 
  36.         }     } 
  37.          public void setupInsuranceTelphone(String key,String telphone){ 
  38.         singleKvStore.putString(Constant.TEL_PREFIX+key,telphone);         HiLog.info(label,"设置保险电话成功!"); 
  39.     }      
  40.     public String getInsuranceTelphone(String key){         String tel = ""; 
  41.         List entrys = singleKvStore.getEntries(Constant.TEL_PREFIX+key);         if (entrys != null && entrys.size()>0) { 
  42.             tel = entrys.get(0).getValue().getString();             HiLog.info(label,"获取保险电话成功!"+tel); 
  43.         } else {             HiLog.info(label,"没有获取保险电话!"); 
  44.         }         return tel; 
  45.     }      
  46.     public void setIp(String key,String value){         singleKvStore.putString(Constant.IP_PREFIX+key,value); 
  47.         HiLog.info(label,"设置IP成功!");     } 
  48.          public String getIp(String key){ 
  49.         String tmpIp = "";         List entrys = singleKvStore.getEntries(Constant.IP_PREFIX+key); 
  50.         if (entrys != null && entrys.size()>0) {             tmpIp = entrys.get(0).getValue().getString(); 
  51.             HiLog.info(label,"获取IP成功!"+tmpIp);         } else { 
  52.             HiLog.info(label,"没有获取到IP!");         } 
  53.         return tmpIp;     } 
  54.      
  55.     public List getDrivingRecords(){         List drivingReporList = new ArrayList<>(); 
  56.         List entrys = singleKvStore.getEntries(Constant.DRIVING_REPORT_PREFIX);         for(Entry entry:entrys){ 
  57.             String key = entry.getKey();             String value = entry.getValue().getString(); 
  58.             HiLog.info(label,"获取到行驶记录的数据:key:" + key+",value:"+value);             Gson gson = new Gson(); 
  59.             DrivingRecord drivingRecord = gson.fromJson(value, DrivingRecord.class);             //HiLog.info(label,drivingRecord.getId()); 
  60.             drivingReporList.add(drivingRecord);         } 
  61.         //排序         if (drivingReporList.size() > 0) { 
  62.             DrivingReportComparator drivingReportComparator = new DrivingReportComparator();             drivingReporList.sort(drivingReportComparator); 
  63.         }         return drivingReporList; 
  64.     }      
  65.     public List getDrivingMap(String drivingId){         String resultJson = singleKvStore.getString(Constant.DRIVING_MAP_PREFIX+drivingId); 
  66.         Gson gson = new Gson();  
  67.         return gson.fromJson(resultJson, new TypeToken>() {}.getType());     } 
  68.          public List getReportRecords(String drivingId){ 
  69.         List entrys = singleKvStore.getEntries(Constant.REPORT_RECORD_PREFIX+drivingId);         if (entrys == null || entrys.size() == 0){ 
  70.             HiLog.info(label,"获取上报记录为空!");             return null; 
  71.         } else {             Gson gson = new Gson(); 
  72.             Entry entry = entrys.get(0);             String resultJson = entry.getValue().getString(); 
  73.             List reportRecordLst = gson.fromJson(resultJson, new TypeToken>() {}.getType());             HiLog.info(label,"获取上报记录成功!"+reportRecordLst.size()); 
  74.              if (reportRecordLst!=null && reportRecordLst.size() > 0) { 
  75.                 //排序                 ReportRecordComparator reportRecordComparator = new ReportRecordComparator(); 
  76.                 reportRecordLst.sort(reportRecordComparator);             } 
  77.             return reportRecordLst;         } 
  78.     }      
  79.     public void syncData() {         List deviceInfoList = kvManager.getConnectedDevicesInfo(DeviceFilterStrategy.NO_FILTER); 
  80.         List deviceIdList = new ArrayList<>();         String deviceId; 
  81.         for (DeviceInfo deviceInfo : deviceInfoList) {             deviceId = deviceInfo.getId(); 
  82.             HiLog.info(label,"deviceId = " + deviceId);             deviceIdList.add(deviceId); 
  83.         }         HiLog.info(label,"deviceIdList.size() = " + deviceIdList.size()); 
  84.         if (deviceIdList.size() > 0) {             singleKvStore.sync(deviceIdList, SyncMode.PUSH_ONLY); 
  85.         } else {             HiLog.error(label,"没有共享设备"); 
  86.         }     } 
  87.      
  88.     public void registerCallback(KvStoreObserver kvStoreObserver) {         singleKvStore.subscribe(SubscribeType.SUBSCRIBE_TYPE_ALL, kvStoreObserver); 
  89.     }      
  90.     public void clearAllData() {         List entrys = singleKvStore.getEntries(""); 
  91.         if (entrys!=null && entrys.size()>0){             for(Entry entry:entrys){ 
  92.                 singleKvStore.delete(entry.getKey());             } 
  93.             HiLog.info(label,"清空数据成功");         } else { 
  94.             HiLog.info(label,"没有数据要清空");         } 
  95.     }          public String getDrivingId(){ 
  96.         String drivingId = "";         List entrys = singleKvStore.getEntries(Constant.DRIVING_REPORT_PREFIX); 
  97.         if (entrys != null && entrys.size() > 0){             List drivingReporList = new ArrayList<>(); 
  98.             for(Entry entry:entrys){                 String value = entry.getValue().getString(); 
  99.                 Gson gson = new Gson();                 DrivingRecord drivingRecord = gson.fromJson(value, DrivingRecord.class); 
  100.                 String dateStr = drivingRecord.getDrivingDate();                 if (StringUtils.isDiffHour(dateStr)){ 
  101.                     drivingReporList.add(drivingRecord);                 } 
  102.                 HiLog.info(label,drivingRecord.getId());                 drivingReporList.add(drivingRecord); 
  103.             }             if (drivingReporList.size() > 0) { 
  104.                 //排序                 DrivingReportComparator drivingReportComparator = new DrivingReportComparator(); 
  105.                 drivingReporList.sort(drivingReportComparator);  
  106.                 drivingId = drivingReporList.get(0).getId();                 HiLog.info(label,"找到符合条件的drivingId:"+drivingId); 
  107.             } else {                 HiLog.info(label,"没有找到符合条件的drivingId"); 
  108.             }         } else { 
  109.             HiLog.info(label,"行驶记录为空,没有找到符合条件的drivingId");         } 
  110.          return drivingId; 
  111.     } } 
3、行驶记录代码
  1. import com.isoftstone.smartcar.app.ResourceTable; import com.isoftstone.smartcar.app.model.DrivingRecord; 
  2. import com.isoftstone.smartcar.app.provider.DrivingRecordProvider; import com.isoftstone.smartcar.app.service.SmartShareService; 
  3. import ohos.aafwk.ability.AbilitySlice; import ohos.aafwk.content.Intent; 
  4. import ohos.aafwk.content.Operation; import ohos.agp.components.Component; 
  5. import ohos.agp.components.Image; import ohos.agp.components.ListContainer; 
  6. import java.util.List;  
  7. public class DrivingRecordsAbilitySlice extends AbilitySlice implements Component.ClickedListener {     private ListContainer lcRecords; 
  8.     private SmartShareService shareService;     private List drivingRecordList; 
  9.     private DrivingRecordProvider drivingRecordProvider;     @Override 
  10.     public void onStart(Intent intent) {         super.onStart(intent); 
  11.         super.setUIContent(ResourceTable.Layout_ability_driving_records);         initUI(); 
  12.     }     private void initUI() { 
  13.         shareService = SmartShareService.getInstance(this);         shareService.init(); 
  14.         Image iBack = (Image) findComponentById(ResourceTable.Id_i_back);         iBack.setClickedListener(this); 
  15.         lcRecords = (ListContainer) findComponentById(ResourceTable.Id_lc_records);         drivingRecordList = getData(); 
  16.         drivingRecordProvider = new DrivingRecordProvider(drivingRecordList, this);         lcRecords.setItemProvider(drivingRecordProvider); 
  17.         lcRecords.setItemClickedListener(new ListContainer.ItemClickedListener() {             @Override 
  18.             public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {                 Intent intent = new Intent(); 
  19.                 DrivingRecord drivingRecord = (DrivingRecord) drivingRecordProvider.getItem(i);                 intent.setParam("drivingId", drivingRecord.getId()); 
  20.                 intent.setParam("lat", drivingRecord.getLatitude());                 intent.setParam("lng", drivingRecord.getLongitude()); 
  21.                 Operation operation = new Intent.OperationBuilder()                         .withDeviceId("") 
  22.                         .withBundleName("com.isoftstone.smartcar.app")                         .withAbilityName("com.isoftstone.smartcar.app.DrivingRecordsDetailAbility") 
  23.                         .build();                 intent.setOperation(operation); 
  24.                 startAbility(intent);                 //terminate(); 
  25.             }         }); 
  26.     }     @Override 
  27.     public void onActive() {         super.onActive(); 
  28.         drivingRecordList = getData();         drivingRecordProvider = new DrivingRecordProvider(drivingRecordList, this); 
  29.         lcRecords.setItemProvider(drivingRecordProvider);     } 
  30.     @Override     public void onForeground(Intent intent) { 
  31.         super.onForeground(intent);     } 
  32.     @Override     public void onClick(Component component) { 
  33.         if (component.getId() == ResourceTable.Id_i_back) {             terminateAbility(); 
  34.         }     } 
  35.     private List getData() {         return shareService.getDrivingRecords(); 
  36.     } } 
4、行驶记录详情代码
  1. import com.isoftstone.smartcar.app.ResourceTable; import com.isoftstone.smartcar.app.model.DrivingMap; 
  2. import com.isoftstone.smartcar.app.model.ReportRecord; import com.isoftstone.smartcar.app.provider.ReportRecordProvider; 
  3. import com.isoftstone.smartcar.app.service.SmartShareService; import com.isoftstone.smartcar.app.utils.CoordinateConverter; 
  4. import com.isoftstone.smartcar.app.widget.carmap.LatLng; import com.isoftstone.smartcar.app.widget.carmap.TinyMap; 
  5. import ohos.aafwk.ability.AbilitySlice; import ohos.aafwk.content.Intent; 
  6. import ohos.agp.components.Component; import ohos.agp.components.Image; 
  7. import ohos.agp.components.ListContainer; import ohos.agp.utils.Point; 
  8. import ohos.hiviewdfx.HiLog; import ohos.hiviewdfx.HiLogLabel; 
  9. import ohos.multimodalinput.event.KeyEvent; import java.util.ArrayList; 
  10. import java.util.List; import java.util.Timer; 
  11. import java.util.TimerTask;  
  12.  public class DrivingRecordsDetailAbilitySlice extends AbilitySlice implements Component.ClickedListener { 
  13.     private static final HiLogLabel logLabel = new HiLogLabel(HiLog.LOG_APP, 0x00100, "DrivingRecordsDetailAbilitySlice");  
  14.     private TinyMap map;     private String drivingId; 
  15.     private SmartShareService shareService;  
  16.     @Override     protected void onStart(Intent intent) { 
  17.         super.onStart(intent);         super.setUIContent(ResourceTable.Layout_ability_driving_records_detail); 
  18.         initUI(intent);     } 
  19.      private void initUI(Intent intent) { 
  20.         Image iBack = (Image) findComponentById(ResourceTable.Id_i_back);         iBack.setClickedListener(this); 
  21.         map = (TinyMap) findComponentById(ResourceTable.Id_map);         ListContainer reportListContainer = (ListContainer) findComponentById(ResourceTable.Id_report_records); 
  22.         drivingId = intent.getStringParam("drivingId");         shareService = SmartShareService.getInstance(this); 
  23.         shareService.init();  
  24.         new Timer().schedule(new TimerTask() {             @Override 
  25.             public void run() {                 getUITaskDispatcher().asyncDispatch(new Runnable() { 
  26.                     @Override                     public void run() { 
  27.                         setMap();                     } 
  28.                 });             } 
  29.         },500);  
  30.         List reportRecords = shareService.getReportRecords(drivingId);         ReportRecordProvider reportRecordProvider = new ReportRecordProvider(reportRecords, this); 
  31.         reportListContainer.setItemProvider(reportRecordProvider);     } 
  32.      @Override 
  33.     public void onClick(Component component) {         if (component.getId() == ResourceTable.Id_i_back) {//present(new DrivingRecordsAbilitySlice(), new Intent()); 
  34.             terminate();         } 
  35.     }  
  36.     @Override     public boolean onKeyUp(int keyCode, KeyEvent keyEvent) { 
  37.         HiLog.error(logLabel,keyEvent.getKeyCode()+"");         if (keyCode==KeyEvent.KEY_BACK){ 
  38.             //present(new DrivingRecordsAbilitySlice(), new Intent());             terminate(); 
  39.             return true;         } 
  40.         return super.onKeyDown(keyCode, keyEvent);     } 
  41.      private LatLng WGS84ToMercator(LatLng latLng) { 
  42.         return CoordinateConverter.WGS84ToMercator(latLng.getLng(), latLng.getLat());     } 
  43.      private void setMap() { 
  44.         map.initMap();         List drivingMaps = shareService.getDrivingMap(drivingId); 
  45.          LatLng startLatLng0 = new LatLng(Double.parseDouble(drivingMaps.get(0).getLatitude()), Double.parseDouble(drivingMaps.get(0).getLongitude())); 
  46.         LatLng startLatLng = new LatLng((float) WGS84ToMercator(startLatLng0).getLat(), (float) WGS84ToMercator(startLatLng0).getLng());         map.setCenterPoint((float) startLatLng.getLng(), (float) startLatLng.getLat()); 
  47.          LatLng endLatLng0 = new LatLng(Double.parseDouble(drivingMaps.get(drivingMaps.size() - 1).getLatitude()), Double.parseDouble(drivingMaps.get(drivingMaps.size() - 1).getLongitude())); 
  48.         LatLng endLatLng = new LatLng((float) WGS84ToMercator(endLatLng0).getLat(), (float) WGS84ToMercator(endLatLng0).getLng());         map.setStartElement((float) startLatLng.getLng(), (float) startLatLng.getLat(), ResourceTable.Media_start_location); 
  49.         map.setEndElement((float) endLatLng.getLng(), (float) endLatLng.getLat(), ResourceTable.Media_end_location);         List latLngs = new ArrayList<>(); 
  50.         for (DrivingMap drivingMap : drivingMaps) {             LatLng latLng = new LatLng(Double.parseDouble(drivingMap.getLatitude()), Double.parseDouble(drivingMap.getLongitude())); 
  51.             Point p = new Point((float) WGS84ToMercator(latLng).getLng(), (float) WGS84ToMercator(latLng).getLat());             latLngs.add(new LatLng(p.getPointY(), p.getPointX())); 
  52.         }         map.setPaths(latLngs); 
  53.     } } 

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

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

https://harmonyos.51cto.com

 

 
反对 0举报 0 收藏 0 评论 0

(c)2022 haohaoxuexi.cc SYSTEM All Rights Reserved

冀ICP备17031443号-5