Explorar o código

add: 全局异常上传、切换网络

huwanxiao hai 1 ano
pai
achega
a726afbd9d

+ 73 - 56
app/src/main/AndroidManifest.xml

@@ -5,7 +5,7 @@
     <!-- 应用使用蓝牙的权限 -->
     <uses-permission android:name="android.permission.BLUETOOTH" /> <!-- 在android 6.0之后要用蓝牙还需要添加一个模糊定位的权限 -->
     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- 扫描蓝牙设备或者操作蓝牙设置 -->
-    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
+    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
     <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
@@ -26,84 +26,101 @@
         android:usesCleartextTraffic="true"
         android:theme="@style/AppTheme"
         tools:ignore="GoogleAppIndexingWarning">
-
-        <activity android:name=".MainActivity"
-            android:screenOrientation="portrait"
+        <activity
+            android:name=".MainActivity"
             android:hardwareAccelerated="true"
-            android:windowSoftInputMode="adjustPan" >
+            android:screenOrientation="portrait"
+            android:windowSoftInputMode="adjustPan">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
+
                 <category android:name="android.intent.category.LAUNCHER" />
             </intent-filter>
         </activity>
         <activity
             android:name=".activity.CaremaActivity"
             android:screenOrientation="portrait"
-            android:windowSoftInputMode="adjustPan" >
-        </activity>
-
+            android:windowSoftInputMode="adjustPan"></activity>
         <activity
             android:name=".NewMainActivity"
             android:screenOrientation="portrait"
-            android:windowSoftInputMode="adjustPan" >
-        </activity>
+            android:windowSoftInputMode="adjustPan"></activity>
         <activity
             android:name=".activity.SettingActivity"
             android:screenOrientation="portrait"
-            android:windowSoftInputMode="adjustPan" >
-        </activity>
-        <activity android:name=".activity.WaitActivity"
-            android:screenOrientation="portrait"/>
-        <activity android:name=".activity.SaveTrademarkActivity"
-            android:screenOrientation="portrait"/>
-        <activity android:name=".activity.UpTrademarkActivity"
-            android:screenOrientation="portrait"/>
-        <activity android:name=".activity.StockSearchActivity"
-            android:screenOrientation="portrait"/>
-        <activity android:name=".activity.UpTrademarkScanActivity"
-            android:screenOrientation="portrait"/>
-        <activity android:name=".activity.ApplyTrademarkActivity"
-            android:screenOrientation="portrait"/>
-        <activity android:name=".activity.ApplyTrademarkSelectActivity"
-            android:screenOrientation="portrait"/>
-        <activity android:name=".activity.RepairTrademarkSelectActivity"
-            android:screenOrientation="portrait"/>
-        <activity android:name=".activity.RepairTrademarkCompleteActivity"
-            android:screenOrientation="portrait"/>
-        <activity android:name=".activity.FullApplyTrademarkActivity"
-            android:screenOrientation="portrait"/>
-        <activity android:name=".activity.FullApplyTrademarkSelectActivity"
-            android:screenOrientation="portrait"/>
-        <activity android:name=".activity.VerifyTrademarkActivity"
-            android:screenOrientation="portrait"/>
-        <activity android:name=".activity.RepairTrademarkActivity"
-            android:screenOrientation="portrait"/>
-        <activity android:name=".activity.RecycleTrademarkActivity"
-            android:screenOrientation="portrait"/>
-        <activity android:name=".activity.ApplyTrademarkCompleteActivity"
-            android:screenOrientation="portrait"/>
-        <activity android:name=".activity.RecycleTrademarkSelectActivity"
-            android:screenOrientation="portrait"/>
-        <activity android:name=".activity.LoginActivity"
-            android:screenOrientation="portrait"/>
-        <activity android:name=".activity.WaitCloseDoorActivity"
-            android:screenOrientation="portrait"/>
-        <activity android:name=".activity.FullApplyTrademarkScanActivity"
-            android:screenOrientation="portrait"/>
-        <activity android:name=".activity.AdActivity"
-            android:screenOrientation="portrait"/>
+            android:windowSoftInputMode="adjustPan"></activity>
+        <activity
+            android:name=".activity.WaitActivity"
+            android:screenOrientation="portrait" />
+        <activity
+            android:name=".activity.SaveTrademarkActivity"
+            android:screenOrientation="portrait" />
+        <activity
+            android:name=".activity.UpTrademarkActivity"
+            android:screenOrientation="portrait" />
+        <activity
+            android:name=".activity.StockSearchActivity"
+            android:screenOrientation="portrait" />
+        <activity
+            android:name=".activity.UpTrademarkScanActivity"
+            android:screenOrientation="portrait" />
+        <activity
+            android:name=".activity.ApplyTrademarkActivity"
+            android:screenOrientation="portrait" />
+        <activity
+            android:name=".activity.ApplyTrademarkSelectActivity"
+            android:screenOrientation="portrait" />
+        <activity
+            android:name=".activity.RepairTrademarkSelectActivity"
+            android:screenOrientation="portrait" />
+        <activity
+            android:name=".activity.RepairTrademarkCompleteActivity"
+            android:screenOrientation="portrait" />
+        <activity
+            android:name=".activity.FullApplyTrademarkActivity"
+            android:screenOrientation="portrait" />
+        <activity
+            android:name=".activity.FullApplyTrademarkSelectActivity"
+            android:screenOrientation="portrait" />
+        <activity
+            android:name=".activity.VerifyTrademarkActivity"
+            android:screenOrientation="portrait" />
+        <activity
+            android:name=".activity.RepairTrademarkActivity"
+            android:screenOrientation="portrait" />
+        <activity
+            android:name=".activity.RecycleTrademarkActivity"
+            android:screenOrientation="portrait" />
+        <activity
+            android:name=".activity.ApplyTrademarkCompleteActivity"
+            android:screenOrientation="portrait" />
+        <activity
+            android:name=".activity.RecycleTrademarkSelectActivity"
+            android:screenOrientation="portrait" />
+        <activity
+            android:name=".activity.LoginActivity"
+            android:screenOrientation="portrait" />
+        <activity
+            android:name=".activity.WaitCloseDoorActivity"
+            android:screenOrientation="portrait" />
+        <activity
+            android:name=".activity.FullApplyTrademarkScanActivity"
+            android:screenOrientation="portrait" />
+        <activity
+            android:name=".activity.AdActivity"
+            android:screenOrientation="portrait" />
 
         <provider
             android:name="androidx.core.content.FileProvider"
             android:authorities="${applicationId}.fileprovider"
             android:exported="false"
-            tools:replace="android:authorities"
-            android:grantUriPermissions="true">
+            android:grantUriPermissions="true"
+            tools:replace="android:authorities">
             <meta-data
                 android:name="android.support.FILE_PROVIDER_PATHS"
                 android:resource="@xml/provider_paths"
-                tools:replace="android:resource"
-                />
+                tools:replace="android:resource" />
         </provider>
     </application>
+
 </manifest>

+ 1 - 0
app/src/main/java/com/naz/sdkdemo/BaseApplication.java

@@ -89,6 +89,7 @@ public class BaseApplication extends Application {
         MultiDex.install(this);
         BleManager.getInstance().init(getApplication());
         BleManager.getInstance()
+                .setReConnectCount(1, 5000)
                 .enableLog(true)
                 .setSplitWriteNum(20)
                 .setConnectOverTime(15000)

+ 422 - 102
app/src/main/java/com/naz/sdkdemo/MainActivity.java

@@ -14,6 +14,7 @@ import android.location.LocationManager;
 import android.os.Build;
 import android.os.Environment;
 import android.os.Handler;
+import android.os.Looper;
 import android.provider.MediaStore;
 import android.text.TextUtils;
 import android.util.Log;
@@ -22,6 +23,7 @@ import android.view.View;
 import android.webkit.CookieManager;
 import android.webkit.CookieSyncManager;
 import android.webkit.JavascriptInterface;
+import android.webkit.RenderProcessGoneDetail;
 import android.webkit.WebResourceError;
 import android.webkit.WebResourceRequest;
 import android.webkit.WebSettings;
@@ -44,7 +46,7 @@ import com.clj.fastble.utils.HexUtil;
 import com.google.common.util.concurrent.ListenableFuture;
 import com.google.gson.Gson;
 import com.google.gson.reflect.TypeToken;
-import com.naz.sdkdemo.activity.ApplyTrademarkCompleteActivity;
+import com.kaopiz.kprogresshud.KProgressHUD;
 import com.naz.sdkdemo.activity.ble.comm.ObserverManager;
 import com.naz.sdkdemo.base.BaseActivity;
 import com.naz.sdkdemo.bean.PrintModule;
@@ -55,6 +57,8 @@ import com.naz.sdkdemo.helper.SerialPortManager;
 import com.naz.sdkdemo.http.ApiHelper;
 import com.naz.sdkdemo.utils.FastClickUtil;
 import com.naz.sdkdemo.utils.MyTools;
+import com.naz.sdkdemo.utils.NetworkSpeedTest;
+import com.naz.sdkdemo.utils.NetworkUtil;
 import com.naz.sdkdemo.utils.SPUtils;
 import com.naz.sdkdemo.weight.UserCache;
 import com.naz.sdkdemo.weight.XToast;
@@ -143,7 +147,13 @@ public class MainActivity extends BaseActivity {
 
     // 相机现在是否正在打开, 用于处理用户在照相机预览页面点击返回按钮的情况
     private boolean cameraIsOpening = false;
-    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
+    private BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
+    private KProgressHUD progressHUD2;
+    int netWorkType = SPUtils.getInt(Constants.NETWORK_TYPE);
+    NetworkUtil networkUtil;
+    long lastConnectTime = 0;
+    String networkTestUrl = "https://clouddevice.qingyaokeji.com/api/androidVersion";
+    Handler sendCommandhandler = new Handler();
 
     @Override
     protected int getLayoutResId() {
@@ -152,12 +162,19 @@ public class MainActivity extends BaseActivity {
 
     @Override
     protected void initView() {
+        networkUtil = new NetworkUtil(this);
         ll_nonet = findViewById(R.id.ll_nonet);
         ll_web = findViewById(R.id.ll_web);
         mWebView = findViewById(R.id.webview);
         previewView = findViewById(R.id.previewView);
         previewViewLayout = findViewById(R.id.rl_preview);
-
+        progressHUD2 = KProgressHUD.create(this)
+                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
+                .setLabel("正在寻找最佳网络")
+                .setDetailsLabel("请稍候")
+                .setCancellable(false)
+                .setAnimationSpeed(1)
+                .setDimAmount(0.5f);
         checkNet();
         findViewById(R.id.bt_ref).setOnClickListener(new View.OnClickListener(){
 
@@ -405,201 +422,325 @@ public class MainActivity extends BaseActivity {
     private AndroidInterface aIn;
 
     private class AndroidInterface {
-        /*
-         * @description: 通过这个接口传递最新的版本
-         */
+
         @JavascriptInterface
-        public void pushVersion(String currentVersionCode){
-            Log.e(TAG, "pushVersion");
-            String preVersionCode = SPUtils.getString("versionCode");
-            if(!preVersionCode.equals(currentVersionCode)) {
-                // 与之前的非空版本不一致则刷新缓存
+        public void swiftNetwork() {
+            try {
                 runOnUiThread(() -> {
-                    SPUtils.setString("versionCode", currentVersionCode);
-                    toRefreshData();
+                    toSwiftNetwork();
                 });
+            }catch (Exception e) {
+                XToast.showToast(e.getMessage());
+                uploadLogMessage(Arrays.toString(e.getStackTrace()) + "------>>" + e.getMessage(), "exception");
+            }
+        }
+
+        @JavascriptInterface
+        public void pushVersion(String currentVersionCode){
+            try {
+                Log.e(TAG, "pushVersion");
+                String preVersionCode = SPUtils.getString("versionCode");
+                if(!preVersionCode.equals(currentVersionCode)) {
+                    // 与之前的非空版本不一致则刷新缓存
+                    runOnUiThread(() -> {
+                        SPUtils.setString("versionCode", currentVersionCode);
+                        toRefreshData();
+                    });
+                }
+            }catch (Exception e) {
+                XToast.showToast(e.getMessage());
+                uploadLogMessage(Arrays.toString(e.getStackTrace()) + "------>>" + e.getMessage(), "exception");
             }
         }
 
         @JavascriptInterface
         public void takePhoto(String path, String name) {
-            Log.e(TAG, "takePhoto");
-            toTakePhoto(path, name);
+            try {
+                Log.e(TAG, "takePhoto");
+                toTakePhoto(path, name);
+            }catch (Exception e) {
+                XToast.showToast(e.getMessage());
+                uploadLogMessage(Arrays.toString(e.getStackTrace()) + "------>>" + e.getMessage(), "exception");
+            }
         }
 
         @JavascriptInterface
         public void openRecorder(boolean isShowPreview) {
-            Log.e(TAG, "openRecorder");
-            toOpenRecorder(isShowPreview);
+            try {
+                Log.e(TAG, "openRecorder");
+                toOpenRecorder(isShowPreview);
+            }catch (Exception e) {
+                XToast.showToast(e.getMessage());
+                uploadLogMessage(Arrays.toString(e.getStackTrace()) + "------>>" + e.getMessage(), "exception");
+            }
         }
 
         @JavascriptInterface
         public void getAllPort() {
-            // 遍历串口
-            SerialPortFinder finder = new SerialPortFinder();
-            String[] allDevicesPath = finder.getAllDevicesPath();
-            String str = String.join(",", allDevicesPath);
-            // 将结果返回给web页面
-            runOnUiThread(() -> mWebView.loadUrl("javascript:getAllPort('" + str + "')"));
+            try {
+                // 遍历串口
+                SerialPortFinder finder = new SerialPortFinder();
+                String[] allDevicesPath = finder.getAllDevicesPath();
+                String str = String.join(",", allDevicesPath);
+                // 将结果返回给web页面
+                runOnUiThread(() -> mWebView.loadUrl("javascript:getAllPort('" + str + "')"));
+            }catch (Exception e) {
+                XToast.showToast(e.getMessage());
+                uploadLogMessage(Arrays.toString(e.getStackTrace()) + "------>>" + e.getMessage(), "exception");
+            }
         }
 
         @JavascriptInterface
         public void getPortStatus(int scannerNum, int lightNum, int maxRetryNum) {
-            toGetPortStatus(scannerNum, lightNum, maxRetryNum);
+            try {
+               toGetPortStatus(scannerNum, lightNum, maxRetryNum);
+            }catch (Exception e) {
+                XToast.showToast(e.getMessage());
+                uploadLogMessage(Arrays.toString(e.getStackTrace()) + "------>>" + e.getMessage(), "exception");
+            }
         }
 
         @JavascriptInterface
         public void refreshData() {
-            Log.e(TAG, "clearCache");
-            runOnUiThread(() -> toRefreshData());
+            try {
+                Log.e(TAG, "clearCache");
+                runOnUiThread(() -> toRefreshData());
+            }catch (Exception e) {
+                XToast.showToast(e.getMessage());
+                uploadLogMessage(Arrays.toString(e.getStackTrace()) + "------>>" + e.getMessage(), "exception");
+            }
         }
 
         //打印
         @JavascriptInterface
         public void printF(String json) {
-            Log.e(TAG, "printF json"+json);
+            try {
+                Log.e(TAG, "printF json"+json);
 
-            Gson gson=new Gson();
-            Type type = new TypeToken<List<PrintModule>>(){}.getType();
-            List<PrintModule> data = gson.fromJson(json, type);
-            if (data == null) {
-                return;
+                Gson gson=new Gson();
+                Type type = new TypeToken<List<PrintModule>>(){}.getType();
+                List<PrintModule> data = gson.fromJson(json, type);
+                if (data == null) {
+                    return;
+                }
+                // startPrint(data);
+                startPrint_1(data);
+            }catch (Exception e) {
+                XToast.showToast(e.getMessage());
+                uploadLogMessage(Arrays.toString(e.getStackTrace()) + "------>>" + e.getMessage(), "exception");
             }
-            // startPrint(data);
-            startPrint_1(data);
         }
 
         @JavascriptInterface
         public void printF2(String json) {
-            Log.e(TAG, "printF2 json"+json);
+            try {
+                Log.e(TAG, "printF2 json"+json);
 
-            Gson gson=new Gson();
-            Type type = new TypeToken<List<PrintModule2>>(){}.getType();
-            List<PrintModule2> data = gson.fromJson(json, type);
-            if (data == null) {
-                return;
+                Gson gson=new Gson();
+                Type type = new TypeToken<List<PrintModule2>>(){}.getType();
+                List<PrintModule2> data = gson.fromJson(json, type);
+                if (data == null) {
+                    return;
+                }
+                startPrint2_1(data);
+            }catch (Exception e) {
+                XToast.showToast(e.getMessage());
+                uploadLogMessage(Arrays.toString(e.getStackTrace()) + "------>>" + e.getMessage(), "exception");
             }
-            startPrint2_1(data);
         }
 
         @JavascriptInterface
         public void printF3(String json) {
-            Log.e(TAG, "printF3 json"+json);
+            try {
+                Log.e(TAG, "printF3 json"+json);
 
-            Gson gson=new Gson();
-            Type type = new TypeToken<List<PrintModule3>>(){}.getType();
-            List<PrintModule3> data = gson.fromJson(json, type);
-            if (data == null) {
-                return;
+                Gson gson=new Gson();
+                Type type = new TypeToken<List<PrintModule3>>(){}.getType();
+                List<PrintModule3> data = gson.fromJson(json, type);
+                if (data == null) {
+                    return;
+                }
+                startPrint3(data);
+            }catch (Exception e) {
+                XToast.showToast(e.getMessage());
+                uploadLogMessage(Arrays.toString(e.getStackTrace()) + "------>>" + e.getMessage(), "exception");
             }
-            startPrint3(data);
         }
 
         @JavascriptInterface
         public void startScan(String name) {
-            String msg = "startScan name: " + name;
-            Log.e(TAG2, msg);
-            uploadLogMessage(msg, "ble");
+            try {
+                String msg = "startScan name: " + name;
+                Log.e(TAG2, msg);
+                uploadLogMessage(msg, "ble");
 
-            if (bluetoothAdapter != null) {
-                // 设备不支持蓝牙
-                boolean enabled = bluetoothAdapter.isEnabled();
-                if (enabled) {
-                    String msg2 = "系统蓝牙已打开";
-                    Log.e(TAG2, msg2);
-                    uploadLogMessage(msg2, "ble");
-                } else {
-                    String msg2 = "系统蓝牙未打开";
-                    Log.e(TAG2, msg2);
-                    uploadLogMessage(msg2, "ble");
+                if (bluetoothAdapter != null) {
+                    // 设备不支持蓝牙
+                    boolean enabled = bluetoothAdapter.isEnabled();
+                    if (enabled) {
+                        String msg2 = "系统蓝牙已打开";
+                        Log.e(TAG2, msg2);
+                        uploadLogMessage(msg2, "ble");
+                    } else {
+                        String msg2 = "系统蓝牙未打开";
+                        Log.e(TAG2, msg2);
+                        uploadLogMessage(msg2, "ble");
+                    }
                 }
-            }
 
-            checkPermissions(name);
+                checkPermissions(name);
+            }catch (Exception e) {
+                XToast.showToast(e.getMessage());
+                uploadLogMessage(Arrays.toString(e.getStackTrace()) + "------>>" + e.getMessage() + "------>>" + e.getMessage(), "exception");
+            }
         }
 
         @JavascriptInterface
         public void closeScan() {
-            String msg = "closeScan";
-            Log.e(TAG2, msg);
-            uploadLogMessage(msg, "ble");
-
-            toCloseScan();
+            try {
+                String msg = "closeScan";
+                Log.e(TAG2, msg);
+                uploadLogMessage(msg, "ble");
+                toCloseScan();
+            }catch (Exception e) {
+                XToast.showToast(e.getMessage());
+                uploadLogMessage(Arrays.toString(e.getStackTrace()) + "------>>" + e.getMessage(), "exception");
+            }
         }
 
         @JavascriptInterface
         public void openCamera(boolean isShowPreview) {
-            Log.e(TAG, "openCamera");
-            // 打开摄像头
-            toOpenCamera(isShowPreview);
+            try {
+                Log.e(TAG, "openCamera");
+                // 打开摄像头
+                toOpenCamera(isShowPreview);
+            }catch (Exception e) {
+                XToast.showToast(e.getMessage());
+                uploadLogMessage(Arrays.toString(e.getStackTrace()) + "------>>" + e.getMessage(), "exception");
+            }
         }
         @JavascriptInterface
         public void closeCamera() {
-            Log.e(TAG, "closeCamera");
-            toCloseCamera();
+            try {
+                Log.e(TAG, "closeCamera");
+                toCloseCamera();
+            }catch (Exception e) {
+                XToast.showToast(e.getMessage());
+                uploadLogMessage(Arrays.toString(e.getStackTrace()) + "------>>" + e.getMessage(), "exception");
+            }
         }
 
         @JavascriptInterface
         public void openPrinter() {
-            Log.e(TAG, "openPrinter");
-            connectUSB(searchUsb());
+            try {
+                Log.e(TAG, "openPrinter");
+                connectUSB(searchUsb());
+            }catch (Exception e) {
+                XToast.showToast(e.getMessage());
+                uploadLogMessage(Arrays.toString(e.getStackTrace()) + "------>>" + e.getMessage(), "exception");
+            }
         }
 
         @JavascriptInterface
         public void closePrinter() {
-            Log.e(TAG, "closePrinter");
-            closeUSB();
+            try {
+                Log.e(TAG, "closePrinter");
+                closeUSB();
+            }catch (Exception e) {
+                XToast.showToast(e.getMessage());
+                uploadLogMessage(Arrays.toString(e.getStackTrace()) + "------>>" + e.getMessage(), "exception");
+            }
         }
 
         @JavascriptInterface
         public void connectLight(String name) {
-            Log.e(TAG, "connectLight");
-            if(!FastClickUtil.isFastClick()) {
-                toConnectLight(name);
-                // XToast.showToast("connectLight");
+            try {
+                Log.e(TAG, "connectLight");
+                if(!FastClickUtil.isFastClick()) {
+                    toConnectLight(name);
+                    // XToast.showToast("connectLight");
+                }
+            }catch (Exception e) {
+                XToast.showToast(e.getMessage());
+                uploadLogMessage(Arrays.toString(e.getStackTrace()) + "------>>" + e.getMessage(), "exception");
             }
         }
 
         @JavascriptInterface
         public void controlLight(int address, int type) {
-            Log.e(TAG, "openLight"+"address="+address+",type="+type);
-            toOpenLight(address, type);
+            try {
+                Log.e(TAG, "openLight"+"address="+address+",type="+type);
+                toOpenLight(address, type);
+            }catch (Exception e) {
+                XToast.showToast(e.getMessage());
+                uploadLogMessage(Arrays.toString(e.getStackTrace()) + "------>>" + e.getMessage(), "exception");
+            }
         }
 
         @JavascriptInterface
         public void disConnectLight() {
-            Log.e(TAG, "closeLight");
-            toCloseLight();
+            try {
+                Log.e(TAG, "closeLight");
+                toCloseLight();
+            }catch (Exception e) {
+                XToast.showToast(e.getMessage());
+                uploadLogMessage(Arrays.toString(e.getStackTrace()) + "------>>" + e.getMessage(), "exception");
+            }
         }
 
         @JavascriptInterface
         public void getPort() {
-            Log.e(TAG, "getPort");
-            mWebView.loadUrl("javascript:getPort('" + UserCache.getSerialPortName() + "')");
+            try {
+                Log.e(TAG, "getPort");
+                mWebView.loadUrl("javascript:getPort('" + UserCache.getSerialPortName() + "')");
+            }catch (Exception e) {
+                XToast.showToast(e.getMessage());
+                uploadLogMessage(Arrays.toString(e.getStackTrace()) + "------>>" + e.getMessage(), "exception");
+            }
         }
 
         @JavascriptInterface
         public void getDeviceId() {
-            Log.e(TAG, "getDeviceId");
-            String deviceId = UserCache.getDeviceId();
-            runOnUiThread(() -> mWebView.loadUrl("javascript:getDeviceId('" + deviceId + "')"));
+            try {
+                Log.e(TAG, "getDeviceId");
+                String deviceId = UserCache.getDeviceId();
+                runOnUiThread(() -> mWebView.loadUrl("javascript:getDeviceId('" + deviceId + "')"));
+            }catch (Exception e) {
+                XToast.showToast(e.getMessage());
+                uploadLogMessage(Arrays.toString(e.getStackTrace()) + "------>>" + e.getMessage(), "exception");
+            }
         }
 
         @JavascriptInterface
         public void connectPort(String name) {
-            Log.e(TAG, "connectPort");
-            toConnectPort(name);
+            try {
+                Log.e(TAG, "connectPort");
+                toConnectPort(name);
+            }catch (Exception e) {
+                XToast.showToast(e.getMessage());
+                uploadLogMessage(Arrays.toString(e.getStackTrace()) + "------>>" + e.getMessage(), "exception");
+            }
         }
 
         @JavascriptInterface
         public void disConnectPort(String name) {
-            Log.e(TAG, "disConnectPort");
-            disconnectPortSingle(name);
+            try {
+                Log.e(TAG, "disConnectPort");
+                disconnectPortSingle(name);
+            }catch (Exception e) {
+                XToast.showToast(e.getMessage());
+                uploadLogMessage(Arrays.toString(e.getStackTrace()) + "------>>" + e.getMessage(), "exception");
+            }
         }
 
         @JavascriptInterface
         public void disConnectPortAll() {
-            toDisconnectPortAll();
+            try {
+               toDisconnectPortAll();
+            }catch (Exception e) {
+                XToast.showToast(e.getMessage());
+                uploadLogMessage(Arrays.toString(e.getStackTrace()) + "------>>" + e.getMessage(), "exception");
+            }
         }
     }
     // -------------------------------------WebInterface相关方法结束----------------------------
@@ -647,8 +788,6 @@ public class MainActivity extends BaseActivity {
         return deletedFiles;
     }
 
-
-    private Handler sendCommandhandler = new Handler();
     private List<String> sendCommands = new ArrayList<String>(){
         {
             add("07C60408008A09FE94");
@@ -1580,7 +1719,7 @@ public class MainActivity extends BaseActivity {
                     uploadLogMessage(msg, "ble");
 
                     mWebView.loadUrl("javascript:responseCode('2')");
-                    XToast.showToast("未找到匹配蓝牙,请等待15秒后重试");
+                    XToast.showToast("未找到匹配蓝牙,请后重试");
                     mBleDevice = null;
                 }
             }
@@ -1600,7 +1739,7 @@ public class MainActivity extends BaseActivity {
                 Log.e(TAG2, msg);
                 uploadLogMessage(msg, "ble");
 
-                XToast.showToast("蓝牙连接失败,请等待15秒后重试");
+                XToast.showToast("蓝牙连接失败,请后重试");
 //                Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
                 mWebView.loadUrl("javascript:responseCode('2')");
             }
@@ -1833,6 +1972,187 @@ public class MainActivity extends BaseActivity {
 
     // ------------------------------灯相关的方法结束--------------------------------------
 
+    // region-----------------------------切换网络开始----------------------
+    private void toSwiftNetwork() {
+        progressHUD2.show();
+        initNetwork();
+    }
+
+    private void initNetwork() {
+        // 查询上次连接成功的网络
+        if(netWorkType <= 0) {
+            // 之前没有连接成功过
+            // 初始化网络
+            doInitNetwork();
+        } else if(netWorkType == 1) {
+            // 之前连的是以太网
+            NetworkSpeedTest.testNetSpeed(networkTestUrl, netSpeed -> {
+                if (netSpeed == 0) {
+                    doInitNetwork();
+                } else {
+                    // 以太网测速正常
+                    SPUtils.setInt(Constants.NETWORK_TYPE, 1);
+//                    netWorkType = 1;
+                    new Handler(Looper.getMainLooper()).post(() -> {
+                        lastConnectTime = System.currentTimeMillis();
+                        XToast.showToast("正在使用以太网");
+                        progressHUD2.dismiss();
+                    });
+                }
+            });
+        } else if(netWorkType == 2) {
+            // 之前连的是wifi
+            NetworkSpeedTest.testNetSpeed(networkTestUrl, netSpeed -> {
+                if (netSpeed == 0) {
+                    doInitNetwork();
+                } else {
+                    // wifi测速正常
+                    SPUtils.setInt(Constants.NETWORK_TYPE, 2);
+//                    netWorkType = 2;
+                    new Handler(Looper.getMainLooper()).post(() -> {
+                        lastConnectTime = System.currentTimeMillis();
+                        XToast.showToast("正在使用Wifi");
+                        progressHUD2.dismiss();
+                    });
+                }
+            });
+        } else if(netWorkType == 3 && (System.currentTimeMillis() - lastConnectTime > 1000 * 60 * 60)){
+            // 使用移动网络超过1小时
+            // 初始化网络
+            doInitNetwork();
+        } else {
+            // 之前连的是移动网络
+            NetworkSpeedTest.testNetSpeed(networkTestUrl, netSpeed -> {
+                if (netSpeed == 0) {
+                    doInitNetwork();
+                } else {
+                    // 移动网络测速正常
+                    SPUtils.setInt(Constants.NETWORK_TYPE, 3);
+//                    netWorkType = 3;
+                    new Handler(Looper.getMainLooper()).post(() -> {
+                        lastConnectTime = System.currentTimeMillis();
+                        XToast.showToast("正在使用移动网络");
+                        progressHUD2.dismiss();
+                    });
+                }
+            });
+        }
+    }
+    private void doInitNetwork() {
+        // 打开以太网
+        networkUtil.enableEthernet();
+        // 打开wifi
+        if(!networkUtil.isWifiEnabled()) {
+            networkUtil.enableWifi();
+        }
+        // 等待初始化完成
+        sendCommandhandler.postDelayed(() -> testEtherNet(1), 5000);
+        // 二次确认
+        sendCommandhandler.postDelayed(() -> testEtherNet(2), 10000);
+    }
+    private void testEtherNet(int count) {
+        // 判断以太网是否连接
+        boolean ethernetConnected = networkUtil.isEthernetConnected();
+        Log.i(TAG, "testEtherNet: " + ethernetConnected);
+        if(ethernetConnected) {
+            // 测速
+            NetworkSpeedTest.testNetSpeed(networkTestUrl, netSpeed -> {
+                if (netSpeed == 0) {
+                    // 网络不通
+                    networkUtil.disableEthernet();
+                    // 进行下一个测试
+                    sendCommandhandler.postDelayed(() -> testWifi(count), 2000);
+                } else {
+                    // 以太网测速正常
+//                    netWorkType = 1;
+                    SPUtils.setInt(Constants.NETWORK_TYPE, 1);
+                    new Handler(Looper.getMainLooper()).post(() -> {
+                        if(count == 1) {
+                            XToast.showToast("正在使用以太网");
+                        } else if (count == 2) {
+                            // 以第二次连接的结果为准
+                            lastConnectTime = System.currentTimeMillis();
+                            XToast.showToast("确认使用以太网");
+                            progressHUD2.dismiss();
+                        }
+                    });
+                }
+            });
+        } else {
+            sendCommandhandler.postDelayed(() -> testWifi(count), 2000);
+        }
+    }
+    private void testWifi(int count) {
+        boolean wifiConnected = networkUtil.isWifiConnected();
+        Log.i(TAG, "testWifi: " + wifiConnected);
+        if(wifiConnected) {
+            // 测速
+            NetworkSpeedTest.testNetSpeed(networkTestUrl, netSpeed -> {
+                if (netSpeed == 0) {
+                    networkUtil.disableWifi();
+                    // 进行下一个测试
+                    sendCommandhandler.postDelayed(() -> testMobileData(count), 2000);
+                } else {
+                    // wifi测速正常
+//                    netWorkType = 2;
+                    SPUtils.setInt(Constants.NETWORK_TYPE, 2);
+                    new Handler(Looper.getMainLooper()).post(() -> {
+                        if(count == 1) {
+                            Log.i(TAG, "testWifi: 正在使用Wifi");
+                            XToast.showToast("正在使用Wifi");
+                        }else if(count == 2) {
+                            // 以第二次连接的结果为准
+                            lastConnectTime = System.currentTimeMillis();
+                            Log.i(TAG, "testWifi: 确认使用Wifi");
+                            XToast.showToast("确认使用Wifi");
+                            progressHUD2.dismiss();
+                        }
+                    });
+                }
+            });
+        }else{
+            sendCommandhandler.postDelayed(() -> testMobileData(count), 2000);
+        }
+    }
+    private void testMobileData(int count) {
+        boolean mobileDataConnected = networkUtil.isMobileDataConnected(this);
+        Log.i(TAG, "testMobileData: " + mobileDataConnected);
+        if(mobileDataConnected) {
+            // 测速
+            NetworkSpeedTest.testNetSpeed(networkTestUrl, netSpeed -> {
+                if (netSpeed == 0) {
+                    if(count == 1) {
+                        XToast.showToast("没有可用网络");
+                    } else if (count == 2) {
+                        XToast.showToast("确认没有可用网络");
+                        progressHUD2.dismiss();
+                    }
+                } else {
+                    // 移动网络测速正常
+//                    netWorkType = 3;
+                    SPUtils.setInt(Constants.NETWORK_TYPE, 3);
+                    new Handler(Looper.getMainLooper()).post(() -> {
+                        if(count == 1) {
+                            XToast.showToast("正在使用移动数据");
+                        } else if(count == 2) {
+                            lastConnectTime = System.currentTimeMillis();
+                            XToast.showToast("确认使用移动数据");
+                            progressHUD2.dismiss();
+                        }
+                    });
+                }
+            });
+        } else {
+            if(count == 1) {
+                XToast.showToast("没有可用网络");
+            } else if (count == 2) {
+                XToast.showToast("确认没有可用网络");
+                progressHUD2.dismiss();
+            }
+        }
+    }
+    // endregion-----------------------------切换网络结束-----------------------
+
     // ------------------------------连接及断开除灯之外的其他串口的相关方法开始------------------
     private List<SerialPortManager> mPortList = new ArrayList<>();
     private void toConnectPort(String name){
@@ -1926,7 +2246,7 @@ public class MainActivity extends BaseActivity {
             }
         }
     }
-    // ------------------------------连接及断开除灯之外的其他串口的相关方法开始------------------
+    // ------------------------------连接及断开除灯之外的其他串口的相关方法结束------------------
     @Override
     protected void onDestroy() {
         super.onDestroy();
@@ -2024,7 +2344,7 @@ public class MainActivity extends BaseActivity {
         }
     }
     private void uploadLogMessage(String message, String type) {
-        String da = UserCache.getDeviceId() + "------>>" + message;
+        String da = "扫标机" + "------>>" + UserCache.getDeviceId() + "------>>" + message;
         String s = BaseApplication.appendDataToLogFile(da, Constants.BLE_LOG_FILE_NAME);
         ApiHelper.uploadExceptionLog(MainActivity.this, s, type, (code, msg, data1) -> {
 

+ 1 - 0
app/src/main/java/com/naz/sdkdemo/comm/Constants.java

@@ -57,6 +57,7 @@ public class Constants {
     public static final String SERIAL_RATE = "SERIAL_RATE";
     public static final String BLE_LOG_FILE_NAME = "BLE_LOG_FILE_NAME";
     public static final String EXCEPTION_LOG_FILE_NAME = "EXCEPTION_LOG_FILE_NAME";
+    public static final String NETWORK_TYPE = "NETWORK_TYPE";
 
     public static String mark_speed = "01f4";//500转十进制,高低位
     public static String mark_num = "0001";//1

+ 32 - 0
app/src/main/java/com/naz/sdkdemo/utils/NetworkSpeedTest.java

@@ -0,0 +1,32 @@
+package com.naz.sdkdemo.utils;
+
+import java.net.HttpURLConnection;
+import java.net.URL;
+
+public class NetworkSpeedTest {
+
+    public interface SpeedTestListener {
+        void onSpeedTestComplete(long netSpeed);
+    }
+
+    public static void testNetSpeed(String url, final SpeedTestListener listener) {
+        new Thread(() -> {
+            try {
+                long startTime = System.currentTimeMillis();
+                HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
+                connection.setRequestMethod("GET");
+                connection.connect();
+
+                long endTime = System.currentTimeMillis();
+                long duration = endTime - startTime;
+
+                listener.onSpeedTestComplete(duration);
+
+                connection.disconnect();
+            } catch (Exception e) {
+                listener.onSpeedTestComplete(0);
+                e.printStackTrace();
+            }
+        }).start();
+    }
+}

+ 131 - 0
app/src/main/java/com/naz/sdkdemo/utils/NetworkUtil.java

@@ -0,0 +1,131 @@
+package com.naz.sdkdemo.utils;
+
+import android.content.Context;
+import android.net.ConnectivityManager;
+import android.net.NetworkInfo;
+import android.net.wifi.WifiManager;
+import android.util.Log;
+
+import java.io.IOException;
+
+public class NetworkUtil {
+
+    private Context context;
+    private WifiManager wifiManager;
+    public NetworkUtil(Context context) {
+        wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
+        this.context = context;
+    }
+
+    // 判断Wi-Fi是否开启
+    public boolean isWifiEnabled() {
+        return wifiManager.isWifiEnabled();
+    }
+
+    // 打开Wi-Fi
+    public void enableWifi() {
+        if (!isWifiEnabled()) {
+            wifiManager.setWifiEnabled(true);
+        }
+    }
+
+    // 关闭Wi-Fi
+    public void disableWifi() {
+        if (isWifiEnabled()) {
+            wifiManager.setWifiEnabled(false);
+        }
+    }
+
+    // 判断Wi-Fi是否连接: 注意开启了但是没有连接的情况
+    public boolean isWifiConnected() {
+        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
+        NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
+        return networkInfo != null && networkInfo.isConnected();
+    }
+
+    // 判断移动数据是否开启
+    public boolean isMobileDataConnected(Context context) {
+        ConnectivityManager connectivityManager = (ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
+        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
+        if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
+            // 旧版本的 API 不区分有线和无线网络
+            // 可以尝试根据连接类型进行判断
+            if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    // 设置网络的优先级
+    public void setNetworkPriority(Context context, int type) {
+        if(isEthernetConnected()) {
+            // 设置以太网络优先
+            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
+            connectivityManager.setNetworkPreference(type);
+        } else if(isWifiConnected()){
+            // 设置wifi优先
+            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
+            connectivityManager.setNetworkPreference(type);
+        } else if (isMobileDataConnected(context)) {
+            // 设置移动网络优先
+            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
+            connectivityManager.setNetworkPreference(type);
+        }
+    }
+
+    /**
+     * 检查设备是否连接到了有线网络
+     *
+     * @return 如果连接到了有线网络返回 true,否则返回 false
+     */
+    public boolean isEthernetConnected() {
+        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
+        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
+        if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
+            // 旧版本的 API 不区分有线和无线网络
+            // 可以尝试根据连接类型进行判断
+            if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+
+    public void enableEthernet() {
+        try {
+            // 创建ProcessBuilder实例,准备执行命令
+            ProcessBuilder pb = new ProcessBuilder("su", "-c", "ifconfig eth0 up");
+            // 启动进程
+            Process process = pb.start();
+            // 等待命令执行完成
+            int exitCode = process.waitFor();
+            if (exitCode == 0) {
+                Log.i("NetworkUtil",  "以太网打开成功");
+            } else {
+                Log.i("NetworkUtil", "以太网打开失败");
+            }
+        } catch (IOException | InterruptedException e) {
+            e.printStackTrace();
+        }
+    }
+
+    public void disableEthernet() {
+        try {
+            // 创建ProcessBuilder实例,准备执行命令
+            ProcessBuilder pb = new ProcessBuilder("su", "-c", "ifconfig eth0 down");
+            // 启动进程
+            Process process = pb.start();
+            // 等待命令执行完成
+            int exitCode = process.waitFor();
+            if (exitCode == 0) {
+                Log.i("NetworkUtil",  "以太网关闭成功");
+            } else {
+                Log.i("NetworkUtil", "以太网关闭并失败");
+            }
+        } catch (IOException | InterruptedException e) {
+            e.printStackTrace();
+        }
+    }
+}

+ 3 - 3
app/src/main/res/values/strings.xml

@@ -3,10 +3,10 @@
 
     <string-array name="nav_tab_list">
         <item>首页</item>
-<!--        <item>发/收货</item>-->
+        <!--        <item>发/收货</item>-->
         <item>扫描</item>
-<!--        <item>安装</item>-->
-<!--        <item>验收</item>-->
+        <!--        <item>安装</item>-->
+        <!--        <item>验收</item>-->
         <item>我的</item>
     </string-array>
     <string name="none_paired">没有配对</string>