app/src/main/assets/js/map.js | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
app/src/main/java/com/dayu/pipirrapp/activity/MainActivity.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
app/src/main/java/com/dayu/pipirrapp/bean/net/InspectionRequest.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
app/src/main/java/com/dayu/pipirrapp/fragment/MapFragment.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
app/src/main/java/com/dayu/pipirrapp/fragment/OrderFragment.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
app/src/main/java/com/dayu/pipirrapp/net/MqttManager.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
app/src/main/java/com/dayu/pipirrapp/tool/MarkerUtils.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
app/src/main/java/com/dayu/pipirrapp/tool/MyWebViewInterface.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
app/src/main/res/layout/fragment_map.xml | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 |
app/src/main/assets/js/map.js
@@ -23,6 +23,8 @@ window.updateInspectionLocation = updateInspectionLocation; window.cleanLoclLay = cleanLoclLay; window.showPin = showPin; window.cancelPin = cancelPin; window.refreshMarker = refreshMarker; } @@ -34,11 +36,7 @@ mountMethodToWindow(); }); // window.onload = function () { // console.log(window.onload); // 打印数组数据 // //加载坐标点 // window.Android.loadMarker(); // }; // 初始化地图 function initMap() { // 影像底图 @@ -146,30 +144,36 @@ // 调用原生安卓方法隐藏取水口详情 function closeWaterIntakeDetail(data) { if (lastClickedMarker !== null) { // 如果有点击取水口则将取水口恢复成黑色 // 上次点击的标注改为黑色 var defaulticon = new T.Icon({ iconUrl: markerBluePath, iconSize: new T.Point(28, 28), iconAnchor: new T.Point(14, 28) }); lastClickedMarker.setIcon(defaulticon); if (!isShowCenterPin) { if (lastClickedMarker !== null) { // 如果有点击取水口则将取水口恢复成黑色 // 上次点击的标注改为黑色 var defaulticon = new T.Icon({ iconUrl: markerBluePath, iconSize: new T.Point(28, 28), iconAnchor: new T.Point(14, 28) }); lastClickedMarker.setIcon(defaulticon); } if (isShowWaterIntakeDetail) { // 假如显示了取水口详情则隐藏取水口详情 isShowWaterIntakeDetail = false; window.Android.closeWaterIntakeView(); } else { // 假如没有显示取水口则添加点击的坐标 getLngLat(data.lnglat); } } if (isShowWaterIntakeDetail) { // 假如显示了取水口详情则隐藏取水口详情 isShowWaterIntakeDetail = false; window.Android.closeWaterIntakeView(); } else { // 假如没有显示取水口则添加点击的坐标 getLngLat(data.lnglat); } } // 点击标注的事件 function addMarkerListener(id, data) { chageMarkerIcon(data); showWaterIntakeDetail(id); if (!isShowCenterPin) { chageMarkerIcon(data); showWaterIntakeDetail(id); } } // 修改点击标注的图标 @@ -196,6 +200,7 @@ } } lastClickedMarker = data.target; map.panTo(currentMarker.getLngLat()); } //调安卓原生 function showToast() { @@ -206,12 +211,21 @@ function isEqualsLngLat(data1, data2) { return data1.lat === data2.lat && data1.lng === data2.lng; } //添加从原生传过来的坐标并显示在地图上 function addMarker(id, lng, lat, name) { console.log("function》》》》》addMarker"); addMarker(id, lng, lat, name, false) } //添加从原生传过来的坐标并显示在地图上 function addMarker(id, lng, lat, name, isRed) { console.log("function》》》》》addMarker>>>id:" + id); var iconUrl; if (isRed) { iconUrl = markerRedPath; } else { iconUrl = markerBluePath; } var icon = new T.Icon({ iconUrl: markerBluePath, iconUrl: iconUrl, iconSize: new T.Point(28, 28), iconAnchor: new T.Point(14, 28) }); @@ -222,7 +236,7 @@ marker.addEventListener("click", (data) => { addMarkerListener(id, data) }); map.addOverLay(marker); // 将标注添加到地图中 let label = new T.Label({ text: `<div style='position:absolute;left:-50%;transform: translateX(-50%);'>${name}<div>`, position: marker.getLngLat(), @@ -233,8 +247,13 @@ label.setBackgroundColor("transparent"); // 设置文本的背景色(透明色) label.setFontColor("#FFFFFF"); label.setFontSize(10); marker.label = label; if (isRed){ lastClickedMarker=marker; } map.addOverLay(label); return "addMarker加载成功" map.addOverLay(marker); // 将标注添加到地图中 return "addMarker加载成功 id:" + id } //更新定位坐标 function updateLocation(log, lat) { @@ -300,36 +319,34 @@ } } //是否显示了地图中心的针用来修改坐标 var isShowCenterPin; //开始获取屏幕中间定位 function showPin(lng, lat) { var newPoint = new T.LngLat(lng, lat); map.panTo(newPoint); isShowCenterPin = true; map.addEventListener("moveend", mapMoveEnd); window.Android.refreshCenter(map.getCenter().getLng(), map.getCenter().getLat()); //在地图上显示中心点 var pinMarker; function showPin() { var icon = new T.Icon({ iconUrl: centerPin, iconSize: new T.Point(28, 28), iconAnchor: new T.Point(14, 28) }); pinMarker = new T.Marker( new T.LngLat(map.getCenter().getLng(), map.getCenter().getLat()) // 创建标注 , { icon: icon }); map.addOverLay(pinMarker); // 将标注添加到地图中 map.addEventListener("moveend", MapMoveend); } //取消修改定位 function cancelPin() { isShowCenterPin = false; } function MapMoveend(e) { map.removeOverLay(pinMarker); var icon = new T.Icon({ iconUrl: centerPin, iconSize: new T.Point(28, 28), iconAnchor: new T.Point(14, 28) }); //成功修改取水口经纬度后刷新取水口位置 function refreshMarker(id, lng, lat, name) { map.removeOverLay(lastClickedMarker.label); map.removeOverLay(lastClickedMarker); addMarker(id, lng, lat, name, true); } function mapMoveEnd(e) { var center = e.target.getCenter(); console.log("lng:" + center.getLng() + " lat:" + center.getLat()) pinMarker = new T.Marker( new T.LngLat(center.getLng(), center.getLat()) // 创建标注 , { icon: icon }); map.addOverLay(pinMarker); // 将标注添加到地图中 window.Android.refreshCenter(center.getLng(), center.getLat()); } })(); app/src/main/java/com/dayu/pipirrapp/activity/MainActivity.java
@@ -59,7 +59,6 @@ e.printStackTrace(); } mqttManager = new MqttManager(this, this); mqttManager.connect(); LiveEventBus.get(CommonKeyName.NetworkCallback).observeForever(new Observer<Object>() { @Override public void onChanged(Object o) { @@ -74,6 +73,7 @@ } } }); registNetCallBack(); } @@ -120,8 +120,9 @@ @Override protected void onDestroy() { super.onDestroy(); //关闭MQ try { //关闭MQ mqttManager.disconnect(); unregisterNetworkCallback(); } catch (Exception e) { app/src/main/java/com/dayu/pipirrapp/bean/net/InspectionRequest.java
@@ -10,12 +10,26 @@ * @version 1.0 * @since 2024-12-02 */ public class InspectionRequest extends BaseRequest{ public class InspectionRequest extends BaseRequest { private static InspectionRequest inspectionRequest; public static InspectionRequest getInstance() { if (inspectionRequest == null) { inspectionRequest = new InspectionRequest(); } inspectionRequest.setStartTime(""); inspectionRequest.setStopTime(""); inspectionRequest.setInspectId(""); inspectionRequest.setInspectorId(""); inspectionRequest.getTracks().clear(); return inspectionRequest; } private String inspectorId; private String inspectId; private String startTime; private String stopTime; private List<Track> tracks=new ArrayList<>(); private List<Track> tracks = new ArrayList<>(); public String getInspectorId() { @@ -64,7 +78,6 @@ } tracks.add(track); } // Track 数据类 app/src/main/java/com/dayu/pipirrapp/fragment/MapFragment.java
@@ -17,11 +17,13 @@ import android.webkit.WebResourceResponse; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.RelativeLayout; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.lifecycle.Observer; import com.dayu.pipirrapp.MyApplication; import com.dayu.pipirrapp.R; import com.dayu.pipirrapp.activity.AddIssueActivity; import com.dayu.pipirrapp.bean.db.CenterPointBean; @@ -68,6 +70,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers; import io.reactivex.rxjava3.schedulers.Schedulers; @@ -90,9 +93,8 @@ MapFragmenObserver mapFragmenObserver; //当前巡检记录的相关信息 public InspectionBean mInspectionBean; //最后一次定位的坐标 LatLonBean lastLatLonBean; InspectionRequest inspectionRequest; // volatile boolean isHaseAginData = false; //web是否加载完成 volatile boolean webViewIsFinished = false; List<InspectionLocationBean> aginShowlocationBeans; @@ -100,6 +102,9 @@ List<MarkerBean> webNoFinishMarkerData = new ArrayList<>(); //所有的Marker数据键为marker的Id Map<String, MarkerBean> markerBeanSet = new HashMap<>(); //中心点坐标 public double centerLng; public double centerLat; @Override public void onAttach(@NonNull Context context) { @@ -242,41 +247,43 @@ @Override public void onNext(BaseResponse<MarkerListResult> t) { if (t.isSuccess()) { if (t.isSuccess()) { if (t.getContent().getObj() != null && !t.getContent().getObj().isEmpty()) { List<MarkerBean> markerBeans = new ArrayList<>(); for (int i = 0; i < t.getContent().getObj().size(); i++) { MarkerResult result = t.getContent().getObj().get(i); //保存数据 MarkerBean markerBean = new MarkerBean(); markerBean.setId(result.getId()); markerBean.setLng(result.getLng()); markerBean.setLat(result.getLat()); markerBean.setBlockId(result.getBlockId()); markerBean.setName(result.getName()); markerBean.setRemarks(result.getRemarks()); markerBean.setTownId(result.getTownId()); markerBean.setVillageId(result.getVillageId()); markerBean.setCountyId(result.getCountyId()); markerBean.setAddress(result.getAddress()); markerBean.setBlockName(result.getBlockName()); markerBeans.add(markerBean); setMapMarker(markerBean); } DaoSingleton.getInstance(MapFragment.this.getContext()).markerDao().deleteAll(); // 使用 RxJava 异步插入数据 DaoSingleton.getAsynchInstance(MapFragment.this.getContext()).markerDao().insertAll(markerBeans) .subscribeOn(Schedulers.io()) // 在 IO 线程上执行 .observeOn(AndroidSchedulers.mainThread()) // 在主线程上观察 .subscribe(() -> { // 插入成功 Log.i("mWebView", "数据插入成功"); }, throwable -> { // 插入失败 Log.e("mWebView", "数据插入失败: " + throwable.getMessage()); }); } if (t.getContent().getObj() != null && !t.getContent().getObj().isEmpty()) { List<MarkerBean> markerBeans = t.getContent().getObj().stream() .map(result -> { MarkerBean markerBean = new MarkerBean(); markerBean.setId(result.getId()); markerBean.setLng(result.getLng()); markerBean.setLat(result.getLat()); markerBean.setBlockId(result.getBlockId()); markerBean.setName(result.getName()); markerBean.setRemarks(result.getRemarks()); markerBean.setTownId(result.getTownId()); markerBean.setVillageId(result.getVillageId()); markerBean.setCountyId(result.getCountyId()); markerBean.setAddress(result.getAddress()); markerBean.setBlockName(result.getBlockName()); markerBean.setDivideId(result.getDivideId()); setMapMarker(markerBean); return markerBean; }) .collect(Collectors.toList()); DaoSingleton.getInstance(MapFragment.this.getContext()).markerDao().deleteAll(); // 使用 RxJava 异步插入数据 DaoSingleton.getAsynchInstance(MapFragment.this.getContext()).markerDao().insertAll(markerBeans) .subscribeOn(Schedulers.io()) // 在 IO 线程上执行 .observeOn(AndroidSchedulers.mainThread()) // 在主线程上观察 .subscribe(() -> { // 插入成功 Log.i("mWebView", "数据插入成功"); }, throwable -> { // 插入失败 Log.e("mWebView", "数据插入失败: " + throwable.getMessage()); }); } } else { ToastUtil.showToast(MapFragment.this.getContext(), t.getMsg()); } @@ -287,7 +294,6 @@ void initView() { //巡检按钮 binding.inspectButton.setOnClickListener(v -> { @@ -333,16 +339,8 @@ MyLog.i(data); MarkerBean markerBean = markerBeanSet.get(data); if (markerBean != null) { binding.bottomLL.setVisibility(View.VISIBLE); binding.markerAddress.setText(markerBean.getAddress()); binding.markerName.setText(markerBean.getName()); binding.markerBlockName.setText(markerBean.getBlockName()); binding.lat.setText(markerBean.getLat()); binding.lng.setText(markerBean.getLng()); binding.editePoint.setOnClickListener(v -> { mWebView.evaluateJavascript("javascript:showPin()", value -> { }); }); setWebViewParams(false); getInstakeDetail(markerBean); } } @@ -352,7 +350,7 @@ * 获取地图中心点 */ private void getCenterPoint() { ApiManager.getInstance().requestGet(this.getContext(), Constants.BASE_URL + "/base/dict_item/map_center", CenterPointResult.class, null, new SubscriberListener<BaseResponse<CenterPointResult>>() { ApiManager.getInstance().requestGetHideLoading(this.getContext(), Constants.BASE_URL + "/base/dict_item/map_center", CenterPointResult.class, null, new SubscriberListener<BaseResponse<CenterPointResult>>() { @Override public void onNext(BaseResponse<CenterPointResult> t) { if (t.isSuccess()) { @@ -380,6 +378,7 @@ * 上报巡检记录 */ private void pushLocationData(InspectionLocationBean inspectionLocationBean) { InspectionRequest inspectionRequest = InspectionRequest.getInstance(); inspectionRequest.setInspectId(inspectionLocationBean.getInspectId()); inspectionRequest.setInspectorId(mInspectionBean.getInspectorId()); if (mInspectionBean != null) { @@ -392,7 +391,6 @@ track.setLat(inspectionLocationBean.getLat()); track.setLng(inspectionLocationBean.getLng()); track.setLocateTime(inspectionLocationBean.getLocateTime()); inspectionRequest.getTracks().clear(); inspectionRequest.addTracks(track); ApiManager.getInstance().requestPostHideLoading(MapFragment.this.getContext(), BASE_URL + "/app/inspect/save", InsectionResult.class, inspectionRequest.toMap(inspectionRequest), new SubscriberListener<BaseResponse<List<InsectionResult>>>() { @Override @@ -558,7 +556,6 @@ public void setMapMarker(MarkerBean markerBean) { if (markerBean != null) { if (webViewIsFinished) { Log.i("mWebView", "addMarker????????????"); mWebView.evaluateJavascript("javascript:addMarker(\"" + markerBean.getId() + "\",\"" + markerBean.getLng() + "\",\"" + markerBean.getLat() + "\",\"" + markerBean.getName() + "\")", new ValueCallback<String>() { @Override public void onReceiveValue(String value) { @@ -586,7 +583,6 @@ binding.inspectPause.setText("暂停"); binding.stateText.setText("已开启巡检"); binding.inspectRL.setBackgroundColor(this.getContext().getResources().getColor(R.color.base_blue)); inspectionRequest = new InspectionRequest(); SharedPreferencesHelper.getInstance(this.getContext()).put(CommonKeyName.inspectionState, InspectionUtils.STAT_INSPECTION); ServiceUtils.startLocationService(MapFragment.this.getContext(), false); } @@ -629,4 +625,139 @@ e.printStackTrace(); } } /** * 接收js传来的中心点坐标 * * @param lng * @param lat */ public void refreshCenterPoint(double lng, double lat) { centerLng = lng; centerLat = lat; binding.pointText.setText(centerLng + "," + centerLat); } /** * 修改经纬度 * * @param markerBean */ private void updataInstake(MarkerBean markerBean) { String lng = String.valueOf(centerLng); String lat = String.valueOf(centerLat); Map<String, Object> params = new HashMap<>(); params.put("id", markerBean.getId()); params.put("lng", lng); params.put("lat", lat); params.put("operator", MyApplication.myApplication.userId); ApiManager.getInstance().requestPost(MapFragment.this.getContext(), BASE_URL + "/project/intake/updateIntakeLngLat", Boolean.class, params, new SubscriberListener<BaseResponse<Boolean>>() { @Override public void onNext(BaseResponse<Boolean> t) { try { if (t.isSuccess()) { mWebView.evaluateJavascript("javascript:refreshMarker(\"" + markerBean.getId() + "\",\"" + centerLng + "\",\"" + centerLat + "\",\"" + markerBean.getName() + "\")", new ValueCallback<String>() { @Override public void onReceiveValue(String value) { } }); binding.pointCenterImg.setVisibility(View.GONE); binding.pointRL.setVisibility(View.GONE); binding.lng.setText(lng); binding.lat.setText(lat); mWebView.evaluateJavascript("javascript:cancelPin()", value -> { }); ToastUtil.showToastLong(MapFragment.this.getContext(), "修改成功!"); } else { ToastUtil.showToastLong(MapFragment.this.getContext(), t.getMsg()); } } catch (Exception e) { e.printStackTrace(); CrashReport.postCatchedException(e); } } }); } /** * 获取取水口详情 * * @param markerBean */ private void getInstakeDetail(MarkerBean markerBean) { Map<String, Object> params = new HashMap<>(); params.put("id", markerBean.getId()); ApiManager.getInstance().requestGet(this.getContext(), Constants.BASE_URL + "/project/intake/one", MarkerResult.class, params, new SubscriberListener<BaseResponse<MarkerResult>>() { @Override public void onNext(BaseResponse<MarkerResult> t) { if (t.isSuccess()) { MarkerResult result = t.getContent(); MarkerBean markerBean = new MarkerBean(); markerBean.setId(result.getId()); markerBean.setLng(result.getLng()); markerBean.setLat(result.getLat()); markerBean.setBlockId(result.getBlockId()); markerBean.setName(result.getName()); markerBean.setRemarks(result.getRemarks()); markerBean.setTownId(result.getTownId()); markerBean.setVillageId(result.getVillageId()); markerBean.setCountyId(result.getCountyId()); markerBean.setAddress(result.getAddress()); markerBean.setBlockName(result.getBlockName()); markerBean.setDivideId(result.getDivideId()); showMarker(markerBean); } else { ToastUtil.showToast(MapFragment.this.getContext(), t.getMsg()); } } }); } private void showMarker(MarkerBean markerBean) { binding.bottomLL.setVisibility(View.VISIBLE); binding.markerAddress.setText(markerBean.getAddress()); binding.markerName.setText(markerBean.getName()); binding.markerBlockName.setText(markerBean.getBlockName()); binding.lat.setText(markerBean.getLat()); binding.lng.setText(markerBean.getLng()); //修改经纬度 binding.editePoint.setOnClickListener(v -> { mWebView.evaluateJavascript("javascript:showPin(\"" + markerBean.getLng() + "\",\"" + markerBean.getLat() + "\")", value -> { }); binding.pointRL.setVisibility(View.VISIBLE); binding.pointCenterImg.setVisibility(View.VISIBLE); setWebViewParams(true); }); //取消修改经纬度 binding.pointCancel.setOnClickListener(v -> { binding.pointCenterImg.setVisibility(View.GONE); binding.pointRL.setVisibility(View.GONE); mWebView.evaluateJavascript("javascript:cancelPin()", value -> { }); } ); //确认修改经纬度 binding.pointEdt.setOnClickListener(v -> { ConfirmDialog confirmDialog = new ConfirmDialog(MapFragment.this.getActivity(), "确认修改到该位置吗?", (confirmDialog1, v1) -> { confirmDialog1.dismiss(); updataInstake(markerBean); }); confirmDialog.show(); }); } private void setWebViewParams(boolean isAbove) { RelativeLayout.LayoutParams paramsAnotherView = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT); if (isAbove) { paramsAnotherView.addRule(RelativeLayout.ABOVE, binding.bottomLL.getId()); } binding.webViewRL.setLayoutParams(paramsAnotherView); } } app/src/main/java/com/dayu/pipirrapp/fragment/OrderFragment.java
@@ -12,6 +12,7 @@ import androidx.activity.result.contract.ActivityResultContracts; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.lifecycle.Observer; import androidx.recyclerview.widget.LinearLayoutManager; import com.dayu.pipirrapp.MyApplication; @@ -93,10 +94,13 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { binding = FragmentOrderBinding.inflate(inflater, container, false); initView(); //获取定位服务传过来的坐标点 LiveEventBus.get(CommonKeyName.MQTTData).observeForever(o -> { }); //mq传来的消息 LiveEventBus.get(CommonKeyName.MQTTData).observeForever(new Observer<Object>() { @Override public void onChanged(Object o) { } }); return binding.getRoot(); } app/src/main/java/com/dayu/pipirrapp/net/MqttManager.java
@@ -6,7 +6,9 @@ import androidx.lifecycle.LifecycleOwner; import androidx.lifecycle.Observer; import com.dayu.pipirrapp.MyApplication; import com.dayu.pipirrapp.utils.CommonKeyName; import com.dayu.pipirrapp.utils.MyJsonParser; import com.dayu.pipirrapp.utils.MyLog; import com.dayu.pipirrapp.utils.NetUtils; import com.jeremyliao.liveeventbus.LiveEventBus; @@ -19,6 +21,7 @@ import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; import java.util.HashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -31,14 +34,16 @@ */ public class MqttManager { // private static final String MQTT_BROKER_URL = "tcp://115.236.153.170:30764"; // 修改为你的 broker 地址 private static final String MQTT_BROKER_URL = "tcp://192.168.10.52:1883"; // private static final String MQTT_BROKER_URL = "tcp://115.236.153.170:30764"; // 修改为你的 broker 地址 private static final String MQTT_BROKER_URL = "tcp://192.168.10.52:1883"; private static final String CLIENT_ID = "mqttx_a7a9fe73"; private static final String TOPIC = "workOrder"; // 订阅的主题 private MqttClient mqttClient; private MqttConnectOptions connectOptions; boolean isHasNet = true; //是否连接成功过一次,没有的话联网后重连 boolean isConnet = false; private ExecutorService executorService = Executors.newSingleThreadExecutor(); public MqttManager(Context context, LifecycleOwner lifecycleOwner) { @@ -50,6 +55,31 @@ connectOptions.setCleanSession(false); connectOptions.setKeepAliveInterval(60); // 设置保持连接的时间 connectOptions.setAutomaticReconnect(true); // 启用自动重连 connectOptions.setConnectionTimeout(30);// 设置连接超时时间,单位为秒 mqttClient.setCallback(new MqttCallback() { @Override public void connectionLost(Throwable cause) { Log.d("MqttManager", "连接丢失:" + cause.getMessage()); // 处理连接丢失,可以尝试重新连接 reconnect(); } @Override public void messageArrived(String topic, MqttMessage message) throws Exception { Log.d("MqttManager", "messageArrived收到的消:" + new String(message.getPayload())); // 处理收到的消息 } @Override public void deliveryComplete(IMqttDeliveryToken token) { // 处理消息发送完成 try { Log.d("MqttManager", "发送完成:" + new String(token.getMessage().toString())); } catch (MqttException e) { e.printStackTrace(); } } }); LiveEventBus.get(CommonKeyName.NetworkCallback).observe(lifecycleOwner, new Observer<Object>() { @Override public void onChanged(Object o) { @@ -58,12 +88,14 @@ case NetUtils.Available: MyLog.i("MqttManager>>>Available"); isHasNet = true; reconnect(); if (!isConnet) { reconnect(); } break; case NetUtils.Lost: MyLog.i("MqttManager>>>Lost"); isHasNet = false; disconnect(); // disconnect(); break; } } @@ -83,30 +115,6 @@ Log.d("MqttManager", "connect开始连接isHasNet:" + isHasNet); if (isHasNet) { Log.d("MqttManager", "connect开始连接"); mqttClient.setCallback(new MqttCallback() { @Override public void connectionLost(Throwable cause) { Log.d("MqttManager", "连接丢失:" + cause.getMessage()); // 处理连接丢失,可以尝试重新连接 reconnect(); } @Override public void messageArrived(String topic, MqttMessage message) throws Exception { Log.d("MqttManager", "收到的消:" + new String(message.getPayload())); // 处理收到的消息 } @Override public void deliveryComplete(IMqttDeliveryToken token) { // 处理消息发送完成 try { Log.d("MqttManager", "发送完成:" + new String(token.getMessage().toString())); } catch (MqttException e) { e.printStackTrace(); } } }); mqttClient.connect(connectOptions); if (mqttClient.isConnected()) { Log.d("MqttManager", "connect连接成功"); @@ -129,11 +137,16 @@ // 订阅主题 private void subscribeToTopic() { try { isConnet = true; mqttClient.subscribe(TOPIC, (topic, message) -> { // 收到消息时的处理逻辑 Log.d("MqttManager", "收到消息:" + new String(message.getPayload())); // 在子线程收到消息时的处理逻辑 Log.d("MqttManager", "subscribe收到消息:" + new String(message.getPayload())); //传递MQ收到的信息 LiveEventBus.get(CommonKeyName.locationData).post(message.getPayload()); HashMap<String, Object> data= MyJsonParser.getMapFromJson(new String(message.getPayload())); //判断是否是当前用户 if (data.get("inspectorId").equals(MyApplication.myApplication.userId)){ LiveEventBus.get(CommonKeyName.MQTTData).post(message.getPayload()); } }); } catch (MqttException e) { @@ -161,27 +174,36 @@ } } catch (MqttException e) { e.printStackTrace(); } finally { executorService.shutdown(); } } // 自动重连方法 private void reconnect() { // executorService.execute(() -> { // try { // MyLog.d("MqttManager>>>>开始重连+isHasNet:" + isHasNet + ">>>mqttClient.isConnected():" + mqttClient.isConnected()); // while (!mqttClient.isConnected() && isHasNet) { // MyLog.d("MqttManager>>>>开始连接"); // mqttClient.connect(connectOptions); // if (mqttClient.isConnected()) { // MyLog.d("MqttManager>>>连接成功"); // subscribeToTopic(); // break; // } // Thread.sleep(5000); // 每5秒重试一次 // } // } catch (MqttException | InterruptedException e) { // MyLog.e("MqttManager>>>Reconnection failed" + e.toString()); // } // }); executorService.execute(() -> { int reconnectAttempts = 0; while (!mqttClient.isConnected() && isHasNet) { try { MyLog.d("MqttManager>>>>开始重连"); mqttClient.connect(connectOptions); if (mqttClient.isConnected()) { MyLog.d("MqttManager>>>连接成功"); subscribeToTopic(); break; } // 指数退避 long backoff = Math.min((1L << reconnectAttempts) * 1000, 30000); Thread.sleep(backoff); reconnectAttempts++; } catch (MqttException e) { MyLog.e("MqttManager>>>Reconnection failed" + e.getMessage()); // 可以在这里增加重连尝试次数的限制 } catch (InterruptedException e) { Thread.currentThread().interrupt(); // 保留中断状态 return; } } }); } } app/src/main/java/com/dayu/pipirrapp/tool/MarkerUtils.java
@@ -25,7 +25,7 @@ .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()).subscribe(markerBeans -> { for (MarkerBean bean : markerBeans) { fragment.setMapMarker(bean); // fragment.setMapMarker(bean); } }); return disposable; app/src/main/java/com/dayu/pipirrapp/tool/MyWebViewInterface.java
@@ -11,7 +11,7 @@ * author: zuo * Date: 2024-01-18 * Time: 9:14 * 备注:供Vue调用原生 * 备注:供js调用原生 */ public class MyWebViewInterface { @@ -81,5 +81,21 @@ } } /** * 刷新地图中心点坐标 */ @JavascriptInterface public void refreshCenter(double lng, double lat) { if (myContext instanceof MapFragment) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { // 在主线程上执行UI操作 // 更新或操作UI元素的代码 myContext.refreshCenterPoint(lng, lat); } }); } } } app/src/main/res/layout/fragment_map.xml
@@ -9,9 +9,10 @@ <!-- android:layout_height="match_parent" />--> <RelativeLayout android:id="@+id/webViewRL" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@+id/bottomLL"> > <WebView @@ -20,12 +21,14 @@ android:layout_height="match_parent" /> <ImageView android:id="@+id/pointCenterImg" android:layout_width="26dp" android:layout_height="52dp" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:paddingBottom="26dp" android:src="@drawable/ic_center_pin" /> android:src="@drawable/ic_center_pin" android:visibility="gone" /> </RelativeLayout> <RelativeLayout @@ -81,7 +84,7 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_marginTop="80dp" android:layout_marginTop="60dp" android:layout_marginRight="15dp" android:background="@drawable/ic_blue_background" android:padding="10dp" @@ -95,7 +98,7 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_marginTop="140dp" android:layout_marginTop="120dp" android:layout_marginRight="15dp" android:background="@drawable/ic_green_bg" android:padding="10dp" @@ -105,11 +108,42 @@ <RelativeLayout android:id="@+id/pointRL" android:layout_width="match_parent" android:layout_height="35dp" android:layout_above="@+id/bottomLL" android:background="@color/white"> android:background="@color/white" android:visibility="gone"> <TextView android:id="@+id/pointCancel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="5dp" android:padding="5dp" android:text="取消" android:textSize="@dimen/common_text_size_little" /> <TextView android:id="@+id/pointText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:textSize="@dimen/common_text_size_little" /> <TextView android:id="@+id/pointEdt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:layout_marginRight="5dp" android:padding="5dp" android:text="修改" android:textColor="@color/base_blue" android:textSize="@dimen/common_text_size_little" /> </RelativeLayout> <LinearLayout @@ -118,8 +152,13 @@ android:layout_height="120dp" android:layout_alignParentBottom="true" android:background="@color/white" android:orientation="horizontal" android:orientation="vertical" android:visibility="gone"> <View android:layout_width="match_parent" android:layout_height="2px" android:background="@color/line_bg" /> <ScrollView android:layout_width="match_parent" @@ -136,7 +175,7 @@ <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_height="25dp" android:gravity="center_vertical" android:orientation="horizontal"> @@ -146,6 +185,7 @@ android:layout_height="25dp" android:layout_centerVertical="true" android:layout_marginRight="10dp" android:padding="3dp" android:src="@drawable/ic_intake" /> <TextView @@ -185,7 +225,7 @@ <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_height="25dp" android:gravity="center_vertical" android:orientation="horizontal"> @@ -228,15 +268,15 @@ android:id="@+id/editePoint" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="5dp" android:padding="2dp" android:src="@drawable/ic_edit_btn" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_height="25dp" android:layout_marginBottom="10dp" android:gravity="start" android:gravity="center" android:orientation="horizontal"> <TextView