瀏覽代碼

优化,去掉了多余的日志打印,规范命名

DESKTOP-SADJPBG\47462 5 年之前
父節點
當前提交
5201ef1cd0

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

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;
 
 
@@ -76,23 +79,19 @@ public class AppApplication extends BaseApplication implements CustomActivityOnC
     public void onCreate() {
         super.onCreate();
         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,8 +115,7 @@ public class AppApplication extends BaseApplication implements CustomActivityOnC
          */
         Map<String, ValueWrapper> propertyValues = new HashMap<>();
         //心跳包 interval 单位秒
-        MqttConfigure.setKeepAliveInterval(150);
-//        MqttConnectOptionsc.setAutomaticReconnect(true);
+        MqttConfigure.setKeepAliveInterval(300);
 
         // 示例
         // propertyValues.put("LightSwitch", new ValueWrapper.BooleanValueWrapper(0));
@@ -154,8 +152,7 @@ public class AppApplication extends BaseApplication implements CustomActivityOnC
             public void onInitDone(Object data) {
                 // 初始化成功 data 作为预留参数
                 KLog.d("初始化成功,data:"+data);
-                MqttPublishRequest request = new MqttPublishRequest();
-
+                MqttConfigure.setKeepAliveInterval(60);
 
             }
         });

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

xqd xqd xqd
@@ -234,7 +234,7 @@ public class OtherDevice extends BaseDeviceEntity {
             e.printStackTrace();
         }
     }
-    public void selectPower(){
+    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};
@@ -258,7 +258,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);
@@ -299,7 +299,7 @@ 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);
                             int num=SPUtils.getInstance().getInt("infraredNum1",0)+1;
                             SPUtils.getInstance().put("infraredNum1",num);

+ 137 - 17
app/src/main/java/com/siwei/recyclebox/ui/main/MainActivity.java

xqd xqd xqd xqd xqd xqd
@@ -9,6 +9,7 @@ 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;
@@ -18,6 +19,9 @@ 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;
@@ -25,13 +29,49 @@ 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() {
@@ -39,28 +79,108 @@ public class MainActivity extends BaseActivity<ViewDataBinding,MainViewModel> {
         Intent service = new Intent(getApplication(), MyService.class);
         getApplication().startService(service);
         getApplication().bindService(new Intent(MainActivity.this,MyService.class),mConnection, Service.BIND_AUTO_CREATE);
-        Log.i("uuid","="+getMacAddress());
 
     }
 
+    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;
 
-    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);
+    }
+    @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);
+            }
         }
-        if (null != info) {
-            macAddress = info.getMacAddress();
+    }
+    /**
+     * 监听网络强度
+     *
+     * @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);
         }
-        return macAddress;
     }
 
+//    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() {
 
@@ -95,7 +215,7 @@ public class MainActivity extends BaseActivity<ViewDataBinding,MainViewModel> {
         if(!isIgnoringBatteryOptimizations()){
             requestIgnoreBatteryOptimizations();
         }
-//        viewModel.netWorkInfo();
+        viewModel.netWorkInfo();
 //        viewModel.openWeight();
 //        System.out.println("serialPortUtil.readControllerStatus:"+ SerialPortUtil.getInstance().readRelayControllerStatus());
     }
@@ -172,7 +292,7 @@ public class MainActivity extends BaseActivity<ViewDataBinding,MainViewModel> {
         viewModel.unRegisterIoTListener();
         getApplication().unbindService(mConnection);
         mService=null;
-//        viewModel.closePort();
+        viewModel.closePort();
 
 //        Log.e("MainActivity.","unregisterIoTListener!!!");
 //        Intent mStartActivity = new Intent(getApplication(),MainActivity.class);

文件差異過大導致無法顯示
+ 313 - 556
app/src/main/java/com/siwei/recyclebox/ui/main/MainViewModel.java


+ 1 - 1
app/src/main/res/layout/activity_main.xml

xqd
@@ -353,7 +353,7 @@
                 <Button
                     android:layout_width="150dp"
                     android:layout_height="100dp"
-                    android:onClick="@{viewModal.btnClickSelectPower}"
+                    android:onClick="@{viewModal.btnClickQueryPower}"
                     android:text="查询电流值"
                     android:textSize="24sp"
                     />

部分文件因文件數量過多而無法顯示