ソースを参照

ltb
更换新设备超声波
其他优化

老狐\25396 4 年 前
コミット
497d958f2f

+ 1 - 0
.gitignore

xqd
@@ -12,3 +12,4 @@
 /captures
 .externalNativeBuild
 .idea/
+app/release/app-release.apk

+ 2 - 1
app/build.gradle

xqd xqd
@@ -14,7 +14,7 @@ android {
             storePassword '159753'
             storeFile file('\\box.keystore')
         }
-        debug{
+        debug {
             keyAlias 'box.keystore'
             keyPassword '159753'
             storePassword '159753'
@@ -63,6 +63,7 @@ android {
         sourceCompatibility = 1.8
         targetCompatibility = 1.8
     }
+    sourceSets { main { jni.srcDirs = ['src/main/jni', 'src/main/jni/2'] } }
 }
 
 dependencies {

+ 1 - 0
app/release/output.json

xqd
@@ -0,0 +1 @@
+[{"outputType":{"type":"APK"},"apkInfo":{"type":"MAIN","splits":[],"versionCode":4,"versionName":"4.0","enabled":true,"outputFile":"app-release.apk","fullName":"release","baseName":"release"},"path":"app-release.apk","properties":{}}]

+ 11 - 1
app/src/main/AndroidManifest.xml

xqd xqd xqd
@@ -38,16 +38,24 @@
     <uses-permission android:name="android.permission.WAKE_LOCK" />
 
 
+    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"> </uses-permission>
+
+    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"> </uses-permission>
+
+    <uses-permission android:name="android.permission.WAKE_LOCK"> </uses-permission>
+
     <uses-permission android:name="android.permission.INTERNET" />
     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
     <uses-permission android:name="android.permission.READ_PHONE_STATE" />
     <uses-permission android:name="android.permission.RECORD_AUDIO" />
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
     <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
+    <!--读权限-->
     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permisssion.READ_LOGS"/>
 <!--    <uses-permission android:name="android.permission.INSTALL_PACKAGES"/>-->
     <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
+    <!--写权限-->
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
     <uses-feature
@@ -62,6 +70,8 @@
     <!--Android 6.0及后续版本扫描蓝牙,需要定位权限(进入GPS设置,可以看到蓝牙定位)-->
     <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
     <uses-permission android:name="com.android.example.USB_PERMISSION" />
+    <!--添加白名单-->
+    <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
 
     <uses-feature
         android:name="android.hardware.usb.host"
@@ -118,7 +128,7 @@
 
         <service android:name=".service.MyService"
             android:permission="android.permission.BIND_JOB_SERVICE"
-            />
+        />
 
         <receiver android:name=".receiver.BootReceiver"  android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
             <intent-filter>

+ 19 - 19
app/src/main/java/com/siwei/recyclebox/application/AppApplication.java

xqd xqd xqd xqd xqd xqd xqd xqd
@@ -53,6 +53,8 @@ import com.siwei.recyclebox.ui.main.MainViewModel;
 
 import java.util.HashMap;
 import java.util.Map;
+import java.util.Timer;
+import java.util.TimerTask;
 import java.util.logging.LogRecord;
 
 import me.goldze.mvvmhabit.base.BaseApplication;
@@ -62,6 +64,7 @@ import me.goldze.mvvmhabit.utils.KLog;
 import me.goldze.mvvmhabit.utils.SPUtils;
 import me.goldze.mvvmhabit.utils.StringUtils;
 import com.siwei.recyclebox.ui.main.MainViewModel;
+import com.squareup.leakcanary.LeakCanary;
 import com.tencent.bugly.crashreport.CrashReport;
 
 
@@ -75,24 +78,20 @@ public class AppApplication extends BaseApplication implements CustomActivityOnC
     @Override
     public void onCreate() {
         super.onCreate();
-        SerialPortUtil.getInstance().init(this);        //初+始化串口
-
+        SerialPortUtil.getInstance().init(this);        //初始化串口
         SPUtils.getInstance().put("RunningState",0);
         SPUtils.getInstance().put("TaskSwitch",1);
         CrashReport.initCrashReport(getApplicationContext(), "40c3954b93", true);//测试阶段为true  发布时改成false
         CrashReport.setUserId(this,MainViewModel.getDeviceId(this));
-        Log.i(TAG,"AppApplication------------------------");
         //是否开启打印日志
         KLog.init(BuildConfig.DEBUG);
         //初始化全局异常崩溃
         initCrash();
         //内存泄漏检测
-//        if (!LeakCanary.isInAnalyzerProcess(this)) {
-//            LeakCanary.install(this);
-//        }
-//        initAliIoT();
+        if (!LeakCanary.isInAnalyzerProcess(this)) {
+            LeakCanary.install(this);
+        }
         initIoTDynamic();
-
     }
 
     private Handler mHandler=new Handler(msg ->{
@@ -116,7 +115,8 @@ public class AppApplication extends BaseApplication implements CustomActivityOnC
          */
         Map<String, ValueWrapper> propertyValues = new HashMap<>();
         //心跳包 interval 单位秒
-        MqttConfigure.setKeepAliveInterval(60);
+        MqttConfigure.setKeepAliveInterval(300);
+
         // 示例
         // propertyValues.put("LightSwitch", new ValueWrapper.BooleanValueWrapper(0));
         IoTMqttClientConfig clientConfig = new IoTMqttClientConfig(deviceInfo.productKey, deviceInfo.deviceName, deviceInfo.deviceSecret);
@@ -146,14 +146,13 @@ public class AppApplication extends BaseApplication implements CustomActivityOnC
                     public void run() {
                         initIoTDynamic();
                     }
-                },300000);
+                },60000);
             }
             @Override
             public void onInitDone(Object data) {
                 // 初始化成功 data 作为预留参数
                 KLog.d("初始化成功,data:"+data);
-                MqttPublishRequest request = new MqttPublishRequest();
-
+                MqttConfigure.setKeepAliveInterval(60);
 
             }
         });
@@ -171,11 +170,11 @@ public class AppApplication extends BaseApplication implements CustomActivityOnC
          *   调用动态注册接口去获取deviceSecret
          */
         DeviceInfo myDeviceInfo = new DeviceInfo();
-        myDeviceInfo.productKey = "a1EtqHmfpNk";//正式服
-//        myDeviceInfo.productKey = "a13H8L6bDyf";//测试服
-//
-        myDeviceInfo.productSecret = "x6wHbrbXUMFYtvLl";//正式服
-//        myDeviceInfo.productSecret = "Nc4Y4KsjofejCy27";//测试服
+//        myDeviceInfo.productKey = "a1EtqHmfpNk";//正式服
+        myDeviceInfo.productKey = "a13H8L6bDyf";//测试服
+
+//        myDeviceInfo.productSecret = "x6wHbrbXUMFYtvLl";//正式服
+        myDeviceInfo.productSecret = "Nc4Y4KsjofejCy27";//测试服
 
         System.out.println(MainViewModel.getDeviceId(this)+"----------------------------+");
         myDeviceInfo.deviceName = MainViewModel.getDeviceId(this);
@@ -183,7 +182,8 @@ public class AppApplication extends BaseApplication implements CustomActivityOnC
         SPUtils.getInstance().put("IMEI",MainViewModel.getDeviceId(this));
 //        myDeviceInfo.deviceName="123456";
 
-//        String secret = SPUtils.getInstance().getString("deviceSecret3");//读
+        SPUtils.getInstance().put("deviceSecret2","e5e50e77141d3e54f8bebfc6d56469cb");//存
+//        SPUtils.getInstance().put("deviceSecret2","WMClVkIJipSunIY4fOSd2Be3xo42TfVs");//测试服
         String secret = SPUtils.getInstance().getString("deviceSecret2");//读
 //        String secret ="WMClVkIJipSunIY4fOSd2Be3xo42TfVs";
         Log.i(TAG,"secret=="+secret);
@@ -203,7 +203,7 @@ public class AppApplication extends BaseApplication implements CustomActivityOnC
         LinkKit.getInstance().deviceRegister(this, params, hubApiRequest, new IConnectSendListener() {
             @Override
             public void onResponse(ARequest aRequest, AResponse aResponse) {
-                // aRequest 用户的请求数据
+                // aRequest 用户的请求数据+
                 System.out.println("arequest:"+aRequest.toString()+"  aResponse:"+aResponse);
                 if (aResponse != null && aResponse.data != null) {
                     ResponseModel<Map<String, String>> response = JSONObject.parseObject(aResponse.data.toString(),

+ 1 - 0
app/src/main/java/com/siwei/recyclebox/deviceUtils/BaseDeviceEntity.java

xqd
@@ -69,6 +69,7 @@ public abstract class BaseDeviceEntity {
         UsbDeviceConnection connection = usbManager.openDevice(port.getDriver().getDevice());
         port.open(connection);
         port.setParameters(getBaudRate(), getDataBits(), getStopBits(), getParity());//连接参数
+
         /*SerialInputOutputManager inputOutputManager = new SerialInputOutputManager(port, new SerialInputOutputManager.Listener() {
             @Override
             public void onNewData(byte[] data) {

+ 142 - 80
app/src/main/java/com/siwei/recyclebox/deviceUtils/OtherDevice.java

xqd xqd xqd xqd xqd xqd xqd xqd xqd xqd xqd xqd
@@ -38,6 +38,7 @@ public class OtherDevice extends BaseDeviceEntity {
      */
     @Override
     int getBaudRate() {
+//        return 9600;
         return 115200;
     }
 
@@ -74,7 +75,7 @@ public class OtherDevice extends BaseDeviceEntity {
                 case 0x0A://电控锁
 
                     break;
-                case 0x0C://距离/温度
+                case 0x01://距离/温度
             }
         }
     }
@@ -133,7 +134,6 @@ public class OtherDevice extends BaseDeviceEntity {
             e.printStackTrace();
             SPUtils.getInstance().put("RunningState",1);
             MainViewModel.SendSmsResponse("其他设备未检测到");
-
             Log.e(TAG,"读取门磁错误",e);
             return 3;
         }
@@ -205,10 +205,28 @@ public class OtherDevice extends BaseDeviceEntity {
             return 0;
         }
     }
-
+    /*
+    * 设置电流阈值
+    * */
     public void setPower(){
         try {
+//            byte[] setPower = new byte[]{(byte) 0xAA, (byte) 0xBB, 0x0A, 0x01, 0x66, 0x0A, 0x02, 0x60, (byte) 0xFF, (byte) 0xFF, (byte) 0xCC, (byte) 0xDD};
+            byte[] setPower = new byte[]{(byte) 0xAA, (byte) 0xBB, 0x0A, 0x01, 0x66, 0x0A, 0x02, 0x44, (byte) 0xFF, (byte) 0xFF, (byte) 0xCC, (byte) 0xDD};
+
+            port.write(setPower, 500);
+            byte[] response = new byte[12];
+            port.read(response,500);
+            Log.i(TAG,ByteUtil.bytesToString(response)+"设置电流");
+        }catch(Exception e){
+            e.printStackTrace();
+        }
+    }
+
+    public void setPowerBigger(){
+        try {
+//            byte[] setPower = new byte[]{(byte) 0xAA, (byte) 0xBB, 0x0A, 0x01, 0x66, 0x0A, 0x02, 0x60, (byte) 0xFF, (byte) 0xFF, (byte) 0xCC, (byte) 0xDD};
             byte[] setPower = new byte[]{(byte) 0xAA, (byte) 0xBB, 0x0A, 0x01, 0x66, 0x0A, 0x03, 0x60, (byte) 0xFF, (byte) 0xFF, (byte) 0xCC, (byte) 0xDD};
+
             port.write(setPower, 500);
             byte[] response = new byte[12];
             port.read(response,500);
@@ -216,8 +234,21 @@ public class OtherDevice extends BaseDeviceEntity {
         }catch(Exception e){
             e.printStackTrace();
         }
+    }
+    public void queryPower(){
 
+        try{
+            byte[] readPushOrderBytes=new byte[]{(byte)0xAA, (byte) 0xBB,0x0A, 0x01, 0x55 ,0x01 , (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xCC, (byte) 0xDD};
+            port.write(readPushOrderBytes, 100);
+            byte[] responseRead = new byte[ 12];
+            port.read(responseRead,200);
+            System.out.println("Read response:"+ByteUtil.bytesToString(responseRead));
+        }catch (Exception e){
+            e.printStackTrace();
+        }
     }
+
+
     /**
      * 伸杆关门
      */
@@ -228,7 +259,7 @@ public class OtherDevice extends BaseDeviceEntity {
                 try {
                     SPUtils.getInstance().put("RodSwitch","0");
                     //门  66后面 01 表示杆 01表示伸杆  1c表示多少秒  02 1c 表示电流
-                    System.out.println("------------push rod------------------------");
+//                    System.out.println("------------push rod------------------------");
                     SPUtils.getInstance().put("queryInfraredError",0);
 //                    byte[] setPower = new byte[]{(byte) 0xAA, (byte) 0xBB, 0x0A, 0x01, 0x66, 0x0A, 0x02, 0x1C, (byte) 0xFF, (byte) 0xFF, (byte) 0xCC, (byte) 0xDD};
 //                    port.write(setPower, 100);
@@ -240,14 +271,24 @@ public class OtherDevice extends BaseDeviceEntity {
                     getRodOpenNumber();
                     byte[] response = new byte[ 12];
                     port.read(response,200);
-                    byte[] readPushOrderBytes=new byte[]{(byte)0xAA, (byte) 0xBB,0x0A, 0x01, 0x55 ,0x01 , (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xCC, (byte) 0xDD};
-                    port.write(readPushOrderBytes, 100);
-                    byte[] responseRead = new byte[ 12];
-                    port.read(responseRead,200);
+                    mHandler.postDelayed(new Runnable() {
+                        @Override
+                        public void run() {
+                            byte[] readPushOrderBytes=new byte[]{(byte)0xAA, (byte) 0xBB,0x0A, 0x01, 0x55 ,0x01 , (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xCC, (byte) 0xDD};
+                            try {
+                                port.write(readPushOrderBytes, 100);
+                                byte[] responseRead = new byte[ 12];
+                                port.read(responseRead,200);
+                                System.out.println("pushRead response:"+ByteUtil.bytesToString(responseRead));
+                            } catch (IOException e) {
+                                e.printStackTrace();
+                            }
+                        }
+                    },1000);
+
                     System.out.println("push response:"+ByteUtil.bytesToString(response));
-                    System.out.println("pushRead response:"+ByteUtil.bytesToString(responseRead));
 
-//                    SPUtils.getInstance().getInt("infraredNum1",0);
+                    SPUtils.getInstance().getInt("infraredNum1",0);
                     long curr=System.currentTimeMillis();
                     Thread.sleep(500);
                     while (System.currentTimeMillis() - curr < 6000) {
@@ -259,8 +300,12 @@ public class OtherDevice extends BaseDeviceEntity {
                         }
                         if (infrared == 1) {//有障碍物
                             //停止关门
-                            Log.i(TAG, "停止关门");
+                            Log.i(TAG, "有障碍物,停止关门");
                             port.write(new byte[]{(byte) 0xAA, (byte) 0xBB, 0x0A, 0x01, 0x66, 0x01, 0x03, (byte) 0x05, (byte) 0xff, (byte) 0xff, (byte) 0xCC, (byte) 0xDD}, 200);
+                            byte[] response3 = new byte[ 12];
+                            port.read(response3,200);
+                            Log.i("停止关门",response3+"");
+
                             int num=SPUtils.getInstance().getInt("infraredNum1",0)+1;
                             SPUtils.getInstance().put("infraredNum1",num);
                             if(num<3){
@@ -313,12 +358,22 @@ public class OtherDevice extends BaseDeviceEntity {
                     System.out.println("pullRod "+writeLen);
                     byte[] response = new byte[12];
                     port.read(response,200);
+                    mHandler.postDelayed(new Runnable() {
+                        @Override
+                        public void run() {
+                            byte[] readPullOrderBytes=new byte[]{(byte)0xAA, (byte) 0xBB,0x0A, 0x01, 0x55 ,0x01 , (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xCC, (byte) 0xDD};
+                            try {
+                                port.write(readPullOrderBytes, 100);
+                                byte[] responseRead = new byte[ 12];
+                                port.read(responseRead,200);
+                                System.out.println("pullRead response:"+ByteUtil.bytesToString(responseRead));
+                            } catch (IOException e) {
+                                e.printStackTrace();
+                            }
+
+                        }
+                    },1000);
 
-                    byte[] readPullOrderBytes=new byte[]{(byte)0xAA, (byte) 0xBB,0x0A, 0x01, 0x55 ,0x01 , (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xCC, (byte) 0xDD};
-                    port.write(readPullOrderBytes, 100);
-                    byte[] responseRead = new byte[ 12];
-                    port.read(responseRead,200);
-                    System.out.println("pullRead response:"+ByteUtil.bytesToString(responseRead));
                     System.out.println("response:"+ByteUtil.bytesToString(response));
                 }catch ( Exception e ){
                     e.printStackTrace();
@@ -334,7 +389,7 @@ public class OtherDevice extends BaseDeviceEntity {
     /**
      * 运收门开锁
      */
-    public  Integer openLock(){
+    public  Integer openLock(){//AA BB 0A 01 66 02 01 07 FF FF CC DD
         try {
 //            byte[] openLockOrderBytes = new byte[]{(byte) 0xAA, (byte) 0xBB, 0x0A, 0x01, 0x66, 0x02, 0x01,0x03, (byte) 0xFF, (byte) 0xFF, (byte) 0xCC, (byte) 0xDD};
           byte[] openLockOrderBytes = new byte[]{(byte) 0xAA, (byte) 0xBB, 0x0A, 0x01, 0x66, 0x02, 0x01,0x07, (byte) 0xFF, (byte) 0xFF, (byte) 0xCC, (byte) 0xDD};
@@ -344,7 +399,7 @@ public class OtherDevice extends BaseDeviceEntity {
             getLockOpenNumber();
             Log.i(TAG,ByteUtil.bytesToString(response)+"开收运门");
             if(response[4]==102&&response[5]==2&&response[6]==1){
-                return 0;
+                return 1;
             }else {
                 return 0;
             }
@@ -385,69 +440,76 @@ public class OtherDevice extends BaseDeviceEntity {
      * 距离
      * @return
      */
-    public  Integer getDistance(){
-        try {
-            byte[] bytes = new byte[]{(byte)0xAA ,(byte)0xBB ,(byte)0x0C ,(byte)0x01 ,(byte)0x55 ,(byte)0x01 ,(byte)0xFF ,(byte)0xFF,(byte)0xFF ,(byte)0xFF ,(byte)0xCC ,(byte)0xDD};
-            port.write(bytes,200);
-            byte[] response = new byte[12];
-            int len = port.read(response,200);
-            Log.i(TAG,ByteUtil.bytesToString(response)+len+"距离");
-            byte[] disBytes = new byte[4];
-            disBytes[2] = response[6];
-            disBytes[3] = response[7];
-            Log.i(TAG,ByteUtil.bytesToString(disBytes)+"juli");
-            int disInt = ByteUtil.bytes2Int(disBytes);
-            if(response[4]==85&&response[5]==1){
-                return disInt;
-            }else {
-                SPUtils.getInstance().put("RunningState",5);
-                MainViewModel.SendSmsResponse("温度超声波失灵");
-                return 0;
-            }
-        }catch ( Exception e ){
-            e.printStackTrace();
-            SPUtils.getInstance().put("RunningState",1);
-            MainViewModel.SendSmsResponse("其他设备未检测到");
-            return 0;
-        }
-    }
-    /**
-     * 温度
-     * @return
-     */
-    public Integer geTemperature(){//获取温度
-        try{
-            byte[] bytes = new byte[]{(byte)0xAA ,(byte)0xBB ,(byte)0x0C ,(byte)0x01 ,(byte)0x55 ,(byte)0x02 ,(byte)0xFF ,(byte)0xFF,(byte)0xFF ,(byte)0xFF ,(byte)0xCC ,(byte)0xDD};
-            port.write(bytes,200);
-            byte[] response=new byte[12];
-            int len=port.read(response,200);
-            Log.i(TAG,ByteUtil.bytesToString(response)+len+"温度"+response[4]+response[5]);
-            byte[] temBytes=new byte[4];
-//            temBytes[2]=response[5];
-            temBytes[3]=response[6];
-            Integer temInt=ByteUtil.bytes2Int(temBytes);
-//            double temDouble=0;
-//            if(temInt<65536){
-//                temDouble=temInt/10;
-//                return temDouble;
+//    public  Integer getDistance(){
+//        try {
+////            byte[] bytes = new byte[]{(byte)0xAA ,(byte)0xBB ,(byte)0x0C ,(byte)0x01 ,(byte)0x55 ,(byte)0x01 ,(byte)0xFF ,(byte)0xFF,(byte)0xFF ,(byte)0xFF ,(byte)0xCC ,(byte)0xDD};
+//            //新超声波 01 03 01 02 00 01 24 36
+//            byte[] bytes = new byte[]{(byte)0xAA ,(byte)0xBB ,(byte)0x01 ,(byte)0x03 ,(byte)0x01 ,(byte)0x02 ,(byte)0x00 ,(byte)0x01,(byte)0x24 ,(byte)0x36 ,(byte)0xCC ,(byte)0xDD};
+////            byte[] bytes = new byte[]{(byte)0x01 ,(byte)0x03 ,(byte)0x01 ,(byte)0x02 ,(byte)0x00 ,(byte)0x01 ,(byte)0x24 ,(byte)0x36};
+//            port.write(bytes,100);
+//            byte[] response = new byte[12];
+//            int len = port.read(response,100);
+//            Log.i(TAG,ByteUtil.bytesToString(response)+len+"距离");
+//            for (int i:response) {
+//                Log.i("超声波", ""+response[i]);
 //            }
-//            temDouble=-(temInt-65536)/10;
-//            return temDouble;
-            if(response[4]==85&&response[5]==2){
-                return temInt;
-            }else {
-                SPUtils.getInstance().put("RunningState",5);
-                MainViewModel.SendSmsResponse("温度超声波失灵");
-                return 0;
-            }
-        }catch ( Exception e ){
-            e.printStackTrace();
-            SPUtils.getInstance().put("RunningState",1);
-            MainViewModel.SendSmsResponse("其他设备未检测到");
-            Log.i(TAG,"测温度失败");
-            return 0;
-        }
-    }
+//            Log.i("超声波", ""+response.toString());
+//            byte[] disBytes = new byte[4];
+//            disBytes[2] = response[3];
+//            disBytes[3] = response[4];
+//            Log.i(TAG,ByteUtil.bytesToString(disBytes)+"juli");
+//            int disInt = ByteUtil.bytes2Int(disBytes);
+//            if(response[4]==85&&response[5]==1){
+//                return disInt;
+//            }else {
+//                SPUtils.getInstance().put("RunningState",5);
+//                MainViewModel.SendSmsResponse("温度超声波失灵");
+//                return 0;
+//            }
+//        }catch ( Exception e ){
+//            e.printStackTrace();
+//            SPUtils.getInstance().put("RunningState",1);
+//            MainViewModel.SendSmsResponse("其他设备未检测到");
+//            return 0;
+//        }
+//    }
+//    /**
+//     * 温度
+//     * @return
+//     */
+//    public Integer geTemperature(){//获取温度
+//        try{
+//            byte[] bytes = new byte[]{(byte)0xAA ,(byte)0xBB ,(byte)0x0C ,(byte)0x01 ,(byte)0x55 ,(byte)0x02 ,(byte)0xFF ,(byte)0xFF,(byte)0xFF ,(byte)0xFF ,(byte)0xCC ,(byte)0xDD};
+//            port.write(bytes,200);
+//            byte[] response=new byte[12];
+//            int len=port.read(response,200);
+//            Log.i(TAG,ByteUtil.bytesToString(response)+len+"温度"+response[4]+response[5]);
+//            byte[] temBytes=new byte[4];
+////            temBytes[2]=response[5];
+//            temBytes[3]=response[6];
+//            Integer temInt=ByteUtil.bytes2Int(temBytes);
+////            double temDouble=0;
+////            if(temInt<65536){
+////                temDouble=temInt/10;
+////                return temDouble;
+////            }
+////            temDouble=-(temInt-65536)/10;
+////            return temDouble;
+//            if(response[4]==85&&response[5]==2){
+//                return temInt;
+//            }else {
+//                SPUtils.getInstance().put("RunningState",5);
+//                MainViewModel.SendSmsResponse("温度超声波失灵");
+//                return 0;
+//            }
+//        }catch ( Exception e ){
+//            e.printStackTrace();
+//            SPUtils.getInstance().put("RunningState",1);
+//            MainViewModel.SendSmsResponse("其他设备未检测到");
+//            Log.i(TAG,"测温度失败");
+//            return 0;
+//        }
+//    }
     /*
      * 开灯关灯
      * */

+ 110 - 60
app/src/main/java/com/siwei/recyclebox/deviceUtils/SerialPortUtil.java

xqd xqd xqd xqd xqd xqd xqd xqd
@@ -26,15 +26,19 @@ import me.goldze.mvvmhabit.utils.SPUtils;
  * 串口读写工具。
  */
 public class SerialPortUtil {
-    private Context mContext ;
-    private SerialPortUtil(){
-    }
+    private Context mContext;
+
 
     private static final String TAG = "SerialPortUtil";
     private static final String INTENT_ACTION_GRANT_USB = "com.siwei.recyclebox.GRANT_USB";
+
+    private SerialPortUtil() {
+    }
+
     private static SerialPortUtil instance;
-    public static SerialPortUtil getInstance(){
-        if(instance == null){
+
+    public static SerialPortUtil getInstance() {
+        if (instance == null) {
             instance = new SerialPortUtil();
         }
         return instance;
@@ -44,26 +48,31 @@ public class SerialPortUtil {
     private List<UsbSerialPort> availablePorts = new ArrayList<>();
 
     private List<BaseDeviceEntity> deviceList = new ArrayList<>();
-    public void init(Context context){
+
+    public void init(Context context) {
         mContext = context;
         mUsbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
+        boolean addWeight = true;
+        boolean addOther = true;
+        boolean addUltasonic = true;
 
         final List<UsbSerialDriver> drivers =
                 UsbSerialProber.getDefaultProber().findAllDrivers(mUsbManager);
-        Log.i("drivers=====",drivers.toString());
+        Log.i("drivers=====", drivers.toString());
 
         for (final UsbSerialDriver driver : drivers) {
-            System.out.println("SerialPortUtil:"+driver.toString());
-            System.out.println("device:"+driver.getDevice().toString());
+            System.out.println("SerialPortUtil:" + driver.toString());
+            System.out.println("device:" + driver.getDevice().toString());
             UsbSerialPort port = driver.getPorts().get(0);
-           if (driver instanceof Ch34xSerialDriver){
-               BaseDeviceEntity weightDevice= isWeightDevice(driver);
-               if( weightDevice!= null){
-                   SPUtils.getInstance().put("RunningState",1);
-                   System.out.println("是称重设备");
-                   deviceList.add(weightDevice);
-                   continue;
-               }
+            if (driver instanceof Ch34xSerialDriver) {
+                BaseDeviceEntity weightDevice = isWeightDevice(driver);
+                if (weightDevice != null && addWeight) {
+                    addWeight = false;
+                    SPUtils.getInstance().put("RunningState", 1);
+                    Log.i(TAG, "添加称重设备");
+                    deviceList.add(weightDevice);
+                    continue;
+                }
 //               else{
 //                   try {
 //                       SPUtils.getInstance().put("RunningState","1");
@@ -72,15 +81,27 @@ public class SerialPortUtil {
 //                       ex.printStackTrace();
 //                   }
 //               }
-               BaseDeviceEntity otherDevicde = isOtherDevice(driver);
-               if(otherDevicde != null ){
-                   System.out.println("是otherDevice");
-                   deviceList.add(otherDevicde);
-                   SerialPortUtil.getInstance().getOtherDevice().setPower();//设置电量阈值
-               }
+                BaseDeviceEntity otherDevicde = isOtherDevice(driver);
+                if (otherDevicde != null && addOther) {
+                    addOther = false;
+                    System.out.println("是otherDevice");
+                    Log.i(TAG, "添加其他设备");
+
+                    deviceList.add(otherDevicde);
+//                   SerialPortUtil.getInstance().getOtherDevice().setPower();//设置电量阈值
+                    continue;
+                }
+
+                BaseDeviceEntity ultrasonicDevice = isultrasonicDevice(driver);
+                if (ultrasonicDevice != null && addUltasonic) {
+                    addUltasonic = false;
+                    deviceList.add(ultrasonicDevice);
+                    Log.i(TAG, "添加超声波设备");
+                    continue;
+                }
 //               else {
 //                   try {
-//                       WarnActivity.SendSmsResponse("杆、门磁、锁、温度、红外、超声波设备未检测到");
+//                       WarnActivity.SendSmsResponse("杆、门磁、锁、、红外、超声波设备未检测到");
 //                   } catch (ClientException ex) {
 //                       ex.printStackTrace();
 //                   }
@@ -89,9 +110,9 @@ public class SerialPortUtil {
 
 //               deviceList.add(new PushRodDevice(mUsbManager,driver));
 //               deviceList.add(new WeightDevice(mUsbManager,driver));
-           }else if(driver instanceof ProlificSerialDriver){
-               deviceList.add(new RelayControllerDevice(mUsbManager,driver));
-           }
+            } else if (driver instanceof ProlificSerialDriver) {
+                deviceList.add(new RelayControllerDevice(mUsbManager, driver));
+            }
 /*
             final List<UsbSerialPort> ports = driver.getPorts();
             UsbDevice device= driver.getDevice();
@@ -111,7 +132,7 @@ public class SerialPortUtil {
         BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
             @Override
             public void onReceive(Context context, Intent intent) {
-                if(intent.getAction().equals(INTENT_ACTION_GRANT_USB)) {
+                if (intent.getAction().equals(INTENT_ACTION_GRANT_USB)) {
                     if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                         System.out.println("granted extra permission");
 //                        writeAndReadPort(port);
@@ -126,30 +147,30 @@ public class SerialPortUtil {
         mContext.registerReceiver(mUsbReceiver, new IntentFilter(INTENT_ACTION_GRANT_USB));
 
         System.out.println("ports size:" + availablePorts.size());
-        if(availablePorts.size() == 0) {
-            Log.e(TAG,"没有RS232 或 RS485 设备");
+        if (availablePorts.size() == 0) {
+            Log.e(TAG, "没有RS232 或 RS485 设备");
             return;
         }
         PendingIntent usbPermissionIntent = PendingIntent.getBroadcast(context, 12, new Intent(INTENT_ACTION_GRANT_USB), 0);
-        for(UsbSerialPort port: availablePorts){
-            if(!mUsbManager.hasPermission(port.getDriver().getDevice())){
-                mUsbManager.requestPermission(port.getDriver().getDevice(),usbPermissionIntent);
+        for (UsbSerialPort port : availablePorts) {
+            if (!mUsbManager.hasPermission(port.getDriver().getDevice())) {
+                mUsbManager.requestPermission(port.getDriver().getDevice(), usbPermissionIntent);
             }
         }
     }
 
 
-    public WeightDevice getWeightDevice(){
-        for(BaseDeviceEntity deviceEntity  : deviceList){
-            if(deviceEntity instanceof WeightDevice)
+    public WeightDevice getWeightDevice() {
+        for (BaseDeviceEntity deviceEntity : deviceList) {
+            if (deviceEntity instanceof WeightDevice)//用来测试一个对象是否为一个类的实例
                 return (WeightDevice) deviceEntity;
         }
         return null;
     }
 
-    public PushRodDevice getPushRodDevice(){
-        for(BaseDeviceEntity deviceEntity : deviceList){
-            if(deviceEntity instanceof PushRodDevice){
+    public PushRodDevice getPushRodDevice() {
+        for (BaseDeviceEntity deviceEntity : deviceList) {
+            if (deviceEntity instanceof PushRodDevice) {
                 return (PushRodDevice) deviceEntity;
             }
 
@@ -157,18 +178,31 @@ public class SerialPortUtil {
         return null;
     }
 
-    public RelayControllerDevice getRelayControllerDevive(){
-        for(BaseDeviceEntity deviceEntity : deviceList){
-            if(deviceEntity instanceof RelayControllerDevice){
+    //超声波
+    public UltrasonicDevice getUltrasonicDevice() {
+        for (BaseDeviceEntity deviceEntity : deviceList) {
+            Log.i(TAG, "getUltrasonicDevice: " + deviceEntity);
+            if (deviceEntity instanceof UltrasonicDevice) {
+                return (UltrasonicDevice) deviceEntity;
+            }
+
+        }
+        return null;
+    }
+
+
+    public RelayControllerDevice getRelayControllerDevive() {
+        for (BaseDeviceEntity deviceEntity : deviceList) {
+            if (deviceEntity instanceof RelayControllerDevice) {
                 return (RelayControllerDevice) deviceEntity;
             }
         }
         return null;
     }
 
-    public OtherDevice getOtherDevice(){
-        for(BaseDeviceEntity deviceEntity : deviceList ){
-            if(deviceEntity instanceof OtherDevice){
+    public OtherDevice getOtherDevice() {
+        for (BaseDeviceEntity deviceEntity : deviceList) {
+            if (deviceEntity instanceof OtherDevice) {
                 return (OtherDevice) deviceEntity;
             }
         }
@@ -176,30 +210,46 @@ public class SerialPortUtil {
     }
 
 
-    private BaseDeviceEntity isOtherDevice( UsbSerialDriver driver ){
-        OtherDevice otherDevice = new OtherDevice(mUsbManager,driver);
-//        Integer infrared = otherDevice.queryInfrared();
-        Integer  magDoor = otherDevice.queryMagDoor();
-        Log.i("otherDevice","---------------------------------------");
-//        if(infrared == 0) {
+    private BaseDeviceEntity isOtherDevice(UsbSerialDriver driver) {
+        OtherDevice otherDevice = new OtherDevice(mUsbManager, driver);
+        Integer infrared = otherDevice.openLock();
+//        Integer  magDoor = otherDevice.queryMagDoor();
+        Log.i("otherDevice", "---------------------------------------");
+        if (infrared == 0) {
+            otherDevice.close();
+            Log.i("otherDevice", "==null");
+            return null;
+        }
+//        if(magDoor == 3) {
 //            otherDevice.close();
 //            Log.i("otherDevice","==null");
 //            return null;
 //        }
-        if(magDoor == 3) {
-            otherDevice.close();
-            Log.i("otherDevice","==null");
+        return otherDevice;
+    }
+
+    //超声波
+    private BaseDeviceEntity isultrasonicDevice(UsbSerialDriver driver) {
+        UltrasonicDevice ultrasonicDevice = new UltrasonicDevice(mUsbManager, driver);
+        Integer infrared = ultrasonicDevice.ultRead();
+        if (infrared == 0) {
+            ultrasonicDevice.close();
             return null;
         }
-        return otherDevice;
+//        if(magDoor == 3) {
+//            otherDevice.close();
+//            Log.i("otherDevice","==null");
+//            return null;
+//        }
+        return ultrasonicDevice;
     }
 
-    private BaseDeviceEntity isWeightDevice(UsbSerialDriver driver){
-        WeightDevice weightDevice = new WeightDevice(mUsbManager,driver);
+    private BaseDeviceEntity isWeightDevice(UsbSerialDriver driver) {
+        WeightDevice weightDevice = new WeightDevice(mUsbManager, driver);
         Integer weight = weightDevice.readIsWeight();
-        Log.i("weightDevice","---------------------------------------");
-        if(weight== 1){
-            Log.i("weightDevice","==NULL");
+        Log.i("weightDevice", "---------------------------------------");
+        if (weight == 1) {
+            Log.i("weightDevice", "==NULL");
             weightDevice.close();
             return null;
         }

+ 108 - 0
app/src/main/java/com/siwei/recyclebox/deviceUtils/UltrasonicDevice.java

xqd
@@ -0,0 +1,108 @@
+package com.siwei.recyclebox.deviceUtils;
+
+import android.hardware.usb.UsbManager;
+import android.speech.tts.TextToSpeech;
+import android.util.Log;
+
+import com.aliyuncs.exceptions.ClientException;
+import com.siwei.recyclebox.ui.main.MainViewModel;
+import com.hoho.android.usbserial.driver.UsbSerialDriver;
+import com.hoho.android.usbserial.driver.UsbSerialPort;
+
+import android.os.Handler;
+
+import java.io.IOException;
+import java.util.Spliterator;
+import java.util.logging.LogRecord;
+
+import me.goldze.mvvmhabit.utils.SPUtils;
+import me.goldze.mvvmhabit.utils.Utils;
+
+
+public class UltrasonicDevice extends BaseDeviceEntity {
+
+    public UltrasonicDevice(UsbManager usbManager, UsbSerialDriver driver) {
+        super(usbManager, driver);
+    }
+
+    /**
+     * 串口的连接参数:
+     * baudRate: 波特率
+     * dataBits: 数据位 一般为8
+     * stopBits: 停止位 一般为1
+     * parity: 奇偶校验 UsbSerialPort.PARITY_ODD、UsbSerialPort.PARITY_EVEN、UsbSerialPort.PARITY_NONE
+     */
+
+    @Override
+    int getBaudRate() {
+        return 9600;
+    }
+
+    @Override
+    int getDataBits() {
+        return UsbSerialPort.DATABITS_8;
+    }
+
+    @Override
+    int getStopBits() {
+        return UsbSerialPort.STOPBITS_1;
+    }
+
+    @Override
+    int getParity() {
+        return UsbSerialPort.PARITY_NONE;
+    }
+
+    @Override
+    int getVendorId() {
+        return 6790;
+    }
+
+    @Override
+    void onDataReceived(byte[] response) {
+
+    }
+
+    String TAG = "超声波";
+
+    /**
+     * 超声波读数
+     * 01 03 01 02 00 01 24 36
+     */
+    public Integer ultRead() {
+        int disInt = 0;
+        while (true){
+            try {
+//                Thread.sleep(500);
+                byte[] bytes = new byte[]{(byte) 0x01, (byte) 0x03, 0x01, 0x02, 0x00, 0x01, 0x24, (byte) 0x36};
+                port.write(bytes, 100);
+                Log.i(TAG,"发 :"+ ByteUtil.bytesToString(bytes));
+                byte[] response = new byte[12];
+                int len = port.read(response, 100);
+                Log.i(TAG, "收 :"+ByteUtil.bytesToString(response));
+                Log.i(TAG, "数组长度 :" + len);
+                byte[] disBytes = new byte[4];
+                disBytes[2] = response[3];
+                disBytes[3] = response[4];
+                disInt = ByteUtil.bytes2Int(disBytes);
+                Log.i(TAG, "距离 :" + disInt);
+//                if (response[4] == 85 && response[5] == 1) {
+                if (len == 7) {
+                    Log.i(TAG, "ultRead: "+disInt);
+                    return disInt;
+                } else {
+                    SPUtils.getInstance().put("RunningState", 5);
+//                    MainViewModel.SendSmsResponse("温度超声波失灵");
+                    Thread.sleep(200);
+                }
+            } catch (Exception e) {
+                e.printStackTrace();
+                SPUtils.getInstance().put("RunningState", 1);
+                MainViewModel.SendSmsResponse("其他设备未检测到");
+                return 0;
+            }
+        }
+//        return (Integer)disInt;
+    }
+}
+    

+ 25 - 15
app/src/main/java/com/siwei/recyclebox/deviceUtils/WeightDevice.java

xqd xqd xqd xqd xqd
@@ -115,7 +115,8 @@ public class WeightDevice extends BaseDeviceEntity {
                     weightBytes[3] = response[4];
                     int weightInt = ByteUtil.bytes2Int(weightBytes);
 //                    weightInt=weightInt*5*2;
-                    num += (weightInt * 5 * 2);
+                    num += (weightInt * 10);
+//                    num += weightInt;
                     a++;
                     Log.i("while","********"+a);
                 }
@@ -124,7 +125,7 @@ public class WeightDevice extends BaseDeviceEntity {
                 weightBytes[2] = response[3];
                 weightBytes[3] = response[4];
                 int weightInt = ByteUtil.bytes2Int(weightBytes);
-                weightInt=weightInt*5*2;
+                weightInt=weightInt*10;
                 System.out.println("称重读数:"+weightInt);
                 int weightNumber=num/a++;
                 if(weightInt>=327670){
@@ -157,39 +158,44 @@ public class WeightDevice extends BaseDeviceEntity {
      */
     public synchronized void weightClear(){
         byte[] cleanOrderBytes = new byte[]{0x1F,0x06 ,0x00 ,0x24,0x00 ,0x00, (byte) 0xCA,0x7F};
-        System.out.println("称重器读数清零!!!!!");
+        System.out.println();
         try {
             port.write(cleanOrderBytes,150);
             byte[] response=new byte[8];
             port.read(response,200);
+            Log.i(TAG,"称重器读数清零!!!!!:"+ByteUtil.bytesToString(response));
         } catch (IOException e) {
             e.printStackTrace();
         }
     }
+
     /*
-     * 设置分度值
+     * 空载
      * */
-    public synchronized void setScale(){
-        byte[] cleanOrderBytes = new byte[]{0x1F, 0x06 ,0x00 ,0x04 ,0x00 ,0x01 ,0x0A ,0x75};
+    public synchronized void zeroCalibration(){
+        byte[] cleanOrderBytes = new byte[]{0x1F ,0x10 ,0x00 ,0x08 ,0x00 ,0x02 ,0x04 ,0x00 ,0x00 ,0x00 ,0x00 , (byte) 0x92,0x21 };
         try {
             port.write(cleanOrderBytes,150);
             byte[] response=new byte[8];
             port.read(response,200);
-            Log.i(TAG,"设置分度值");
+            Log.i(TAG,"空载:"+ByteUtil.bytesToString(response));
         } catch (IOException e) {
             e.printStackTrace();
         }
     }
     /*
-     * 空载
+     * 设置分度值
      * */
-    public synchronized void zeroCalibration(){
-        byte[] cleanOrderBytes = new byte[]{0x1F ,0x10 ,0x00 ,0x08 ,0x00 ,0x02 ,0x04 ,0x00 ,0x00 ,0x00 ,0x00 , (byte) 0x92,0x21 };
+    public synchronized void setScale(){//1F 06 00 04 00 01 0A 75              02  4A 74
+
+//        byte[] cleanOrderBytes = new byte[]{0x1F, 0x06 ,0x00 ,0x04 ,0x00 ,0x02 ,0x0A ,0x75};
+        byte[] cleanOrderBytes = new byte[]{0x1F, 0x06 ,0x00 ,0x04 ,0x00 ,0x02 ,0x4A ,0x74};
+
         try {
             port.write(cleanOrderBytes,150);
             byte[] response=new byte[8];
             port.read(response,200);
-            Log.i(TAG,"空载");
+            Log.i(TAG,"设置分度值2:"+ByteUtil.bytesToString(response));
         } catch (IOException e) {
             e.printStackTrace();
         }
@@ -197,13 +203,15 @@ public class WeightDevice extends BaseDeviceEntity {
     /*
      * 量程设定
      * */
-    public synchronized void weightSet(){
+    public synchronized void weightSet(){//1F 10 00 00 00 02 04 27 10 00 00 98 F6
         byte[] cleanOrderBytes = new byte[]{0x1F ,0x10 ,0x00 ,0x00 ,0x00 ,0x02 ,0x04 , 0x27, 0x10,0x00 ,0x00 , (byte) 0x98, (byte) 0xF6};
+//        byte[] cleanOrderBytes = new byte[]{0x1F ,0x10 ,0x00 ,0x00 ,0x00 ,0x02 ,0x04 , 0x4E, 0x20,0x00 ,0x00 , (byte) 0x98, (byte) 0xF6};
+
         try {
             port.write(cleanOrderBytes,150);
             byte[] response=new byte[8];
             port.read(response,200);
-            Log.i(TAG,"l量程设定");
+            Log.i(TAG,"l0000量程设定:"+ByteUtil.bytesToString(response));
         } catch (IOException e) {
             e.printStackTrace();
         }
@@ -213,13 +221,15 @@ public class WeightDevice extends BaseDeviceEntity {
      * */
     public synchronized void weightCalibration(){
         //1F 10 00 10 00 02 04 03 E8 00 00 12 FB
-        byte[] cleanOrderBytes = new byte[]{0x1F ,0x10 ,0x00 ,0x10 ,0x00 ,0x02 ,0x04 ,0x03 , (byte) 0xE8,0x00 ,0x00, (byte) 0x96, (byte) 0xE4};
+        byte[] cleanOrderBytes = new byte[]{0x1F ,0x10 ,0x00 ,0x10 ,0x00 ,0x02 ,0x04 ,0x03 , (byte) 0xE8,0x00 ,0x00, 0x12, (byte) 0xFB};
+//        byte[] cleanOrderBytes = new byte[]{0x1F ,0x10 ,0x00 ,0x10 ,0x00 ,0x02 ,0x04 ,0x27 , 0x10,0x00 ,0x00, (byte) 0x96, (byte) 0xE4};
+
 //        byte[] cleanOrderBytes = new byte[]{0x1F ,0x10 ,0x00 ,0x10 ,0x00 ,0x02 ,0x04 ,0x27 ,0x10 ,0x00 ,0x00, (byte) 0x96, (byte) 0xE4};
         try {
             port.write(cleanOrderBytes,150);
             byte[] response=new byte[8];
             port.read(response,200);
-            Log.i(TAG,"砝码校准kg");
+            Log.i(TAG,"砝码校准10kg:"+ByteUtil.bytesToString(response));
         } catch (IOException e) {
             e.printStackTrace();
         }

+ 17 - 4
app/src/main/java/com/siwei/recyclebox/receiver/BootReceiver.java

xqd xqd
@@ -3,6 +3,7 @@ package com.siwei.recyclebox.receiver;
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
+import android.os.Handler;
 import android.util.Log;
 
 import com.siwei.recyclebox.ui.main.MainActivity;
@@ -10,11 +11,23 @@ import com.siwei.recyclebox.ui.main.MainActivity;
 public class BootReceiver extends BroadcastReceiver {
     private static final String TAG = "BootReceiver";
 
+    /*
+    * 广播监听开机,开机就启动app;开机时网络可能要等会儿才能识别到,所以延迟启动
+    * */
     @Override
     public void onReceive(Context context, Intent intent) {
-        Log.e(TAG,"onReceive//////////////////:"+intent);
-        Intent i = new Intent(context,MainActivity.class);
-        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
-        context.startActivity(i);
+        mHandler.postDelayed(new Runnable() {
+            @Override
+            public void run() {
+                Log.e(TAG,"onReceive//////////////////:"+intent);
+                Intent i = new Intent(context,MainActivity.class);
+                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
+                context.startActivity(i);
+            }
+        },60000);
+
     }
+    public android.os.Handler mHandler = new Handler(msg -> {
+        return true;
+    });
 }

+ 131 - 5
app/src/main/java/com/siwei/recyclebox/service/MyService.java

xqd
@@ -1,45 +1,171 @@
 package com.siwei.recyclebox.service;
 
+import android.app.Activity;
+import android.app.ActivityManager;
 import android.app.AlarmManager;
+import android.app.Application;
+import android.app.Notification;
 import android.app.PendingIntent;
 import android.app.Service;
 import android.content.Context;
 import android.content.Intent;
+import android.os.Binder;
+import android.os.Bundle;
+import android.os.Handler;
 import android.os.IBinder;
 import android.util.Log;
+import android.widget.RemoteViews;
 import android.widget.Toast;
 
+import com.siwei.recyclebox.R;
 import com.siwei.recyclebox.ui.main.MainActivity;
 
-public class MyService extends Service {
+import java.util.List;
+import java.util.Timer;
+import java.util.TimerTask;
 
+public class MyService extends Service {
+    public  final IBinder mBinder=new LocalBinder();
     @Override
     public IBinder onBind(Intent arg0) {
         return null;
     }
-
+    private final Timer timer=new Timer();
+    private TimerTask task1;
     @Override
     public int onStartCommand(Intent intent, int flags, int startId) {
         // Let it continue running until it is stopped.
 //        Toast.makeText(this, "服务已经启动", Toast.LENGTH_LONG).show();
-        Log.i("server","服务已经启动");
+       Log.i("server","服务已经启动");
+        task1=new TimerTask() {
+            @Override
+            public void run() {
+                isBackground(getApplicationContext());
+            }
+        };
+        timer.schedule(task1,10000,60000);
         return START_STICKY;
     }
+    public class LocalBinder extends Binder {
+        // 在Binder中定义一个自定义的接口用于数据交互
+              // 这里直接把当前的服务传回给宿主
+              public MyService getService(){
+                      return MyService.this;
+                  }
+     }
+    @Override
+    public boolean onUnbind(Intent intent) {
+        Log.i("onUnbind","1111111111");
+        Intent mStartActivity = new Intent(getApplicationContext(), MainActivity.class);
+        int mPendingIntentId = 123456;
+        PendingIntent mPendingIntent = PendingIntent.getActivity(this, mPendingIntentId,    mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
+        AlarmManager mgr = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
+        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
+        System.exit(0);
+        return super.onUnbind(intent);
+    }
 
     @Override
     public void onDestroy() {
 
 //            Intent intent=new Intent(this,MyService.class);
 //            this.startService(intent);
-
-        Intent mStartActivity = new Intent(this, MainActivity.class);
+        Log.i("onDestroy","1111111111");
+        Intent mStartActivity = new Intent(getApplicationContext(), MainActivity.class);
         int mPendingIntentId = 123456;
         PendingIntent mPendingIntent = PendingIntent.getActivity(this, mPendingIntentId,    mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
         AlarmManager mgr = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
         mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
         System.exit(0);
+
         super.onDestroy();
 //        Toast.makeText(this, "服务已经停止", Toast.LENGTH_LONG).show();
 //        Log.i("","服务已经停止");
     }
+
+    @Override
+    public void onCreate() {
+        super.onCreate();
+    }
+/*    class ActivityLifecycleListener implements Application.ActivityLifecycleCallbacks {
+
+        private int refCount = 0;
+
+        @Override
+        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
+
+        }
+
+        @Override
+        public void onActivityStarted(Activity activity) {
+            refCount++;
+        }
+
+        @Override
+        public void onActivityResumed(Activity activity) {
+
+        }
+
+        @Override
+        public void onActivityPaused(Activity activity) {
+
+        }
+
+        @Override
+        public void onActivityStopped(Activity activity) {
+            refCount--;
+            if(refCount == 0){
+                Intent mStartActivity = new Intent(getApplicationContext(), MainActivity.class);
+                int mPendingIntentId = 123456;
+                PendingIntent mPendingIntent = PendingIntent.getActivity(getApplicationContext(), mPendingIntentId,    mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
+                AlarmManager mgr = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
+                mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
+                System.exit(0);
+            }
+        }
+
+        @Override
+        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
+
+        }
+
+        @Override
+        public void onActivityDestroyed(Activity activity) {
+        }
+    }*/
+    public boolean isBackground(Context context) {
+        ActivityManager activityManager = (ActivityManager) context
+                .getSystemService(Context.ACTIVITY_SERVICE);
+        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
+                .getRunningAppProcesses();
+        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
+            if (appProcess.processName.equals(context.getPackageName())) {
+                /*
+                BACKGROUND=400 EMPTY=500 FOREGROUND=100
+                GONE=1000 PERCEPTIBLE=130 SERVICE=300 ISIBLE=200
+                 */
+                Log.i(context.getPackageName(), "此appimportace ="
+                        + appProcess.importance
+                        + ",context.getClass().getName()="
+                        + context.getClass().getName());
+                if (appProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
+                    Log.i(context.getPackageName(), "处于后台"
+                            + appProcess.processName);
+                    Intent mStartActivity = new Intent(getApplicationContext(), MainActivity.class);
+                    int mPendingIntentId = 123456;
+                    PendingIntent mPendingIntent = PendingIntent.getActivity(getApplicationContext(), mPendingIntentId,    mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
+                    AlarmManager mgr = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
+                    mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
+                    System.exit(0);
+                    return true;
+                } else {
+                    Log.i(context.getPackageName(), "处于前台"
+                            + appProcess.processName);
+                    return false;
+                }
+            }
+        }
+        return false;
+    }
+
 }

+ 228 - 12
app/src/main/java/com/siwei/recyclebox/ui/main/MainActivity.java

xqd xqd xqd xqd
@@ -2,11 +2,26 @@ package com.siwei.recyclebox.ui.main;
 
 import android.app.AlarmManager;
 import android.app.PendingIntent;
+import android.app.Service;
 import android.bluetooth.BluetoothAdapter;
+import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
+import android.content.ServiceConnection;
 import android.databinding.ViewDataBinding;
+import android.net.TrafficStats;
+import android.net.Uri;
+import android.net.wifi.WifiInfo;
+import android.net.wifi.WifiManager;
+import android.os.Build;
 import android.os.Bundle;
+import android.os.IBinder;
+import android.os.PowerManager;
+import android.provider.Settings;
+import android.support.annotation.RequiresApi;
+import android.telephony.PhoneStateListener;
+import android.telephony.SignalStrength;
+import android.telephony.TelephonyManager;
 import android.util.Log;
 
 import com.siwei.recyclebox.BR;
@@ -14,22 +29,179 @@ import com.siwei.recyclebox.R;
 import com.siwei.recyclebox.service.MyService;
 
 
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.nio.file.Path;
+import java.util.Timer;
+import java.util.TimerTask;
+
 import me.goldze.mvvmhabit.base.BaseActivity;
 
+import static java.nio.file.Files.newBufferedReader;
 
-public class MainActivity extends BaseActivity<ViewDataBinding,MainViewModel> {
 
+public class MainActivity extends BaseActivity<ViewDataBinding,MainViewModel> {
+    TimerTask task1;
+    Timer timer=new Timer();
+    TelephonyManager telephonyManager ;
+    private PhoneStatListener phoneStatListener;
     private static final String TAG = "MainActivity";
 
+
+    @RequiresApi(api = Build.VERSION_CODES.O)
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+//        Log.i("uuid","="+getMacAddress());
+//        getNetSpeed(getApplicationContext());//获取网速
+//        listenerSignal(getApplication());//获取信号强度
+//        task1=new TimerTask() {
+//            @Override
+//            public void run() {
+//                try {
+//                    getNetQuelity();//获取ping ip 的丢包率和延迟
+//                } catch (IOException e) {
+//                    e.printStackTrace();
+//                }
+//            }
+//        };
+//        timer.schedule(task1,1000,4000);
+    }
+
     //页面接收的参数方法
     @Override
     public void initParam() {
         super.initParam();
         Intent service = new Intent(getApplication(), MyService.class);
         getApplication().startService(service);
+        getApplication().bindService(new Intent(MainActivity.this,MyService.class),mConnection, Service.BIND_AUTO_CREATE);
+
+    }
+
+    private long lastTotalRxBytes = 0;
+    private long lastTimeStamp = 0;
+    /**
+     * 得到网络速度
+     * @param context
+     * @return
+     */
+    public String getNetSpeed(Context context) {
+        Log.i("getNetSpeed","1----------------------------------------------------------");
+        String netSpeed = "0 kb/s";
+        long nowTotalRxBytes = TrafficStats.getUidRxBytes(context.getApplicationInfo().uid)==
+                TrafficStats.UNSUPPORTED ? 0 :(TrafficStats.getTotalRxBytes()/1024);//转为KB;
+        long nowTimeStamp = System.currentTimeMillis();
+        long speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / (nowTimeStamp - lastTimeStamp));//毫秒转换
+
+        lastTimeStamp = nowTimeStamp;
+        lastTotalRxBytes = nowTotalRxBytes;
+        netSpeed  = String.valueOf(speed) + " kb/s";
+        Log.i("getNetSpeed","网速:"+netSpeed);
+        Log.i("getNetSpeed","2----------------------------------------------------------");
+        return  netSpeed;
+
     }
+    @RequiresApi(api = Build.VERSION_CODES.O)
+    public void getNetQuelity() throws IOException {
+        String lost;
+        String delay;
+        //a13H8L6bDyf.iot-as-mqtt.cn-huadong2.aliyuncs.com:1883
+        Process p = Runtime.getRuntime().exec("ping -c 4 " + "a13H8L6bDyf.iot-as-mqtt.cn-shanghai.aliyuncs.com");
+        BufferedReader buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
+        String str = "";
+        while((str=buf.readLine())!=null){
+            if(str.contains("packet loss")){
+                int i= str.indexOf("received");
+                int j= str.indexOf("%");
+                System.out.println("丢包率:"+str.substring(i+10, j+1));
+//					System.out.println("丢包率:"+str.substring(j-3, j+1));
+                lost = str.substring(i+10, j+1);
+                Log.i(TAG,"getNetQuelity--------------------"+lost);
+            }
+            if(str.contains("avg")){
+                int i=str.indexOf("/", 20);
+                int j=str.indexOf(".", i);
+                System.out.println("延迟:"+str.substring(i+1, j));
+                delay =str.substring(i+1, j);
+                delay = delay+"ms";
+                Log.i(TAG,"getNetQuelity--------------------"+delay);
+            }
+        }
+    }
+    /**
+     * 监听网络强度
+     *
+     * @param context
+     */
+    public void listenerSignal(Context context) {
+        Log.i("listenerSignal","1----------------------------------------------------------");
+
+        //获取一个电话管理类
+        telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
+        phoneStatListener = new PhoneStatListener();
+
+        //通过 listen 方法来侦听电话信息的改变,这里用来侦听网络信号的强度变化,具体还能侦听什么需要看 PhoneStateListener 类的源码
+        telephonyManager.listen(phoneStatListener, PhoneStatListener.LISTEN_SIGNAL_STRENGTHS);
+        Log.i("listenerSignal","2----------------------------------------------------------");
+    }
+    private class PhoneStatListener extends PhoneStateListener {
+        private int mSignalStrength=0;
+        @Override
+        public void onSignalStrengthsChanged(SignalStrength signalStrength) {
+            Log.i("PhoneStatListener","信号:"+mSignalStrength);
+            //获取信号强度变化
+            super.onSignalStrengthsChanged(signalStrength);
+            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+                mSignalStrength = signalStrength.getLevel();
+                return;
+            }
+            mSignalStrength = signalStrength.getGsmSignalStrength();
+            Log.i("PhoneStatListener","信号:"+mSignalStrength);
+        }
+    }
+
+//    public String getMacAddress() {
+//        //获取 uuid
+//        String macAddress = null;
+//        WifiManager wifiManager =
+//                (WifiManager)getApplication().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
+//        WifiInfo info = (null == wifiManager ? null : wifiManager.getConnectionInfo());
+//        if (!wifiManager.isWifiEnabled()){
+//            //必须先打开,才能获取到MAC地址
+//            wifiManager.setWifiEnabled(true);
+//            wifiManager.setWifiEnabled(false);
+//        }
+//        if (null != info) {
+//            macAddress = info.getMacAddress();
+//        }
+//        return macAddress;
+//    }
+
+    MyService mService=null;
+    private ServiceConnection mConnection = new ServiceConnection() {
+
+
+        @Override
+        public void onServiceDisconnected(ComponentName name) {
+            mService = null;
+        }
+
+        @Override
+         public void onServiceConnected(ComponentName name, IBinder service) {
+                         // 获取服务上的IBinder对象,调用IBinder对象中定义的自定义方法,获取Service对象
+            MyService.LocalBinder binder=(MyService.LocalBinder)service;
+                       mService=binder.getService();
+                    }
+    };
+
+
 
     //页面数据初始化方法。
+    @RequiresApi(api = Build.VERSION_CODES.M)
     @Override
     public void initData() {
 //        viewModel.btnClick.onClick();
@@ -40,10 +212,35 @@ public class MainActivity extends BaseActivity<ViewDataBinding,MainViewModel> {
 //        viewModel.repeatTask();
         Log.i("repeatTask","*****************************************");
         viewModel.startBLEServer();
-//        viewModel.netWorkInfo();
+        if(!isIgnoringBatteryOptimizations()){
+            requestIgnoreBatteryOptimizations();
+        }
+        viewModel.netWorkInfo();
 //        viewModel.openWeight();
 //        System.out.println("serialPortUtil.readControllerStatus:"+ SerialPortUtil.getInstance().readRelayControllerStatus());
     }
+    @RequiresApi(api = Build.VERSION_CODES.M)
+    private boolean isIgnoringBatteryOptimizations() {
+        boolean isIgnoring = false;
+        PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
+        if (powerManager != null) {
+            isIgnoring = powerManager.isIgnoringBatteryOptimizations(getPackageName());
+            Log.i("白名单","已经添加白名单");
+        }
+        return isIgnoring;
+    }
+    @RequiresApi(api = Build.VERSION_CODES.M)
+    public void requestIgnoreBatteryOptimizations() {
+        try {
+            Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
+            intent.setData(Uri.parse("package:" + getPackageName()));
+            startActivity(intent);
+            Log.i("白名单","申请添加白名单");
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
 
     public void openBlueTooth(){
 //      打开蓝牙(提示对话框)
@@ -90,19 +287,38 @@ public class MainActivity extends BaseActivity<ViewDataBinding,MainViewModel> {
 
     @Override
     protected void onDestroy() {
-
-//        viewModel.closePort();
+        super.onDestroy();
         viewModel.stopBleServer();
         viewModel.unRegisterIoTListener();
-        Log.e("MainActivity.","unregisterIoTListener!!!");
-        Intent mStartActivity = new Intent(getApplication(),MainActivity.class);
-        int mPendingIntentId = 123456;
-        PendingIntent mPendingIntent = PendingIntent.getActivity(getApplication(), mPendingIntentId,    mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
-        AlarmManager mgr = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
-        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
-        System.exit(0);
-        super.onDestroy();
+        getApplication().unbindService(mConnection);
+        mService=null;
+        viewModel.closePort();
+
+//        Log.e("MainActivity.","unregisterIoTListener!!!");
+//        Intent mStartActivity = new Intent(getApplication(),MainActivity.class);
+//        int mPendingIntentId = 123456;
+//        PendingIntent mPendingIntent = PendingIntent.getActivity(getApplication(), mPendingIntentId,    mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
+//        AlarmManager mgr = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
+//        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
+//        System.exit(0);
+
+    }
+
+    @Override
+    protected void onStop() {
+        super.onStop();
 
+        getApplication().unbindService(mConnection);
+        mService=null;
+//        viewModel.stopBleServer();
+//        viewModel.unRegisterIoTListener();
+//        Log.e("MainActivity.","unregisterIoTListener!!!");
+//        Intent mStartActivity = new Intent(getApplication(),MainActivity.class);
+//        int mPendingIntentId = 123456;
+//        PendingIntent mPendingIntent = PendingIntent.getActivity(getApplication(), mPendingIntentId,    mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
+//        AlarmManager mgr = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
+//        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
+//        System.exit(0);
     }
 
     @Override

ファイルの差分が大きいため隠しています
+ 405 - 588
app/src/main/java/com/siwei/recyclebox/ui/main/MainViewModel.java


+ 214 - 239
app/src/main/res/layout/activity_main.xml

xqd xqd xqd xqd xqd xqd
@@ -9,96 +9,116 @@
         <variable
             name="viewModal"
             type="com.siwei.recyclebox.ui.main.MainViewModel"/>
+<!--        关联view model-->
     </data>
 
-    <ScrollView
+    <LinearLayout
         android:layout_width="match_parent"
-        android:layout_height="match_parent">
-        <LinearLayout
+        android:layout_height="match_parent"
+        android:orientation="vertical">
+
+        <TableLayout
             android:layout_width="match_parent"
-            android:layout_height="wrap_content"
-            android:orientation="vertical">
+            android:collapseColumns="1"
+            android:layout_height="wrap_content">
+                <android.support.constraint.ConstraintLayout
+                    android:layout_width="match_parent"
+                    android:layout_height="130dp"
+                    android:padding="16dp">
 
-            <!--<TextView
-                android:id="@+id/textView"
-                android:layout_width="0dp"
-                android:layout_height="11dp"
-                android:text=""
-                android:textSize="18sp"
-                app:layout_constraintBottom_toBottomOf="parent"
-                app:layout_constraintHorizontal_bias="0.283"
-                app:layout_constraintLeft_toLeftOf="parent"
-                app:layout_constraintRight_toRightOf="parent"
-                app:layout_constraintTop_toTopOf="parent"
-                app:layout_constraintVertical_bias="0.022" />-->
-            <LinearLayout
-                android:layout_width="match_parent"
-                android:layout_height="130dp"
-                android:padding="16dp">
+                        <Button
+                            app:layout_constraintTop_toTopOf="parent"
+                            app:layout_constraintLeft_toLeftOf="parent"
+                            android:layout_width="120dp"
+                            android:layout_height="96dp"
+                            android:onClick="@{viewModal.btnQeryIMEI}"
+                            android:text="查询IMEI:**"
+                            android:textSize="24sp"
+                            android:id="@+id/btn1"/>
+                        <TextView
+                            app:layout_constraintLeft_toRightOf="@+id/btn1"
+                            app:layout_constraintTop_toTopOf="parent"
+                            android:layout_width="400dp"
+                            android:layout_height="77dp"
+                            android:layout_marginStart="1dp"
+                            android:layout_marginTop="1dp"
+                            android:layout_marginEnd="2dp"
+                            android:text="@={viewModal.textIMEI}"
+                            android:textSize="30dp" />
+                    <LinearLayout
+                        app:layout_constraintRight_toRightOf="parent"
+                        android:layout_width="wrap_content"
+                        android:layout_height="match_parent">
+                        <Button
+                            android:layout_width="150dp"
+                            android:layout_height="100dp"
+                            android:onClick="@{viewModal.btnClickrestartApp}"
+                            android:text="重启"
+                            android:textSize="24sp"
+                            />
+                        <Button
+                            android:layout_width="150dp"
+                            android:layout_height="100dp"
+                            android:onClick="@{viewModal.btnClickfinishApp}"
+                            android:text="关闭"
+                            android:textSize="24sp"
+                            />
+                        <Button
+                            android:layout_width="150dp"
+                            android:layout_height="100dp"
+                            android:onClick="@{viewModal.btnClickrestartAndroid}"
+                            android:text="重启系统"
+                            android:textSize="24sp"
+                            />
+                    </LinearLayout>
+                </android.support.constraint.ConstraintLayout>
+        </TableLayout>
+        <TableLayout
+            android:layout_width="match_parent"
+            android:collapseColumns="2"
+            android:layout_height="wrap_content">
+            <TableRow>
+                <LinearLayout
+                    android:id="@+id/linearLayout"
+                    android:layout_width="match_parent"
+                    android:layout_height="130dp"
+                    android:padding="16dp">
 
 
-                <LinearLayout
-                    android:layout_width="120dp"
-                    android:layout_height="match_parent">
-                    <Button
+                    <LinearLayout
                         android:layout_width="120dp"
-                        android:layout_height="96dp"
-                        android:onClick="@{viewModal.btnQeryIMEI}"
-                        android:text="查询IMEI:**"
-                        android:textSize="24sp" />
-                </LinearLayout>
-                <LinearLayout
-                    android:layout_width="wrap_content"
-                    android:layout_height="match_parent">
-                    <TextView
+                        android:layout_height="match_parent">
+                        <Button
+                            android:layout_width="120dp"
+                            android:layout_height="96dp"
+                            android:onClick="@{viewModal.btnClickReport}"
+                            android:text="数据上报1.0"
+                            android:textSize="24sp" />
+                    </LinearLayout>
+                    <LinearLayout
                         android:layout_width="wrap_content"
-                        android:layout_height="77dp"
-                        android:layout_marginStart="1dp"
-                        android:layout_marginTop="1dp"
-                        android:layout_marginEnd="2dp"
-                        android:text="@={viewModal.textIMEI}"
-                        android:textSize="30dp" />
-                </LinearLayout>
-
-            </LinearLayout>
-            <LinearLayout
-                android:id="@+id/linearLayout"
-                android:layout_width="match_parent"
-                android:layout_height="130dp"
-                android:padding="16dp">
-
+                        android:layout_height="match_parent">
+                        <TextView
+                            android:layout_width="wrap_content"
+                            android:layout_height="77dp"
+                            android:layout_marginStart="1dp"
+                            android:layout_marginTop="1dp"
+                            android:layout_marginEnd="2dp"
+                            android:text="@={viewModal.textReportData}"
+                            android:textSize="30dp" />
+                    </LinearLayout>
 
-                <LinearLayout
-                    android:layout_width="120dp"
-                    android:layout_height="match_parent">
-                <Button
-                    android:layout_width="120dp"
-                    android:layout_height="96dp"
-                    android:onClick="@{viewModal.btnClickReport}"
-                    android:text="数据上报1.0"
-                    android:textSize="24sp" />
-                </LinearLayout>
-                <LinearLayout
-                    android:layout_width="wrap_content"
-                    android:layout_height="match_parent">
-                <TextView
-                    android:layout_width="wrap_content"
-                    android:layout_height="77dp"
-                    android:layout_marginStart="1dp"
-                    android:layout_marginTop="1dp"
-                    android:layout_marginEnd="2dp"
-                    android:text="@={viewModal.textReportData}"
-                    android:textSize="30dp" />
                 </LinearLayout>
+            </TableRow>
+            <TableRow>
 
-            </LinearLayout>
-
-
-
-            <LinearLayout
-                android:layout_width="match_parent"
-                android:layout_height="120dp"
-                android:padding="16dp">
+            </TableRow>
+        </TableLayout>
+        <TableLayout
+            android:layout_width="match_parent"
+            android:shrinkColumns="3"
+            android:layout_height="wrap_content">
+            <TableRow>
                 <Button
                     android:layout_width="161dp"
                     android:layout_height="100dp"
@@ -113,156 +133,64 @@
                     android:text="关门"
                     android:textSize="24sp"
                     />
-            </LinearLayout>
-            <LinearLayout
-                android:layout_width="match_parent"
-                android:layout_height="130dp"
-                android:padding="16dp">
-                        <TextView
-                            android:layout_width="wrap_content"
-                            android:layout_height="wrap_content"
-                            android:text="开锁 3秒后 关锁"
-                            android:textSize="24sp"
-                            />
-                        <Button
-                            android:layout_width="150dp"
-                            android:layout_height="100dp"
-                            android:onClick="@{viewModal.btnClickOpenLock}"
-                            android:text="开锁"
-                            android:textSize="24sp"
-                             />
-            </LinearLayout>
-            <LinearLayout
-                android:layout_width="match_parent"
-                android:layout_height="130dp"
-                android:padding="16dp">
-                <LinearLayout
-                    android:layout_width="130dp"
-                    android:layout_height="100dp">
+
                 <Button
-                    android:layout_width="130dp"
+                    android:layout_width="150dp"
                     android:layout_height="100dp"
-                    android:onClick="@{viewModal.btnClickreadWeight}"
-                    android:text="称重"
+                    android:onClick="@{viewModal.btnClickOpenLock}"
+                    android:text="开锁"
                     android:textSize="24sp"
-                />
-                </LinearLayout>
-                <LinearLayout
-                    android:layout_width="wrap_content"
-                    android:layout_height="match_parent">
+                    />
                 <TextView
                     android:layout_width="wrap_content"
-                    android:layout_height="100dp"
-                    android:text="@={viewModal.textReadWeightData}"
-                    android:textSize="42sp"
+                    android:layout_height="wrap_content"
+                    android:text="开锁 3秒后 关锁"
+                    android:textSize="24sp"
                     />
-                </LinearLayout>
-            </LinearLayout>
-            <LinearLayout
-                android:layout_width="match_parent"
-                android:layout_height="130dp"
-                android:padding="16dp">
                 <Button
                     android:layout_width="150dp"
                     android:layout_height="100dp"
-                    android:onClick="@{viewModal.btnClicksetScale}"
-                    android:text="设置分度值"
+                    android:onClick="@{viewModal.btnClickRodRepeat}"
+                    android:text="连续伸缩杆"
                     android:textSize="24sp"
                     />
                 <Button
+                    android:id="@+id/button2"
                     android:layout_width="150dp"
                     android:layout_height="100dp"
-                    android:onClick="@{viewModal.btnClickclearWeight}"
-                    android:text="称重清零去皮"
+                    android:onClick="@{viewModal.btnClickLockRepeat}"
+                    android:text="连续开锁"
                     android:textSize="24sp"
                     />
-            </LinearLayout>
-            <LinearLayout
-                android:layout_width="match_parent"
-                android:layout_height="130dp"
-                android:padding="16dp"
-                >
                 <Button
-                    android:layout_width="150dp"
+                    android:layout_width="wrap_content"
                     android:layout_height="100dp"
-                    android:onClick="@{viewModal.btnClickzeroCalibration}"
-                    android:text="零度校准"
+                    android:onClick="@{viewModal.btnClickqueryCurrent}"
+                    android:text="电流过大查询"
                     android:textSize="24sp"
                     />
-
-                <Button
-                    android:id="@+id/button"
-                    android:layout_width="150dp"
+                <TextView
+                    android:layout_width="50dp"
                     android:layout_height="100dp"
-                    android:onClick="@{viewModal.btnClickweightCalibration}"
-                    android:text="砝码校准"
+                    android:text="@={viewModal.textqueryCurrentData}"
                     android:textSize="24sp"
                     />
-            </LinearLayout>
-            <LinearLayout
-                android:layout_width="match_parent"
-                android:layout_height="130dp"
-                android:padding="16dp">
-            <Button
-                android:layout_width="150dp"
-                android:layout_height="100dp"
-                android:onClick="@{viewModal.btnClickRodRepeat}"
-                android:text="连续伸缩杆"
-                android:textSize="24sp"
-                 />
                 <Button
-                    android:id="@+id/button2"
                     android:layout_width="150dp"
                     android:layout_height="100dp"
-                    android:onClick="@{viewModal.btnClickLockRepeat}"
-                    android:text="连续开锁"
+                    android:onClick="@{viewModal.btnClickclearCurrent}"
+                android:text="清除"
                     android:textSize="24sp"
                     />
-            </LinearLayout>
 
-            <LinearLayout
-                android:layout_width="match_parent"
-                android:layout_height="130dp"
-                android:padding="16dp">
-                <LinearLayout
-                    android:layout_width="wrap_content"
-                    android:layout_height="130dp">
-            <Button
-                android:layout_width="150dp"
-                android:layout_height="100dp"
-                android:onClick="@{viewModal.btnClickqueryCurrent}"
-                android:text="电流过大查询"
-                android:textSize="24sp"
-                />
-            </LinearLayout>
-                <LinearLayout
-                    android:layout_width="wrap_content"
-                    android:layout_height="130dp"
-                    >
-                <TextView
-                    android:layout_width="50dp"
-                    android:layout_height="100dp"
-                    android:text="@={viewModal.textqueryCurrentData}"
-                    android:textSize="24sp"
-                    />
-                </LinearLayout>
-                <LinearLayout
-                    android:layout_width="wrap_content"
-                    android:layout_height="130dp">
-            <Button
-                android:layout_width="150dp"
-                android:layout_height="100dp"
-                android:onClick="@{viewModal.btnClickclearCurrent}"
-                android:text="清除"
-                android:textSize="24sp"
-                 />
-                </LinearLayout>
-            </LinearLayout>
-            <LinearLayout
-                android:layout_width="match_parent"
-                android:layout_height="130dp"
-                android:padding="16dp"
-                >
+            </TableRow>
+        </TableLayout>
+
+        <TableLayout
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:shrinkColumns="4">
+            <TableRow>
                 <Button
                     android:layout_width="150dp"
                     android:layout_height="100dp"
@@ -277,12 +205,6 @@
                     android:text="开灯1234"
                     android:textSize="24sp"
                     />
-            </LinearLayout>
-            <LinearLayout
-                android:layout_width="match_parent"
-                android:layout_height="130dp"
-                android:padding="16dp"
-                >
                 <Button
                     android:layout_width="150dp"
                     android:layout_height="100dp"
@@ -297,12 +219,6 @@
                     android:text="获取属性"
                     android:textSize="24sp"
                     />
-            </LinearLayout>
-            <LinearLayout
-                android:layout_width="match_parent"
-                android:layout_height="130dp"
-                android:padding="16dp"
-                >
                 <Button
                     android:layout_width="150dp"
                     android:layout_height="100dp"
@@ -317,12 +233,6 @@
                     android:text="开灯2"
                     android:textSize="24sp"
                     />
-            </LinearLayout>
-            <LinearLayout
-                android:layout_width="match_parent"
-                android:layout_height="130dp"
-                android:padding="16dp"
-                >
                 <Button
                     android:layout_width="150dp"
                     android:layout_height="100dp"
@@ -337,43 +247,108 @@
                     android:text="开灯4"
                     android:textSize="24sp"
                     />
-            </LinearLayout>
-            <LinearLayout
-                android:layout_width="match_parent"
-                android:layout_height="130dp"
-                android:padding="16dp">
-
+            </TableRow>
+        </TableLayout>
+        <TableLayout
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:shrinkColumns="5">
+            <TableRow>
                 <Button
                     android:layout_width="150dp"
                     android:layout_height="100dp"
-                    android:onClick="@{viewModal.btnClickrestartApp}"
-                    android:text="重启"
+                    android:onClick="@{viewModal.btnClickSetPowerBigger}"
+                    android:text="设置更大的电流阈值"
                     android:textSize="24sp"
                     />
                 <Button
                     android:layout_width="150dp"
                     android:layout_height="100dp"
-                    android:onClick="@{viewModal.btnClickfinishApp}"
-                    android:text="关闭"
+                    android:onClick="@{viewModal.btnClickQueryPower}"
+                    android:text="查询电流值"
                     android:textSize="24sp"
                     />
-            </LinearLayout>
-            <LinearLayout
-                android:layout_width="match_parent"
-                android:layout_height="130dp"
-                android:padding="16dp">
-
+            </TableRow>
+        </TableLayout>
+        <TableLayout
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:shrinkColumns="6">
+            <TableRow>
                 <Button
                     android:layout_width="150dp"
                     android:layout_height="100dp"
-                    android:onClick="@{viewModal.btnClickrestartAndroid}"
-                    android:text="重启系统"
+                    android:onClick="@{viewModal.btnClicksetScale}"
+                    android:text="设置分度值"
                     android:textSize="24sp"
                     />
+                <TextView
+                    android:layout_width="wrap_content"
+                    android:layout_height="100dp"
+                    android:text="→"
+                    android:textSize="42sp"
+                    android:textAlignment="center"
+                    />
+                <Button
+                    android:layout_width="150dp"
+                    android:layout_height="100dp"
+                    android:onClick="@{viewModal.btnClickzeroCalibration}"
+                    android:text="零度校准"
+                    android:textSize="24sp"
+                    />
+                <TextView
+                    android:layout_width="500dp"
+                    android:layout_height="100dp"
+                    android:text="称盘无物且稳定,放10KG的砝码,等8秒稳定后,点击下一个按钮"
+                    android:textSize="30sp"
+                    />
+                <Button
+                    android:id="@+id/button"
+                    android:layout_width="150dp"
+                    android:layout_height="100dp"
+                    android:onClick="@{viewModal.btnClickweightCalibration}"
+                    android:text="砝码校准"
+                    android:textSize="24sp"
+                    />
+                <TextView
+                    android:layout_width="150dp"
+                    android:layout_height="100dp"
+                    android:text="取走砝码"
+                    android:textSize="30sp"
+                    />
+                <Button
+                    android:layout_width="150dp"
+                    android:layout_height="100dp"
+                    android:onClick="@{viewModal.btnClickclearWeight}"
+                    android:text="称重清零去皮"
+                    android:textSize="24sp"
+                    />
+            </TableRow>
+        </TableLayout>
+        <TableLayout
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content">
+            <TextView
+                android:layout_width="wrap_content"
+                android:layout_height="100dp"
+                android:text="@={viewModal.textReadWeightData}"
+                android:textSize="42sp"
+                android:textAlignment="center"
+                />
+        </TableLayout>
+        <TableLayout
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:shrinkColumns="7">
+            <Button
+                android:layout_width="130dp"
+                android:layout_height="100dp"
+                android:onClick="@{viewModal.btnClickreadWeight}"
+                android:text="称重"
+                android:textSize="24sp"
+                />
+        </TableLayout>
 
-            </LinearLayout>
-
-        </LinearLayout>
-    </ScrollView>
+    </LinearLayout>
 
 </layout>

+ 1 - 1
build.gradle

xqd
@@ -9,7 +9,7 @@ buildscript {
         jcenter()
     }
     dependencies {
-        classpath 'com.android.tools.build:gradle:3.3.2'
+        classpath 'com.android.tools.build:gradle:3.5.3'
         
         // NOTE: Do not place your application dependencies here; they belong
         // in the individual module build.gradle files

+ 2 - 2
config.gradle

xqd
@@ -7,8 +7,8 @@ ext {
             minSdkVersion    : 21,
             targetSdkVersion : 25,
 
-            versionCode      : 5,
-            versionName      : "1.5",
+            versionCode      : 8,
+            versionName      : "1.8",
     ]
     //version配置
     versions = [

+ 1 - 0
gradle.properties

xqd
@@ -11,5 +11,6 @@ org.gradle.jvmargs=-Xmx1536m
 # This option should only be used with decoupled projects. More details, visit
 # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
 # org.gradle.parallel=true
+android.useDeprecatedNdk=true
 
 

+ 2 - 2
gradle/wrapper/gradle-wrapper.properties

xqd
@@ -1,6 +1,6 @@
-#Mon Nov 18 10:56:28 CST 2019
+#Tue Jul 28 16:11:17 CST 2020
 distributionBase=GRADLE_USER_HOME
 distributionPath=wrapper/dists
 zipStoreBase=GRADLE_USER_HOME
 zipStorePath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.1-all.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip

この差分においてかなりの量のファイルが変更されているため、一部のファイルを表示していません