Browse Source

add: 大小版本更新

huwanxiao 1 year ago
parent
commit
ca218af0c7

+ 7 - 0
app/src/main/java/com/naz/sdkdemo/AppConfig.java

@@ -9,6 +9,13 @@ import com.naz.sdkdemo.utils.SPUtils;
  */
 public class AppConfig {
     public static final boolean IS_DEBUG =true;//true打印数据
+
+    public static final String APP_VERSION_CODE = "2.24.0918";//true打印数据
+    public static final String APP_VERSION = "正式包-" + APP_VERSION_CODE;//true打印数据
+    public static final String REMARK = "1. 新增: 大小版本更新\n" +
+            "2.新增: 添加全局日志的捕获\n" +
+            "3.更新: 打印格式的调整";
+
     // public  static String INTERFACE_URL = "http://121.37.173.82:82/";//线上
 //    public  static String INTERFACE_URL = "http://121.41.102.225:82/";//测试
     // public static String INTERFACE_URL = "";//正式

+ 358 - 83
app/src/main/java/com/naz/sdkdemo/MainActivity.java

@@ -52,9 +52,12 @@ import com.naz.sdkdemo.base.BaseActivity;
 import com.naz.sdkdemo.bean.PrintModule;
 import com.naz.sdkdemo.bean.PrintModule2;
 import com.naz.sdkdemo.bean.PrintModule3;
+import com.naz.sdkdemo.bean.VersionBean;
 import com.naz.sdkdemo.comm.Constants;
+import com.naz.sdkdemo.dialog.VersionUpdateDialog;
 import com.naz.sdkdemo.helper.SerialPortManager;
 import com.naz.sdkdemo.http.ApiHelper;
+import com.naz.sdkdemo.utils.DownloadService;
 import com.naz.sdkdemo.utils.FastClickUtil;
 import com.naz.sdkdemo.utils.MyTools;
 import com.naz.sdkdemo.utils.NetworkSpeedTest;
@@ -119,7 +122,8 @@ import android_serialport_api.SerialPortFinder;
 public class MainActivity extends BaseActivity {
     private final String TAG = "HomeActivity";
     private final String TAG2 = "BleBle";
-
+    private static final int REQUEST_CODE_OPEN_GPS = 1;
+    private static final int REQUEST_CODE_PERMISSION_LOCATION = 2;
     private WebView mWebView;
     private LinearLayout ll_nonet;
     private LinearLayout ll_web;
@@ -155,6 +159,8 @@ public class MainActivity extends BaseActivity {
     String networkTestUrl = "https://clouddevice.qingyaokeji.com/api/androidVersion";
     Handler sendCommandhandler = new Handler();
 
+    private DownloadService downloadService = new DownloadService();
+
     @Override
     protected int getLayoutResId() {
         return R.layout.activity_home_web;
@@ -397,7 +403,7 @@ public class MainActivity extends BaseActivity {
 
         Log.e("------->","-------->"+UserCache.getSerialName());
     }
-    // -------------------------------------WebInterface相关方法开始----------------------------
+    //region -------------------------------------WebInterface相关方法开始----------------------------
     String mUrl = "http://192.168.0.133:8082";
     private void checkNet() {
         if (!MyTools.isNetworkAvailable(getApplicationContext())) {
@@ -424,6 +430,17 @@ public class MainActivity extends BaseActivity {
     private class AndroidInterface {
 
         @JavascriptInterface
+        public void checkVersionUpdate() {
+            try {
+                Log.e(TAG, "checkVersionUpdate");
+                toCheckVersionUpdate();
+            }catch (Exception e) {
+                XToast.showToast(e.getMessage());
+                uploadLogMessage(Arrays.toString(e.getStackTrace()) + "------>>" + e.getMessage(), "exception");
+            }
+        }
+
+        @JavascriptInterface
         public void swiftNetwork() {
             try {
                 Log.e(TAG, "swiftNetwork");
@@ -744,10 +761,9 @@ public class MainActivity extends BaseActivity {
             }
         }
     }
-    // -------------------------------------WebInterface相关方法结束----------------------------
+    //endregion -------------------------------------WebInterface相关方法结束----------------------------
 
-    // -------------------------------------获取usb口状态开始-----------------------------------
-    // todo 暂时放在这里
+    //region -------------------------------------清除缓存开始-----------------------------------
     private void toRefreshData() {
         try {
             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // 清除cookie
@@ -788,7 +804,9 @@ public class MainActivity extends BaseActivity {
         }
         return deletedFiles;
     }
+    //endregion -------------------------------------清除缓存结束-----------------------------------
 
+    //region -------------------------------------获取usb口状态开始-----------------------------------
     private List<String> sendCommands = new ArrayList<String>(){
         {
             add("07C60408008A09FE94");
@@ -973,9 +991,9 @@ public class MainActivity extends BaseActivity {
 
 
     }
-    // -------------------------------------获取usb口状态结束---------------------------------
+    //endregion -------------------------------------获取usb口状态结束---------------------------------
 
-    // -------------------------------------拍照相关方法结束----------------------------------
+    //region -------------------------------------拍照相关方法结束----------------------------------
     int retryCount = 0;
     int maxRetries = 10;
     private void toCloseCamera() {
@@ -1199,9 +1217,9 @@ public class MainActivity extends BaseActivity {
         File imageFile = new File(picturesDir, imageName);
         return imageFile.exists() ? imageFile.getAbsolutePath() :"";
     }
-    // -------------------------------------拍照相关方法结束---------------------------------
+    //endregion -------------------------------------拍照相关方法结束---------------------------------
 
-    // -------------------------------------打印相关方法开始---------------------------------
+    //region -------------------------------------打印相关方法开始---------------------------------
     static int mPot = 8;//mm转像素8倍
     static int mWFont = 24;//字体宽度
     static int mHFont = 24;//字体高度
@@ -1602,9 +1620,9 @@ public class MainActivity extends BaseActivity {
         }
         return isChinese;
     }
-    // -------------------------------------------------打印相关方法结束-----------------------------------
+    //endregion -------------------------------------------------打印相关方法结束-----------------------------------
 
-    // -------------------------------------------------蓝牙相关方法开始-----------------------------------
+    //region -------------------------------------------------蓝牙相关方法开始-----------------------------------
     //关闭蓝牙扫码器
     BleDevice mBleDevice;
     BluetoothGattCharacteristic mCharacteristic;
@@ -1636,6 +1654,68 @@ public class MainActivity extends BaseActivity {
         BleManager.getInstance().initScanRule(scanRuleConfig);
     }
 
+    private void checkPermissions(String name) {
+        bleName = name;
+        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
+        if (!bluetoothAdapter.isEnabled()) {
+            Toast.makeText(this, getString(R.string.please_open_blue), Toast.LENGTH_LONG).show();
+            return;
+        }
+
+        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
+        List<String> permissionDeniedList = new ArrayList<>();
+        for (String permission : permissions) {
+            int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
+            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
+                onPermissionGranted(permission);
+            } else {
+                permissionDeniedList.add(permission);
+            }
+        }
+        if (!permissionDeniedList.isEmpty()) {
+            Log.e("------->","----->checkPermissions permissionDeniedList="+permissionDeniedList);
+            String[] deniedPermissions = permissionDeniedList.toArray(new String[permissionDeniedList.size()]);
+            ActivityCompat.requestPermissions(this, deniedPermissions, REQUEST_CODE_PERMISSION_LOCATION);
+        }
+    }
+
+    private void onPermissionGranted(String permission) {
+        Log.e("------->","----->onPermissionGranted permission="+permission);
+        switch (permission) {
+            case Manifest.permission.ACCESS_FINE_LOCATION:
+                setScanRule();
+                startScan(bleName);
+//                Log.e("------->","----->checkGPSIsOpen="+checkGPSIsOpen());
+//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !checkGPSIsOpen()) {
+//                    new AlertDialog.Builder(this)
+//                            .setTitle(R.string.notifyTitle)
+//                            .setMessage(R.string.gpsNotifyMsg)
+//                            .setNegativeButton(R.string.cancel,
+//                                    new DialogInterface.OnClickListener() {
+//                                        @Override
+//                                        public void onClick(DialogInterface dialog, int which) {
+//                                            finish();
+//                                        }
+//                                    })
+//                            .setPositiveButton(R.string.setting,
+//                                    new DialogInterface.OnClickListener() {
+//                                        @Override
+//                                        public void onClick(DialogInterface dialog, int which) {
+//                                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
+//                                            startActivityForResult(intent, REQUEST_CODE_OPEN_GPS);
+//                                        }
+//                                    })
+//
+//                            .setCancelable(false)
+//                            .show();
+//                } else {
+//                    setScanRule();
+//                    startScan(bleName);
+//                }
+                break;
+        }
+    }
+
     //开始蓝牙扫码器
     private void startScan(String name) {
 //        Toast.makeText(MainActivity.this, "开始连接", Toast.LENGTH_SHORT).show();
@@ -1844,9 +1924,7 @@ public class MainActivity extends BaseActivity {
             }
         });
     }
-    // --------------------------蓝牙相关方法结束--------------------------
 
-    // --------------------------打印机相关方法结束--------------------------
     public String hexStringToGbk(String hexString) {
         byte[] bytes = new byte[hexString.length() / 2];
         for (int i = 0; i < hexString.length(); i += 2) {
@@ -1861,7 +1939,9 @@ public class MainActivity extends BaseActivity {
             return null;
         }
     }
+    //endregion --------------------------蓝牙相关方法结束--------------------------
 
+    // region --------------------------打印机相关方法开始--------------------------
     IDeviceConnection curConnect = null;
     private void connectUSB(String pathName){
         if (curConnect!=null){
@@ -1888,9 +1968,9 @@ public class MainActivity extends BaseActivity {
             curConnect.close();
         }
     }
-    // --------------------------打印机相关方法结束--------------------------
+    // endregion --------------------------打印机相关方法结束--------------------------
 
-    // --------------------------灯相关的方法开始----------------------------
+    // region --------------------------灯相关的方法开始----------------------------
     private IConnectListener connectListener = new IConnectListener() {
         @Override
         public void onStatus(int code, String connInfo, String msg) {
@@ -1971,7 +2051,7 @@ public class MainActivity extends BaseActivity {
         }
     }
 
-    // ------------------------------灯相关的方法结束--------------------------------------
+    //endregion ------------------------------灯相关的方法结束--------------------------------------
 
     // region-----------------------------切换网络开始----------------------
     private void toSwiftNetwork() {
@@ -2155,7 +2235,261 @@ public class MainActivity extends BaseActivity {
     }
     // endregion-----------------------------切换网络结束-----------------------
 
-    // ------------------------------连接及断开除灯之外的其他串口的相关方法开始------------------
+    // region -----------------------------大小版本更新开始----------------------
+    private void toCheckVersionUpdate() {
+        ApiHelper.versionInfoList(this, 1, "sbj",(code, msg, data) -> {
+            // 获取稳定的版本号
+            ApiHelper.stableVersionInfo(this, "androidT", (code2, msg2, data2) -> {
+                // 获取版本列表
+                List<VersionBean> versionBeanList = new ArrayList<>();
+                if(data instanceof List) {
+                    List<?> content = (ArrayList<?>) data;
+                    for (Object o : content) {
+                        VersionBean item = (VersionBean) o;
+                        if(item.type.equals("1")) {
+                            versionBeanList.add(item);
+                        }
+                    }
+                }
+                // 对返回的apk列表信息进行数据解析
+                versionBeanList = parseVersionInfo(versionBeanList);
+                Log.i(TAG, "checkVersionUpdate: " + JSONObject.toJSONString(versionBeanList));
+                // 当前apk的版本
+                String currentVersion = AppConfig.APP_VERSION_CODE;
+                Log.i(TAG, "currentVersion: " + currentVersion);
+                String[] currentVersionSplit = currentVersion.split("[.]");
+                if(currentVersionSplit == null || currentVersionSplit.length != 3) {
+                    XToast.showToast("当前版本格式解析错误");
+                    return;
+                }
+                // 指定的apk版本
+                String publicVersion = "";
+                if(data2 instanceof VersionBean) {
+                    VersionBean item = (VersionBean) data2;
+                    publicVersion = item.version;
+                }
+                Log.i(TAG, "publicVersion: " + currentVersion);
+                // 从更新列表中筛选出指定的apk版本
+                VersionBean specifyVersion = null;
+                for (VersionBean bean : versionBeanList) {
+                    // 判断是否为指定的apk生产版本版本
+                    if(bean.versionCode.equals(publicVersion) && bean.type.equals("1")) {
+                        specifyVersion = bean;
+                        break;
+                    }
+                }
+                if(specifyVersion == null) {
+                    XToast.showToast("未找到指定版本");
+                    return;
+                }
+                if(specifyVersion != null && specifyVersion.checkExtraFields()) {
+                    // 将本地的版本与指定的apk版本进行比对
+                    // 先进行大版本更新
+                    if (currentVersionSplit[0].compareTo(specifyVersion.bigVersion) < 0) {
+                        // 如果当前版本的大版本比较指定的大版本小,那么应该自动更新
+                        loadingLabel = "正在更新版本中";
+                        loadingDetailLabel = "请稍候";
+                        showLoading();
+                        downloadService.downloadApk(MainActivity.this, specifyVersion.load);
+                    } else if (currentVersionSplit[0].equals(specifyVersion.bigVersion)) {
+                        String noLongerVersion = SPUtils.getString(Constants.IS_SHOW_VERSION_UPDATE_DIALOG);
+                        if (!noLongerVersion.equals(specifyVersion.versionCode)) {
+                            // 如果大版本相同则判断小版本
+                            if (currentVersionSplit[2].compareTo(specifyVersion.smallVersion) < 0) {
+                                // 弹出版本更新弹窗
+                                VersionBean finalSpecifyVersion = specifyVersion;
+                                VersionUpdateDialog dialog = new VersionUpdateDialog(this, new VersionUpdateDialog.OnBtnClickListener() {
+                                    @Override
+                                    public void OnCommitClickListener(VersionUpdateDialog dialog, View clickView) {
+                                        loadingLabel = "正在更新版本中";
+                                        loadingDetailLabel = "请稍候";
+                                        showLoading();
+                                        downloadService.downloadApk(MainActivity.this, finalSpecifyVersion.load);
+                                        dialog.dismiss();
+                                    }
+
+                                    @Override
+                                    public void OnCloseListener(VersionUpdateDialog dialog, View clickView) {
+                                        dialog.dismiss();
+                                    }
+
+                                    @Override
+                                    public void OnNoLongerListener(VersionUpdateDialog dialog, View clickView) {
+                                        // 记录下次不再提示的版本的版本号
+                                        // 该版本是否点了不再提醒
+                                        SPUtils.setString(Constants.IS_SHOW_VERSION_UPDATE_DIALOG, finalSpecifyVersion.versionCode);
+                                        // 当下次的大小版本大于这个版本的时候依旧会提示
+                                        dialog.dismiss();
+                                    }
+                                }, "有新版本可以更新: " + currentVersion + " --> " + publicVersion + "\n" + specifyVersion.remark, false, "立即更新");
+                                dialog.show();
+                            }
+                        }
+                    }
+                } else {
+                    XToast.showToast("目标版本信息解析错误");
+                }
+            });
+        });
+
+
+//        // TODO 测试代码
+//        // 当前apk的版本
+//        String currentVersion = "3.24.0906";
+//        String[] currentVersionSplit = currentVersion.split("[.]");
+//        if(currentVersionSplit == null || currentVersionSplit.length != 3) {
+//            XToast.showToast("当前版本格式解析错误");
+//            return;
+//        }
+//        // 指定的apk版本
+//        String publicVersion = "3.24.0908";
+//        // 可下载的apk列表
+//        List<VersionBean> beanArrayList = new ArrayList<>();
+//        VersionBean versionBean = new VersionBean();
+//        versionBean.load = "https://t9.qingyaokeji.com/dwy/updateprod0906.apk";
+//        versionBean.remark = "更新文案";
+//        versionBean.type = "1";
+//        versionBean.version = "测试包-3.24.0908";
+//        beanArrayList.add(versionBean);
+//        // 对返回的apk列表信息进行数据解析
+//        List<VersionBean> versionBeanList = parseVersionInfo(beanArrayList);
+//        // 从更新列表中筛选出指定的apk版本
+//        VersionBean specifyVersion = null;
+//        for (VersionBean bean : versionBeanList) {
+//            // 判断是否为指定的apk生产版本版本
+//            if(bean.versionCode.equals(publicVersion) && bean.type.equals("1")) {
+//                specifyVersion = bean;
+//                break;
+//            }
+//        }
+//        if(specifyVersion == null) {
+//            XToast.showToast("未找到指定版本");
+//            return;
+//        }
+//        // 找到了指定版本并且数据解析正确
+//        if(specifyVersion != null && specifyVersion.checkExtraFields()) {
+//            // 将本地的版本与指定的apk版本进行比对
+//            // 先进行大版本更新
+//            if(currentVersionSplit[0].compareTo(specifyVersion.bigVersion) < 0) {
+//                // 如果当前版本的大版本比较指定的大版本小,那么应该自动更新
+//                downloadService.downloadApk(NewMainActivity.this, specifyVersion.load);
+//            } else if(currentVersionSplit[0].equals(specifyVersion.bigVersion)) {
+//                String noLongerVersion = SPUtils.getString(Constants.IS_SHOW_VERSION_UPDATE_DIALOG);
+//                if(!noLongerVersion.equals(specifyVersion.versionCode)) {
+//                    // 如果大版本相同则判断小版本
+//                    if(currentVersionSplit[2].compareTo(specifyVersion.smallVersion) < 0) {
+//                        // 弹出版本更新弹窗
+//                        VersionBean finalSpecifyVersion = specifyVersion;
+//                        VersionUpdateDialog dialog = new VersionUpdateDialog(this, new VersionUpdateDialog.OnBtnClickListener() {
+//                            @Override
+//                            public void OnCommitClickListener(VersionUpdateDialog dialog, View clickView) {
+//                                loadingLabel = "正在下载中";
+//                                loadingDetailLabel = "请稍候";
+//                                showLoading();
+//                                downloadService.downloadApk(NewMainActivity.this, finalSpecifyVersion.load);
+//                                dialog.dismiss();
+//                            }
+//
+//                            @Override
+//                            public void OnCloseListener(VersionUpdateDialog dialog, View clickView) {
+//                                dialog.dismiss();
+//                            }
+//
+//                            @Override
+//                            public void OnNoLongerListener(VersionUpdateDialog dialog, View clickView) {
+//                                // 记录下次不再提示的版本的版本号
+//                                // 该版本是否点了不再提醒
+//                                SPUtils.setString(Constants.IS_SHOW_VERSION_UPDATE_DIALOG, finalSpecifyVersion.versionCode);
+//                                // 当下次的大小版本大于这个版本的时候依旧会提示
+//                                dialog.dismiss();
+//                            }
+//                        }, specifyVersion.remark, false,"立即更新");
+//                        dialog.show();
+//                    }
+//                }
+//
+//            }
+//        }
+
+
+
+//        // 正式包开启更新检查
+//        String flag = AppConfig.APP_VERSION.contains("正式包")? "1" : "0";
+//        String prefix = AppConfig.APP_VERSION.contains("正式包")? "正式包-" : "测试包-";
+//        // 获取版本列表
+//        List<VersionBean> versionBeanList = new ArrayList<>();
+//        ApiHelper.versionInfoList(this, 1, (code, msg, data) -> {
+//            // 保存版本信息
+//            if(data instanceof List) {
+//                List<?> content = (ArrayList<?>) data;
+//                for (Object o : content) {
+//                    VersionBean item = (VersionBean) o;
+//                    if(!AppConfig.APP_VERSION.contains(item.version) && item.type.equals(flag)) {
+//                        versionBeanList.add(item);
+//                    }
+//                }
+//            }
+//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
+//                versionBeanList.sort(new Comparator<VersionBean>() {
+//                    @Override
+//                    public int compare(VersionBean v1, VersionBean v2) {
+//                        return v2.version.compareTo(v1.version);
+//                    }
+//                });
+//            }
+//            // 获取最新的版本
+//            if(versionBeanList.size() > 0) {
+//                VersionBean latestVersion = versionBeanList.get(0);
+//                // 将最新的版本和当前的版本进行比较
+//                String latestVersionName = latestVersion.version.replace(prefix, "");
+//                if(AppConfig.APP_VERSION_CODE.compareTo(latestVersionName) < 0) {
+//                    // 如果线上版本大于当前版本,则提示更新
+//                    SimpleDialog dialog = new SimpleDialog(this, new SimpleDialog.OnBtnClickListener() {
+//                        @Override
+//                        public void OnCommitClickListener(SimpleDialog dialog, View clickView) {
+//                            loadingLabel = "正在下载中";
+//                            loadingDetailLabel = "请稍候";
+//                            showLoading();
+//                            downloadService.downloadApk(NewMainActivity.this, latestVersion.load);
+//                            dialog.dismiss();
+//                        }
+//
+//                        @Override
+//                        public void OnCloseListener(SimpleDialog dialog, View clickView) {
+//
+//                        }
+//                    }, latestVersion.remark, false,"立即更新");
+//                    dialog.show();
+//                }
+//            }
+//        });
+    }
+    private List<VersionBean> parseVersionInfo(List<VersionBean> beanArrayList) {
+        for (VersionBean versionBean : beanArrayList) {
+            try {
+                String[] versionInfo = versionBean.version.split("-");
+                // 提取版本名称
+                String versionName = versionInfo[0];
+                versionBean.versionName = versionName;
+                // 提取版本号
+                String versionCode = versionInfo[1];
+                versionBean.versionCode = versionCode;
+                // 提取大小版本
+                String[] versionCodeSplit = versionCode.split("[.]");
+                versionBean.bigVersion = versionCodeSplit[0];
+                versionBean.middleVersion = versionCodeSplit[1];
+                versionBean.smallVersion = versionCodeSplit[2];
+            }catch (Exception e){
+                versionBean.clearExtraFields();
+            }
+        }
+        return beanArrayList;
+    }
+    // endregion -----------------------------大小版本更新结束----------------------
+
+
+
+    //region ------------------------------连接及断开除灯之外的其他串口的相关方法开始------------------
     private List<SerialPortManager> mPortList = new ArrayList<>();
     private void toConnectPort(String name){
         Log.i("===","------->toConnectPort name="+name);
@@ -2248,7 +2582,7 @@ public class MainActivity extends BaseActivity {
             }
         }
     }
-    // ------------------------------连接及断开除灯之外的其他串口的相关方法结束------------------
+    //endregion ------------------------------连接及断开除灯之外的其他串口的相关方法结束------------------
     @Override
     protected void onDestroy() {
         super.onDestroy();
@@ -2261,6 +2595,12 @@ public class MainActivity extends BaseActivity {
     }
 
     @Override
+    protected void onResume() {
+        super.onResume();
+        toCheckVersionUpdate();
+    }
+
+    @Override
     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
         super.onActivityResult(requestCode, resultCode, data);
         if (requestCode == REQUEST_CODE_OPEN_GPS) {
@@ -2270,7 +2610,6 @@ public class MainActivity extends BaseActivity {
 //            }
         }
     }
-
     @Override
     public void onBackPressed() {
         if(cameraIsOpening) {
@@ -2281,70 +2620,6 @@ public class MainActivity extends BaseActivity {
         super.onBackPressed();
     }
 
-
-    private static final int REQUEST_CODE_OPEN_GPS = 1;
-    private static final int REQUEST_CODE_PERMISSION_LOCATION = 2;
-    private void checkPermissions(String name) {
-        bleName = name;
-        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
-        if (!bluetoothAdapter.isEnabled()) {
-            Toast.makeText(this, getString(R.string.please_open_blue), Toast.LENGTH_LONG).show();
-            return;
-        }
-
-        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
-        List<String> permissionDeniedList = new ArrayList<>();
-        for (String permission : permissions) {
-            int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
-            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
-                onPermissionGranted(permission);
-            } else {
-                permissionDeniedList.add(permission);
-            }
-        }
-        if (!permissionDeniedList.isEmpty()) {
-            Log.e("------->","----->checkPermissions permissionDeniedList="+permissionDeniedList);
-            String[] deniedPermissions = permissionDeniedList.toArray(new String[permissionDeniedList.size()]);
-            ActivityCompat.requestPermissions(this, deniedPermissions, REQUEST_CODE_PERMISSION_LOCATION);
-        }
-    }
-
-    private void onPermissionGranted(String permission) {
-        Log.e("------->","----->onPermissionGranted permission="+permission);
-        switch (permission) {
-            case Manifest.permission.ACCESS_FINE_LOCATION:
-                setScanRule();
-                startScan(bleName);
-//                Log.e("------->","----->checkGPSIsOpen="+checkGPSIsOpen());
-//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !checkGPSIsOpen()) {
-//                    new AlertDialog.Builder(this)
-//                            .setTitle(R.string.notifyTitle)
-//                            .setMessage(R.string.gpsNotifyMsg)
-//                            .setNegativeButton(R.string.cancel,
-//                                    new DialogInterface.OnClickListener() {
-//                                        @Override
-//                                        public void onClick(DialogInterface dialog, int which) {
-//                                            finish();
-//                                        }
-//                                    })
-//                            .setPositiveButton(R.string.setting,
-//                                    new DialogInterface.OnClickListener() {
-//                                        @Override
-//                                        public void onClick(DialogInterface dialog, int which) {
-//                                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
-//                                            startActivityForResult(intent, REQUEST_CODE_OPEN_GPS);
-//                                        }
-//                                    })
-//
-//                            .setCancelable(false)
-//                            .show();
-//                } else {
-//                    setScanRule();
-//                    startScan(bleName);
-//                }
-                break;
-        }
-    }
     private void uploadLogMessage(String message, String type) {
         String da = "扫标机" + "------>>" + UserCache.getDeviceId() + "------>>" + message;
         String s = BaseApplication.appendDataToLogFile(da, Constants.BLE_LOG_FILE_NAME);

+ 16 - 2
app/src/main/java/com/naz/sdkdemo/base/BaseActivity.java

@@ -5,6 +5,7 @@ import android.content.pm.ActivityInfo;
 import android.content.res.Configuration;
 import android.content.res.Resources;
 import android.os.Bundle;
+import android.text.TextUtils;
 import android.view.View;
 
 import com.kaopiz.kprogresshud.KProgressHUD;
@@ -26,6 +27,8 @@ import butterknife.ButterKnife;
 public abstract class BaseActivity extends AppCompatActivity implements View.OnClickListener {
     protected TitleBar titleBar;
     private KProgressHUD hud;
+    public String loadingLabel = "";
+    public String loadingDetailLabel = "";
    /* public static RFIDWithUHFUART mReader;*/
     @Override
     protected void onCreate(@Nullable Bundle savedInstanceState) {
@@ -83,8 +86,19 @@ public abstract class BaseActivity extends AppCompatActivity implements View.OnC
     }
 
     public void showLoading() {
-        if (hud == null) {
-            hud = KProgressHUD.create(this).setStyle(KProgressHUD.Style.SPIN_INDETERMINATE);
+        if(hud == null) {
+            hud = KProgressHUD.create(this)
+                    .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
+                    .setAnimationSpeed(1)
+                    .setDimAmount(0.5f);
+        }
+        if(!TextUtils.isEmpty(loadingLabel)) {
+            hud.setLabel(loadingLabel);
+            loadingLabel = "";
+        }
+        if(!TextUtils.isEmpty(loadingDetailLabel)) {
+            hud.setDetailsLabel(loadingDetailLabel);
+            loadingDetailLabel = "";
         }
         hud.show();
     }

+ 28 - 0
app/src/main/java/com/naz/sdkdemo/bean/VersionBean.java

@@ -0,0 +1,28 @@
+package com.naz.sdkdemo.bean;
+
+import android.text.TextUtils;
+
+public class VersionBean {
+    public String version;
+    public String load;
+    public String remark;
+    public String type;
+    // 以下的字段为扩展字段
+    public String versionName = "";
+    public String bigVersion = "";
+    public String middleVersion = "";
+    public String smallVersion = "";
+    public String versionCode = "";
+
+    public void clearExtraFields() {
+        versionName = "";
+        bigVersion = "";
+        middleVersion = "";
+        smallVersion = "";
+        versionCode = "";
+    }
+
+    public boolean checkExtraFields() {
+        return !TextUtils.isEmpty(versionName) && !TextUtils.isEmpty(bigVersion) && !TextUtils.isEmpty(middleVersion) && !TextUtils.isEmpty(smallVersion) && !TextUtils.isEmpty(versionCode);
+    }
+}

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

@@ -58,6 +58,7 @@ public class Constants {
     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 final String IS_SHOW_VERSION_UPDATE_DIALOG = "IS_SHOW_VERSION_UPDATE_DIALOG";
 
     public static String mark_speed = "01f4";//500转十进制,高低位
     public static String mark_num = "0001";//1

+ 108 - 0
app/src/main/java/com/naz/sdkdemo/dialog/VersionUpdateDialog.java

@@ -0,0 +1,108 @@
+package com.naz.sdkdemo.dialog;
+
+import android.app.Activity;
+import android.app.Dialog;
+import android.content.Context;
+import android.os.Bundle;
+import android.view.Display;
+import android.view.Gravity;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.Window;
+import android.view.WindowManager;
+import android.widget.Button;
+import android.widget.TextView;
+
+import com.naz.sdkdemo.R;
+
+
+public class VersionUpdateDialog extends Dialog implements View.OnClickListener {
+
+
+    private final boolean canCancel;
+    private String btnText;
+    private String str;
+    private OnBtnClickListener onBtnClickListener;
+    private Context context;
+    private Button btn_update;
+    private Button btn_close;
+    private Button btn_no_longer;
+    private TextView tv_content;
+
+
+
+    public VersionUpdateDialog(Context context, OnBtnClickListener onBtnClickListener, String str, boolean canCancel, String btnText) {
+        super(context, R.style.bottom_select_dialog);
+        this.context = context;
+        this.onBtnClickListener = onBtnClickListener;
+        this.str = str;
+        this.canCancel = canCancel;
+        this.btnText = btnText;
+    }
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        Window window = getWindow();
+        window.setGravity(Gravity.CENTER);
+        LayoutInflater inflater = (LayoutInflater) getContext()
+                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+        View view = inflater.inflate(R.layout.dialog_version_update, null);
+        // 文本提示
+        tv_content = view.findViewById(R.id.tv_content);
+        tv_content.setText(str);
+        // 不再提示按钮
+        btn_no_longer = view.findViewById(R.id.btn_no_longer);
+        btn_no_longer.setOnClickListener(this);
+        btn_close = view.findViewById(R.id.btn_close);
+        btn_close.setOnClickListener(this);
+        // 立即更新按钮
+        btn_update = view.findViewById(R.id.btn_update);
+        btn_update.setText(btnText);
+        btn_update.setOnClickListener(this);
+        // 弹框大小
+        setContentView(view);
+        FullScreen((Activity) context, this, 0.85);
+        setCanceledOnTouchOutside(canCancel);
+    }
+
+
+    /**
+     * 自定义dialog全屏展示
+     *
+     * @param activity
+     * @param dialog
+     */
+    public static void FullScreen(Activity activity, Dialog dialog, double scale) {
+        WindowManager m = activity.getWindowManager();
+        Display d = m.getDefaultDisplay();  //为获取屏幕宽、高
+        WindowManager.LayoutParams p = dialog.getWindow().getAttributes();  //获取对话框当前的参数值
+        p.height = (int) (d.getHeight() * 0.55);   //高度设置为屏幕的0.3
+        p.width = (int) (d.getWidth() * scale);    //宽度设置为全屏
+        dialog.getWindow().setAttributes(p);     //设置生效
+    }
+
+
+    @Override
+    public void onClick(View view) {
+        switch (view.getId()) {
+            case R.id.btn_update:    // 立即更新
+                onBtnClickListener.OnCommitClickListener(this, view);
+                break;
+            case R.id.btn_close:     // 关闭
+                onBtnClickListener.OnCloseListener(this, view);
+                break;
+            case R.id.btn_no_longer: // 不再提醒
+                onBtnClickListener.OnNoLongerListener(this, view);
+                break;
+
+        }
+    }
+
+    public interface OnBtnClickListener {
+        void OnCommitClickListener(VersionUpdateDialog dialog, View clickView);
+        void OnCloseListener(VersionUpdateDialog dialog, View clickView);
+        void OnNoLongerListener(VersionUpdateDialog dialog, View clickView);
+    }
+}
+

+ 8 - 0
app/src/main/java/com/naz/sdkdemo/http/Api.java

@@ -250,4 +250,12 @@ public class Api {
     public static String UPLOAD_EXCEPTION_LOG(){
         return "https://clouddevice.qingyaokeji.com/api/andriodLog";
     }
+
+    public static String VERSION_INFO_LIST() {
+        return "https://clouddevice.qingyaokeji.com/api/andriodDownload";
+    }
+
+    public static String STABLE_VERSION_INFO() {
+        return "https://clouddevice.qingyaokeji.com/api/androidVersion";
+    }
 }

+ 42 - 0
app/src/main/java/com/naz/sdkdemo/http/ApiHelper.java

@@ -20,6 +20,7 @@ import com.naz.sdkdemo.bean.ScanRecycleInfo;
 import com.naz.sdkdemo.bean.StatusInfo;
 import com.naz.sdkdemo.bean.StockInfo;
 import com.naz.sdkdemo.bean.TrademarkInfo;
+import com.naz.sdkdemo.bean.VersionBean;
 import com.naz.sdkdemo.okgo.callback.DialogCallback;
 import com.naz.sdkdemo.okgo.module.BaseResponse;
 import com.naz.sdkdemo.okgo.module.BaseResponse2;
@@ -162,6 +163,47 @@ public class ApiHelper {
     }
 
 
+    public static void versionInfoList(Activity activity, int type, String packageName, Callback callback) {
+        JSONObject raw = new JSONObject();
+        try {
+            raw.put("type", String.valueOf(type));
+            raw.put("package", packageName);
+        } catch (JSONException e) {
+
+        }
+        OkGo.<BaseResponse2<List<VersionBean>>>post(Api.VERSION_INFO_LIST())
+                .upJson(raw)
+                .tag(activity)
+                .execute(new DialogCallback<BaseResponse2<List<VersionBean>>>(activity, false) {
+                    @Override
+                    public void onSuccess(Response<BaseResponse2<List<VersionBean>>> response) {
+                        if ("200".equals(response.body().status)){
+                            callback.onSuccess(Callback.SUCCESS, null, response.body().data);
+                        }
+                    }
+                });
+    }
+
+    public static void stableVersionInfo(Activity activity, String type, Callback callback) {
+        JSONObject raw = new JSONObject();
+        try {
+            raw.put("type", type);
+        } catch (JSONException e) {
+
+        }
+        OkGo.<BaseResponse2<VersionBean>>post(Api.STABLE_VERSION_INFO())
+                .upJson(raw)
+                .tag(activity)
+                .execute(new DialogCallback<BaseResponse2<VersionBean>>(activity, false) {
+                    @Override
+                    public void onSuccess(Response<BaseResponse2<VersionBean>> response) {
+                        if ("200".equals(response.body().status)){
+                            callback.onSuccess(Callback.SUCCESS, null, response.body().data);
+                        }
+                    }
+                });
+    }
+
     public static void operateRecord(Activity activity, int type, CallbackNew<OperateResult> callback) {
         JSONObject body = new JSONObject();
         try {

+ 133 - 0
app/src/main/java/com/naz/sdkdemo/utils/DownloadService.java

@@ -0,0 +1,133 @@
+package com.naz.sdkdemo.utils;
+
+import android.app.DownloadManager;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.pm.PackageManager;
+import android.net.Uri;
+import android.os.Build;
+import android.os.Environment;
+import android.text.TextUtils;
+import android.util.Log;
+
+import com.naz.sdkdemo.base.BaseActivity;
+import com.naz.sdkdemo.weight.XToast;
+
+import java.io.File;
+import java.io.IOException;
+
+public class DownloadService {  
+  
+    private DownloadManager downloadManager;  
+    private long downloadID;
+    private BaseActivity mActivity;
+    private String TAG = "DownloadService";
+    private String apkName;
+
+    public void downloadApk(Context context, String url) {
+        // 初始化参数
+        mActivity = (BaseActivity) context;
+        String[] split = url.split("/");
+        apkName = split[split.length - 1];
+        downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);  
+        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
+
+        // 设置APK存储位置(注意:Android 10及以上应使用MediaStore或分区存储)
+        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, apkName);
+
+        // apk如果已存在则先删除
+        File apkfile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath(), apkName);
+        if (apkfile.exists()) {
+            apkfile.delete();
+        }
+
+        // 可选:设置通知可见性、网络类型等  
+        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);  
+  
+        // 将下载请求加入队列  
+        downloadID = downloadManager.enqueue(request);  
+  
+        // 注册广播接收器监听下载状态(可选)  
+        context.registerReceiver(downloadReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));  
+    }  
+  
+    private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {  
+        @Override  
+        public void onReceive(Context context, Intent intent) {  
+            long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);  
+            if (id == downloadID) {
+                mActivity.hideLoading();
+                // 下载完成,可以处理APK文件了  
+                // 检查大王椰更新器是否存在
+                boolean isInstalled = isAppInstalled(mActivity, "com.dawangye.booter");
+                if (isInstalled) {
+                    // 应用已安装
+                    Log.d(TAG, "应用已安装");
+                    if(!TextUtils.isEmpty(apkName)) {
+                        installApkSilently();
+                    }
+                } else {
+                    // 应用未安装
+                    Log.d(TAG, "应用未安装");
+                    Uri uri = downloadManager.getUriForDownloadedFile(downloadID);
+                    // 使用uri进行后续操作,如安装APK
+                    installApk(context, uri);
+                }
+                apkName = "";
+                // 别忘了注销广播接收器  
+                context.unregisterReceiver(this);  
+            }  
+        }  
+    };  
+  
+    // 后续你需要实现installApk方法来安装APK
+    public void installApk(Context context, Uri apkUri) {
+        try {
+            // 对于Android N(7.0)及以上版本,使用FileProvider
+            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
+                // 这里需要替换为你的FileProvider的authority
+                Intent intent = new Intent(Intent.ACTION_VIEW);
+                intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
+                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
+                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+                context.startActivity(intent);
+            }
+        }catch (Exception e) {
+            Log.i(TAG, "installApk: " + e.getMessage());
+            XToast.showToast("安装包下载失败, 请重试");
+        }
+    }
+
+    private void installApkSilently() {
+        try {
+            // 启动启动器
+            Intent launchIntent = mActivity.getPackageManager().getLaunchIntentForPackage("com.dawangye.booter");
+            mActivity.startActivity(launchIntent);
+            // 执行重装命令
+            String cmd = "pm install -r " + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + File.separator + apkName;
+            ProcessBuilder pb = new ProcessBuilder("su", "-c", cmd);
+            // 启动进程
+            Process process = pb.start();
+            // 等待命令执行完成
+            int exitCode = process.waitFor();
+            if (exitCode == 0) {
+                Log.i(TAG, "重装成功");
+            } else {
+                Log.i(TAG, "重装失败");
+            }
+        } catch (IOException | InterruptedException e) {
+            e.printStackTrace();
+        }
+    }
+
+    private boolean isAppInstalled(Context context, String packageName) {
+        try {
+            context.getPackageManager().getApplicationInfo(packageName, PackageManager.GET_META_DATA);
+            return true;
+        } catch (PackageManager.NameNotFoundException e) {
+            return false;
+        }
+    }
+}

+ 8 - 0
app/src/main/res/drawable/bg_grey_round_20_top_left_top_right.xml

@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<shape xmlns:android="http://schemas.android.com/apk/res/android">
+  <solid android:color="#f7f7f7" />
+  <corners
+      android:topLeftRadius="33px"
+      android:topRightRadius="33px"
+  />
+</shape>

+ 6 - 0
app/src/main/res/drawable/bg_white_round_20.xml

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<shape xmlns:android="http://schemas.android.com/apk/res/android">
+  <solid android:color="#ffffff" />
+  <corners
+      android:radius="33px" />
+</shape>

+ 92 - 0
app/src/main/res/layout/dialog_version_update.xml

@@ -0,0 +1,92 @@
+<?xml version="1.0" encoding="utf-8"?>
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:orientation="vertical">
+
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:background="@drawable/bg_white_round_20"
+        android:layout_height="match_parent"
+        android:orientation="vertical">
+        <RelativeLayout
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:layout_marginBottom="10dp"
+            android:background="@drawable/bg_grey_round_20_top_left_top_right">
+            <ImageView
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:src="@mipmap/top_logo"
+                android:layout_centerHorizontal="true"/>
+        </RelativeLayout>
+<!--        密码输入框-->
+        <LinearLayout
+            android:layout_gravity="center"
+            android:layout_marginHorizontal="15dp"
+            android:layout_width="match_parent"
+            android:orientation="vertical"
+            android:layout_height="0dp"
+            android:layout_weight="1"
+        >
+            <ScrollView
+                android:layout_width="match_parent"
+                android:layout_height="match_parent">
+                <TextView
+                    android:id="@+id/tv_content"
+                    style="@style/wrap_style"
+                    android:layout_gravity="left"
+                    android:layout_marginBottom="9dp"
+                    android:text=""
+                    android:textColor="@color/grey_66"
+                    android:textSize="22sp" />
+            </ScrollView>
+        </LinearLayout>
+        <LinearLayout
+            android:layout_marginVertical="28dp"
+            android:layout_marginHorizontal="15dp"
+            android:layout_width="match_parent"
+            android:orientation="vertical"
+            android:layout_height="wrap_content">
+            <Button
+                android:layout_weight="1"
+                android:id="@+id/btn_update"
+                android:layout_width="match_parent"
+                android:layout_height="54dp"
+                android:background="@drawable/shape_e6212a_4dp"
+                android:gravity="center"
+                android:text="立即更新"
+                android:textColor="@color/white"
+                android:layout_marginBottom="10dp"
+                android:textSize="18sp" />
+<!--                <View-->
+<!--                    android:layout_height="match_parent"-->
+<!--                    android:layout_width="10dp"-->
+<!--                    />-->
+            <Button
+                android:layout_weight="1"
+                android:id="@+id/btn_no_longer"
+                android:layout_width="match_parent"
+                android:layout_height="54dp"
+                android:background="@drawable/shape_e6212a_4dp"
+                android:gravity="center"
+                android:text="不再提醒"
+                android:textColor="@color/white"
+                android:layout_marginBottom="10dp"
+                android:textSize="18sp" />
+
+            <Button
+                android:layout_weight="1"
+                android:id="@+id/btn_close"
+                android:layout_width="match_parent"
+                android:layout_height="54dp"
+                android:background="@drawable/shape_e6212a_4dp"
+                android:gravity="center"
+                android:text="关闭"
+                android:visibility="visible"
+                android:textColor="@color/white"
+                android:textSize="18sp" />
+        </LinearLayout>
+    </LinearLayout>
+
+</RelativeLayout>

+ 7 - 1
app/src/main/res/values/styles.xml

@@ -1,5 +1,11 @@
 <resources>
-
+    <!--dialog-->
+    <style name="bottom_select_dialog" parent="@android:style/Theme.Dialog">
+        <item name="android:windowIsFloating">true</item><!-- 是否漂现在activity上 -->
+        <item name="android:windowNoTitle">true</item>
+        <item name="android:backgroundDimEnabled">true</item>
+        <item name="android:windowBackground">@android:color/transparent</item>
+    </style>
     <!-- Base application theme. -->
     <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
         <!-- Customize your theme here. -->