DESKTOP-SADJPBG\47462 5 년 전
부모
커밋
489a30a7dc

파일 크기가 너무 크기때문에 변경 상태를 표시하지 않습니다.
+ 969 - 0
100.log


+ 4 - 3
app/build.gradle

xqd
@@ -84,7 +84,8 @@ dependencies {
     implementation 'com.aliyun:aliyun-java-sdk-dysmsapi:1.1.0'
     implementation 'com.squareup.okhttp3:okhttp:3.10.0'
     implementation 'com.zhy:okhttputils:2.6.2'
-//    compile group: 'xerces', name: 'xercesImpl', version: '2.12.0'
-//    implementation files('src/main/libs//aliyun-java-sdk-core-4.1.0.jar')
-//    implementation files('src/main/libs/aliyun-java-sdk-dysmsapi-1.0.0.jar')
+    //    compile group: 'xerces', name: 'xercesImpl', version: '2.12.0'
+    //    implementation files('src/main/libs//aliyun-java-sdk-core-4.1.0.jar')
+    //    implementation files('src/main/libs/aliyun-java-sdk-dysmsapi-1.0.0.jar')
+    implementation files('libs/AMap.jar')
 }

BIN
app/libs/AMap.jar


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

xqd xqd xqd
@@ -4,6 +4,38 @@
     package="com.siwei.recyclebox"
 
     >
+    <!--用于进行网络定位-->
+    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
+    <!--用于访问GPS定位-->
+    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
+    <!--获取运营商信息,用于支持提供运营商信息相关的接口-->
+    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
+    <!--用于访问wifi网络信息,wifi信息会用于进行网络定位-->
+    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
+    <!--这个权限用于获取wifi的获取权限,wifi信息会用来进行网络定位-->
+    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
+    <!--用于访问网络,网络定位需要上网-->
+    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
+    <!--用于读取手机当前的状态-->
+    <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
+    <!--写入扩展存储,向扩展卡写入数据,用于写入缓存定位数据-->
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
+    <!--用于申请调用A-GPS模块-->
+    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"></uses-permission>
+    <!--用于申请获取蓝牙信息进行室内定位-->
+    <uses-permission android:name="android.permission.BLUETOOTH"></uses-permission>
+    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"></uses-permission>
+    <!-- 高德导航需要的权限 -->
+    <uses-permission android:name="android.permission.INTERNET" />
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
+    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
+    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
+    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
+    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
+    <uses-permission android:name="android.permission.WAKE_LOCK" />
+
 
     <uses-permission android:name="android.permission.INTERNET" />
     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
@@ -50,6 +82,11 @@
         android:supportsRtl="true"
         android:theme="@style/AppTheme">
 
+        <meta-data
+            android:name="com.amap.api.v2.apikey"
+            android:value="e0f65b84cb308106d63c5d07f40bd998" />
+        <service android:name="com.amap.api.location.APSService" />
+
         <provider
             android:name="android.support.v4.content.FileProvider"
             android:authorities="com.siwei.recyclebox.fileprovider"
@@ -91,7 +128,6 @@
                 <action android:name="android.intent.action.PACKAGE_REPLACED"/>
                 <data android:scheme="package"/>
             </intent-filter>
-
         </receiver>
 
     </application>

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

xqd xqd xqd xqd xqd xqd xqd xqd xqd xqd xqd xqd xqd
@@ -208,8 +208,11 @@ public class OtherDevice extends BaseDeviceEntity {
 
     public void setPower(){
         try {
-            byte[] setPower = new byte[]{(byte) 0xAA, (byte) 0xBB, 0x0A, 0x01, 0x66, 0x0A, 0x02, 0x20, (byte) 0xFF, (byte) 0xFF, (byte) 0xCC, (byte) 0xDD};
-            port.write(setPower, 2000);
+            byte[] setPower = new byte[]{(byte) 0xAA, (byte) 0xBB, 0x0A, 0x01, 0x66, 0x0A, 0x02, 0x60, (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();
         }
@@ -237,12 +240,12 @@ 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);
+                    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("push response:"+ByteUtil.bytesToString(response));
-//                    System.out.println("pushRead response:"+ByteUtil.bytesToString(responseRead));
+                    System.out.println("pushRead response:"+ByteUtil.bytesToString(responseRead));
                     SPUtils.getInstance().put("infraredNum1",0);
                     SPUtils.getInstance().getInt("infraredNum1",0);
                     long curr=System.currentTimeMillis();
@@ -396,6 +399,7 @@ public class OtherDevice extends BaseDeviceEntity {
                 return disInt;
             }else {
                 SPUtils.getInstance().put("RunningState",5);
+                MainViewModel.SendSmsResponse("温度超声波失灵");
                 return 0;
             }
         }catch ( Exception e ){
@@ -411,7 +415,6 @@ public class OtherDevice extends BaseDeviceEntity {
      */
     public Integer geTemperature(){//获取温度
         try{
-//            byte[] bytes=new byte[]{(byte) 0xAA, (byte) 0xBB,0x0D,0x01,0x55, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xCC, (byte) 0xDD};
             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];
@@ -432,6 +435,7 @@ public class OtherDevice extends BaseDeviceEntity {
                 return temInt;
             }else {
                 SPUtils.getInstance().put("RunningState",5);
+                MainViewModel.SendSmsResponse("温度超声波失灵");
                 return 0;
             }
         }catch ( Exception e ){
@@ -449,6 +453,9 @@ public class OtherDevice extends BaseDeviceEntity {
         try{
             byte[] bytes=new byte[]{(byte) 0xAA, (byte) 0xBB, 0x0D, 0x01, 0x66, 0x01, 0x01, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xCC, (byte) 0xDD};
             port.write(bytes,200);
+            byte[] response=new byte[12];
+            port.read(response,200);
+            Log.i(TAG,"openLight1"+ByteUtil.bytesToString(response));
         }catch (Exception e){
             e.printStackTrace();
             Log.i(TAG,"开灯1失败");
@@ -458,6 +465,9 @@ public class OtherDevice extends BaseDeviceEntity {
         try{
             byte[] bytes=new byte[]{(byte) 0xAA, (byte) 0xBB, 0x0D, 0x01, 0x66, 0x01, 0x00, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xCC, (byte) 0xDD};
             port.write(bytes,200);
+            byte[] response=new byte[12];
+            port.read(response,200);
+            Log.i(TAG,"closeLight1"+ByteUtil.bytesToString(response));
         }catch (Exception e){
             e.printStackTrace();
             Log.i(TAG,"关灯1失败");
@@ -467,6 +477,9 @@ public class OtherDevice extends BaseDeviceEntity {
         try{
             byte[] bytes=new byte[]{(byte) 0xAA, (byte) 0xBB, 0x0D, 0x01, 0x66, 0x02, 0x01, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xCC, (byte) 0xDD};
             port.write(bytes,200);
+            byte[] response=new byte[12];
+            port.read(response,200);
+            Log.i(TAG,"openLight2"+ByteUtil.bytesToString(response));
         }catch (Exception e){
             e.printStackTrace();
             Log.i(TAG,"开灯2失败");
@@ -476,6 +489,9 @@ public class OtherDevice extends BaseDeviceEntity {
         try{
             byte[] bytes=new byte[]{(byte) 0xAA, (byte) 0xBB, 0x0D, 0x01, 0x66, 0x02, 0x00, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xCC, (byte) 0xDD};
             port.write(bytes,200);
+            byte[] response=new byte[12];
+            port.read(response,200);
+            Log.i(TAG,"closeLight2"+ByteUtil.bytesToString(response));
         }catch (Exception e){
             e.printStackTrace();
             Log.i(TAG,"关灯2失败");
@@ -485,6 +501,9 @@ public class OtherDevice extends BaseDeviceEntity {
         try{
             byte[] bytes=new byte[]{(byte) 0xAA, (byte) 0xBB, 0x0D, 0x01, 0x66, 0x03, 0x01, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xCC, (byte) 0xDD};
             port.write(bytes,200);
+            byte[] response=new byte[12];
+            port.read(response,200);
+            Log.i(TAG,"openLight3"+ByteUtil.bytesToString(response));
         }catch (Exception e){
             e.printStackTrace();
             Log.i(TAG,"开灯3失败");
@@ -494,6 +513,9 @@ public class OtherDevice extends BaseDeviceEntity {
         try{
             byte[] bytes=new byte[]{(byte) 0xAA, (byte) 0xBB, 0x0D, 0x01, 0x66, 0x03, 0x00, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xCC, (byte) 0xDD};
             port.write(bytes,200);
+            byte[] response=new byte[12];
+            port.read(response,200);
+            Log.i(TAG,"closeLight3"+ByteUtil.bytesToString(response));
         }catch (Exception e){
             e.printStackTrace();
             Log.i(TAG,"关灯3失败");
@@ -503,6 +525,9 @@ public class OtherDevice extends BaseDeviceEntity {
         try{
             byte[] bytes=new byte[]{(byte) 0xAA, (byte) 0xBB, 0x0D, 0x01, 0x66, 0x04, 0x01, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xCC, (byte) 0xDD};
             port.write(bytes,200);
+            byte[] response=new byte[12];
+            port.read(response,200);
+            Log.i(TAG,"openLight4"+ByteUtil.bytesToString(response));
         }catch (Exception e){
             e.printStackTrace();
             Log.i(TAG,"开灯4失败");
@@ -512,6 +537,9 @@ public class OtherDevice extends BaseDeviceEntity {
         try{
             byte[] bytes=new byte[]{(byte) 0xAA, (byte) 0xBB, 0x0D, 0x01, 0x66, 0x04, 0x00, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xCC, (byte) 0xDD};
             port.write(bytes,200);
+            byte[] response=new byte[12];
+            port.read(response,200);
+            Log.i(TAG,"closeLight4"+ByteUtil.bytesToString(response));
         }catch (Exception e){
             e.printStackTrace();
             Log.i(TAG,"关灯4失败");

+ 135 - 0
app/src/main/java/com/siwei/recyclebox/entity/MapLocationInfo.java

xqd
@@ -0,0 +1,135 @@
+package com.siwei.recyclebox.entity;
+
+import android.text.TextUtils;
+
+import java.io.Serializable;
+
+/**
+ * @author hanli
+ */
+public class MapLocationInfo implements Serializable {
+
+    /**
+     *
+     */
+    private static final long serialVersionUID = 1L;
+    /** 地址 */
+    private String address;
+    /** 省份 */
+    private String province;
+    /** 城市 */
+    private String city;
+    /** 区域 */
+    private String district;
+    /** 街道 */
+    private String street;
+    /** 纬度 */
+    private double latitude;
+    /** 精度 */
+    private double longitude;
+//    /** 附近点 */
+//    private String aoi;
+//    /** 兴趣点 */
+//    private String poi;
+
+    public MapLocationInfo() {
+    }
+
+    public MapLocationInfo(String address, String province, String city, String district, String street, double latitude, double longitude, String aoi, String poi) {
+        super();
+        this.address = address;
+        this.province = province;
+        this.city = city;
+        this.street = street;
+        this.district = district;
+        this.latitude = latitude;
+        this.longitude = longitude;
+//        this.aoi = aoi;
+//        this.poi = poi;
+    }
+
+//    public String getAoi() {
+//        return TextUtils.isEmpty(aoi) ? "" : aoi;
+//    }
+//
+//    public void setAoi(String aoi) {
+//        this.aoi = aoi;
+//    }
+//
+//    public String getPoi() {
+//        return TextUtils.isEmpty(poi) ? "" : poi;
+//    }
+//
+//    public void setPoi(String poi) {
+//        this.poi = poi;
+//    }
+
+    public String getStreet() {
+        return TextUtils.isEmpty(street) ? "" : street;
+    }
+
+    public void setStreet(String street) {
+        this.street = street;
+    }
+
+    public String getAddress() {
+        return address;
+    }
+
+    public void setAddress(String address) {
+        this.address = address;
+    }
+
+    public String getProvince() {
+        return TextUtils.isEmpty(province) ? "" : province;
+    }
+
+    public void setProvince(String province) {
+        this.province = province;
+    }
+
+    public String getCity() {
+        return TextUtils.isEmpty(city) ? "" : city;
+    }
+
+    public void setCity(String city) {
+        this.city = city;
+    }
+
+    public String getDistrict() {
+        return TextUtils.isEmpty(district) ? "" : district;
+    }
+
+    public void setDistrict(String district) {
+        this.district = district;
+    }
+
+    public double getLatitude() {
+        return latitude;
+    }
+
+    public void setLatitude(double latitude) {
+        this.latitude = latitude;
+    }
+
+    public double getLongitude() {
+        return longitude;
+    }
+
+    public void setLongitude(double longitude) {
+        this.longitude = longitude;
+    }
+
+    @Override
+    public String toString() {
+        return "MapLocationInfo{" +
+                "address='" + address + '\'' +
+                ", province='" + province + '\'' +
+                ", city='" + city + '\'' +
+                ", district='" + district + '\'' +
+                ", street='" + street + '\'' +
+                ", latitude=" + latitude +
+                ", longitude=" + longitude +
+                '}';
+    }
+}

+ 0 - 3
app/src/main/java/com/siwei/recyclebox/receiver/BCRUpgradeApk.java

xqd
@@ -14,13 +14,10 @@ public class BCRUpgradeApk extends BroadcastReceiver {
     public void onReceive(Context context, Intent intent) {
         if (intent.getAction().equals("android.intent.action.PACKAGE_REPLACED")){
 //            Toast.makeText(context,"升级了一个安装包",Toast.LENGTH_SHORT).show();
-
             Log.e(TAG,"BroadcastReceiver//////////////////:"+intent);
             Intent i = new Intent(context,MainActivity.class);
             i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
             context.startActivity(i);
-
         }
-
     }
 }

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

xqd xqd xqd
@@ -1,30 +1,17 @@
 package com.siwei.recyclebox.ui.main;
 
-import android.Manifest;
-import android.app.AlarmManager;
-import android.app.PendingIntent;
-import android.arch.lifecycle.Observer;
-import android.content.Context;
 import android.content.Intent;
 import android.databinding.ViewDataBinding;
 import android.os.Bundle;
-import android.support.annotation.Nullable;
 import android.util.Log;
-import android.view.View;
 
 import com.siwei.recyclebox.BR;
 import com.siwei.recyclebox.R;
-import com.siwei.recyclebox.databinding.ActivityMainBinding;
-import com.siwei.recyclebox.deviceUtils.SerialPortUtil;
 import com.siwei.recyclebox.service.MyService;
-import com.tbruyelle.rxpermissions2.RxPermissions;
 
-import java.io.IOException;
 
-import io.reactivex.disposables.Disposable;
 import me.goldze.mvvmhabit.base.BaseActivity;
-import me.goldze.mvvmhabit.utils.SPUtils;
-import me.goldze.mvvmhabit.utils.ToastUtils;
+
 
 public class MainActivity extends BaseActivity<ViewDataBinding,MainViewModel> {
 
@@ -34,8 +21,8 @@ public class MainActivity extends BaseActivity<ViewDataBinding,MainViewModel> {
     @Override
     public void initParam() {
         super.initParam();
-//        Intent service = new Intent(getApplication(), MyService.class);
-//        getApplication().startService(service);
+        Intent service = new Intent(getApplication(), MyService.class);
+        getApplication().startService(service);
     }
 
     //页面数据初始化方法。
@@ -46,7 +33,7 @@ public class MainActivity extends BaseActivity<ViewDataBinding,MainViewModel> {
         viewModel.registerAliIoTListener();
 //        viewModel.repeatTask();
         Log.i("repeatTask","*****************************************");
-//        viewModel.startBLEServer();
+        viewModel.startBLEServer();
 //        viewModel.netWorkInfo();
 //        viewModel.openWeight();
 //        System.out.println("serialPortUtil.readControllerStatus:"+ SerialPortUtil.getInstance().readRelayControllerStatus());

+ 251 - 147
app/src/main/java/com/siwei/recyclebox/ui/main/MainViewModel.java

xqd xqd xqd xqd xqd xqd xqd xqd xqd xqd xqd xqd xqd xqd xqd xqd xqd
@@ -4,7 +4,6 @@ import android.Manifest;
 import android.app.ActivityManager;
 import android.app.AlarmManager;
 import android.app.Application;
-
 import android.app.PendingIntent;
 import android.bluetooth.BluetoothAdapter;
 import android.bluetooth.BluetoothDevice;
@@ -35,6 +34,7 @@ import android.os.BatteryManager;
 import android.os.Build;
 import android.os.Handler;
 import android.os.ParcelUuid;
+import android.provider.Settings;
 import android.support.annotation.NonNull;
 import android.support.annotation.RequiresApi;
 import android.support.v4.app.ActivityCompat;
@@ -100,7 +100,10 @@ import top.maybesix.xhlibrary.serialport.ComPortData;
 import top.maybesix.xhlibrary.serialport.SerialPortHelper;
 import top.maybesix.xhlibrary.util.HexStringUtils;
 
+import com.siwei.recyclebox.entity.MapLocationInfo;
+import com.siwei.recyclebox.service.MyService;
 import com.siwei.recyclebox.utils.DemoOne;
+import com.siwei.recyclebox.utils.LocationUtils;
 import com.siwei.recyclebox.utils.SilentInstall;
 import com.siwei.recyclebox.utils.unZipFileDemo;
 import com.zhy.http.okhttp.OkHttpUtils;
@@ -116,11 +119,37 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
     private TimerTask task1;
     private TimerTask task2;
     private TimerTask task3;
+    private LocationUtils mLocationUtils;
+    /** 定位信息 */
+    private MapLocationInfo mMapLocationInfo;
     @RequiresApi(api = Build.VERSION_CODES.O)
     public void onCreate(){
         super.onCreate();
-//        Intent service = new Intent(getApplication(), MyService.class);
-//        getApplication().startService(service);//打开服务,把程序写在服务里不容易被系统kill
+        Intent service = new Intent(getApplication(), MyService.class);
+        getApplication().startService(service);//打开服务,把程序写在服务里不容易被系统kill
+        mLocationUtils = LocationUtils.getInstance();
+        Log.i(TAG,"定位--------------------");
+        mLocationUtils.startLocationInfo();
+        mLocationUtils.onCreate(new LocationUtils.LocationListener() {
+            @Override
+            public void locationSuccess(MapLocationInfo mapLocationInfo, String message) {
+                mMapLocationInfo = mapLocationInfo;
+                Log.i("定位: ","" + message);
+                Log.i(TAG,"定位ok");
+                Log.i(TAG,mMapLocationInfo.toString());
+                Log.i(TAG,"纬度"+mMapLocationInfo.getLatitude()+"经度"+mMapLocationInfo.getLongitude());
+            }
+            @Override
+            public void locationFail(String message) {
+                Log.i("定位: ","" + message);
+            }
+        });
+        mHandler.postDelayed(new Runnable() {
+            @Override
+            public void run() {
+                mLocationUtils.stopLocationClient();
+            }
+        },5000);
 
         MainViewModel.context = getApplication();
         SPUtils.getInstance().put("RunningState",0);//设备运行状态
@@ -143,6 +172,9 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
     public ObservableField<String> textIMEI = new ObservableField<>();//imei显示
     public ObservableField<String> textqueryCurrentData = new ObservableField<>();//电流过大查询显示
 
+//    public void startLocation(){
+//        mLocationUtils.startLocationInfo();
+//    }
     /*
     * 按钮模拟指令
     * */
@@ -244,36 +276,50 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
                 SerialPortUtil.getInstance().getOtherDevice().closeLight3();
             }
             a++;
+//            publishRepeat();
         }
     };
     public View.OnClickListener btnClickOpenLight2 = new View.OnClickListener() {
         //打开关闭灯2按钮
         @Override
         public void onClick(View view) {
-//            if(a%2==0){
-//                SerialPortUtil.getInstance().getOtherDevice().openLight2();
-//            }
-//            else {
-//                SerialPortUtil.getInstance().getOtherDevice().closeLight2();
-//            }
-//            a++;
-            int hour=readTime();
-            Log.i("当前时间hour是:",hour+"dian");
+            if(a%2==0){
+                SerialPortUtil.getInstance().getOtherDevice().openLight2();
+            }
+            else {
+                SerialPortUtil.getInstance().getOtherDevice().closeLight2();
+            }
+            a++;
         }
     };
     public View.OnClickListener btnClickOpenLight1 = new View.OnClickListener() {
         //打开关闭灯1按钮
         @Override
         public void onClick(View view) {
-           /* if(a%2==0){
+            if(a%2==0){
                 SerialPortUtil.getInstance().getOtherDevice().openLight1();
             }
             else {
                 SerialPortUtil.getInstance().getOtherDevice().closeLight1();
             }
-            a++;*/
-//            reportDeviceEvent("haoge");
-            SendSmsResponse("(测试123)");
+            a++;
+        }
+    };
+    public View.OnClickListener btnClickSendMsg = new View.OnClickListener() {
+        //发送短信 事件测试
+        @Override
+        public void onClick(View view) {
+            SendSmsResponse("(测试12355656)");
+        }
+    };
+    public View.OnClickListener btnClickGetDeviceValue = new View.OnClickListener() {
+        //获取属性
+        @Override
+        public void onClick(View view) {
+            int hour=readTime();
+            Log.i("当前时间hour是:",hour+"dian");
+//            getDeviceProperty("1");
+            Log.i(TAG,"纬度"+mMapLocationInfo.getLatitude()+"经度"+mMapLocationInfo.getLongitude());
         }
     };
     public View.OnClickListener btnClickreadWeight = new View.OnClickListener() {
@@ -330,8 +376,20 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
             System.out.println("btnClickrestartApp");
             restartApp();//重启方法
         }
-        private Object getSystemService(String name) {
-            return getApplication().getSystemService(name);
+    };
+    public View.OnClickListener btnClickrestartAndroid = new View.OnClickListener() {
+        //重启app
+        @Override
+        public void onClick(View view) {
+            restartAndroid();//重启系统
+        }
+    };
+    public View.OnClickListener btnClickfinishApp = new View.OnClickListener() {
+        //关闭app
+        @Override
+        public void onClick(View view) {
+            System.out.println("btnClickfinishApp");
+            System.exit(0);
         }
     };
     public View.OnClickListener btnClickReport = new View.OnClickListener() {
@@ -715,7 +773,13 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
             if (topic.endsWith("thing/event/property/post_reply")){ //推送设备属性的回包。
             }
             if(topic.endsWith("thing/service/restartApp")){
-                restartApp();
+                restartApp();//重启app
+            }
+            if(topic.endsWith("thing/service/finishApp")){
+                System.exit(0);//关闭app
+            }
+            if(topic.endsWith("thing/service/restartAndroidSystem")){
+                restartAndroid();//重启系统
             }
             if(topic.endsWith("thing/service/RemoteOpen")){//   云端开门的请求。
 //                SerialPortUtil.getInstance().getPushRodDevice().pushRod();
@@ -1025,84 +1089,96 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
      * 上报状态
      */
     public void reportProperty() {
-        Log.i(TAG,"上报数据");
-        try{
-            Integer weight = 0;
-            Log.i("num=1","读一次称重");
-            weight = SerialPortUtil.getInstance().getWeightDevice().readWeight();//读称重
-            if(weight==1){
-                weight = SerialPortUtil.getInstance().getWeightDevice().readWeight();//读称重
-            }
+        Thread thread=new Thread(new Runnable() {
+            @Override
+            public void run() {
+                //        publishRepeat();
+                Log.i(TAG,"上报数据");
+                try{
+                    double longitude=107.31;
+                    double latitude=23.16;
+                    if(mMapLocationInfo!=null){
+                        longitude=mMapLocationInfo.getLongitude();
+                        latitude=mMapLocationInfo.getLatitude();
+                        Log.i(TAG,mMapLocationInfo.toString()+"--地址:"+mMapLocationInfo.getAddress());
+
+                    }
+                    Integer weight = 0;
+                    Log.i("num=1","读一次称重");
+                    weight = SerialPortUtil.getInstance().getWeightDevice().readWeight();//读称重
+                    if(weight==1){
+                        weight = SerialPortUtil.getInstance().getWeightDevice().readWeight();//读称重
+                    }
 //            weight=SerialPortUtil.getInstance().getOtherDevice().readWeight();//称重
-            Integer capacity=0;
-            capacity=SerialPortUtil.getInstance().getOtherDevice().getDistance();//超声波距离
-            if(capacity==0){
-                capacity=SerialPortUtil.getInstance().getOtherDevice().getDistance();//超声波距离
-            }
-            Integer magDoorSwitch=0;
-            magDoorSwitch=SerialPortUtil.getInstance().getOtherDevice().queryMagDoor();//门磁
-            Integer currentTemperature=0;
-            currentTemperature=SerialPortUtil.getInstance().getOtherDevice().geTemperature();//温度
-            if(currentTemperature==0){
-                currentTemperature=SerialPortUtil.getInstance().getOtherDevice().geTemperature();//温度
-            }
-            Log.i(TAG,"----------------------------------------");
+                    Integer capacity=0;
+                    capacity=SerialPortUtil.getInstance().getOtherDevice().getDistance();//超声波距离
+                    if(capacity==0){
+                        capacity=SerialPortUtil.getInstance().getOtherDevice().getDistance();//超声波距离
+                    }
+                    Integer magDoorSwitch=0;
+                    magDoorSwitch=SerialPortUtil.getInstance().getOtherDevice().queryMagDoor();//门磁
+                    Integer currentTemperature=0;
+                    currentTemperature=SerialPortUtil.getInstance().getOtherDevice().geTemperature();//温度
+                    if(currentTemperature==0){
+                        currentTemperature=SerialPortUtil.getInstance().getOtherDevice().geTemperature();//温度
+                    }
+                    Log.i(TAG,"----------------------------------------");
 
-            Map<String, ValueWrapper> locationMap = new HashMap<>();
-            Map<String, ValueWrapper> reportData = new HashMap<>();
+                    Map<String, ValueWrapper> locationMap = new HashMap<>();
+                    Map<String, ValueWrapper> reportData = new HashMap<>();
 //            SPUtils.getInstance().put("RodNumber","4721");
-            String rodNumberStr= SPUtils.getInstance().getString("RodNumber");
-            if(rodNumberStr.equals("")){
-                rodNumberStr="0";
-            }
-            int rodNumberInt=Integer.parseInt(rodNumberStr);
-            String rodSwitchStr=SPUtils.getInstance().getString("RodSwitch");
-            if(rodSwitchStr.equals("")){
-                rodSwitchStr="0";
-            }
-            int rodSwitchInt=Integer.parseInt(rodSwitchStr);
+                    String rodNumberStr= SPUtils.getInstance().getString("RodNumber");
+                    if(rodNumberStr.equals("")){
+                        rodNumberStr="0";
+                    }
+                    int rodNumberInt=Integer.parseInt(rodNumberStr);
+                    String rodSwitchStr=SPUtils.getInstance().getString("RodSwitch");
+                    if(rodSwitchStr.equals("")){
+                        rodSwitchStr="0";
+                    }
+                    int rodSwitchInt=Integer.parseInt(rodSwitchStr);
 //            SPUtils.getInstance().put("LockNumber","7562");
-            String lockNumberStr=SPUtils.getInstance().getString("LockNumber");
-            if(lockNumberStr.equals("")){
-                lockNumberStr="0";
-            }
-            int lockNumberInt=Integer.parseInt(lockNumberStr);
+                    String lockNumberStr=SPUtils.getInstance().getString("LockNumber");
+                    if(lockNumberStr.equals("")){
+                        lockNumberStr="0";
+                    }
+                    int lockNumberInt=Integer.parseInt(lockNumberStr);
 
-            int runningStateInt=SPUtils.getInstance().getInt("RunningState");
-            reportData.put("RodOpenNum",new ValueWrapper.IntValueWrapper(rodNumberInt));
-            reportData.put("LockOpenNum",new ValueWrapper.IntValueWrapper(lockNumberInt));
+                    int runningStateInt=SPUtils.getInstance().getInt("RunningState");
+                    reportData.put("RodOpenNum",new ValueWrapper.IntValueWrapper(rodNumberInt));
+                    reportData.put("LockOpenNum",new ValueWrapper.IntValueWrapper(lockNumberInt));
 
-            reportData.put("Weight", new ValueWrapper.IntValueWrapper(weight));    //重量  单位 --- 克
-            reportData.put("CurrentTemperature", new ValueWrapper.IntValueWrapper(currentTemperature));//温度,范围正负 ,精确到小数点后2位
-            reportData.put("RestCapacity", new ValueWrapper.IntValueWrapper(capacity));  //距离值,单位mm
-            reportData.put("MagDoorSwitch", new ValueWrapper.BooleanValueWrapper(magDoorSwitch));//门磁 0-关闭状态  1-开门状态
+                    reportData.put("Weight", new ValueWrapper.IntValueWrapper(weight));    //重量  单位 --- 克
+                    reportData.put("CurrentTemperature", new ValueWrapper.IntValueWrapper(currentTemperature));//温度,范围正负 ,精确到小数点后2位
+                    reportData.put("RestCapacity", new ValueWrapper.IntValueWrapper(capacity));  //距离值,单位mm
+                    reportData.put("MagDoorSwitch", new ValueWrapper.BooleanValueWrapper(magDoorSwitch));//门磁 0-关闭状态  1-开门状态
 
-            reportData.put("LockSwitch", new ValueWrapper.BooleanValueWrapper(lockSwitch));   //锁开关状态:0-关锁  1-解锁  解锁后3s就关锁
-            reportData.put("RodSwitch", new ValueWrapper.BooleanValueWrapper(rodSwitchInt));   //推杆状态:0-关闭状态  1-打开  开门
+                    reportData.put("LockSwitch", new ValueWrapper.BooleanValueWrapper(lockSwitch));   //锁开关状态:0-关锁  1-解锁  解锁后3s就关锁
+                    reportData.put("RodSwitch", new ValueWrapper.BooleanValueWrapper(rodSwitchInt));   //推杆状态:0-关闭状态  1-打开  开门
 
-            reportData.put("RunningState", new ValueWrapper.BooleanValueWrapper(runningStateInt)); // 0正常
+                    reportData.put("RunningState", new ValueWrapper.BooleanValueWrapper(runningStateInt)); // 0正常
 //            1设备故障 未识别到称重设备 报警  未识别到杆、门磁、锁、温度、红外、超声波设备 报警
 //            2温度过高 报警
 //            3收运门意外打开报警
 //            4称重失灵报警 错误一次就再读一次  超过两次读取错误就报警
 //            5温度和超声波失灵警告 失灵显示的000000000
 
-            System.out.println(IMEI+"DeviceId");
-            reportData.put("IMEI", new ValueWrapper.StringValueWrapper(IMEI));
-            locationMap.put("longitude", new ValueWrapper.DoubleValueWrapper(107.31));
-            locationMap.put("latitude", new ValueWrapper.DoubleValueWrapper(23.16));
-            locationMap.put("altitude", new ValueWrapper.DoubleValueWrapper(523.1));
-            reportData.put("GeoLocation", new ValueWrapper.StructValueWrapper(locationMap)); //
-
-            int queryCurrent=SPUtils.getInstance().getInt("queryCurrent");
-            Log.i(TAG, "称重" + weight.toString() + "距离" + capacity.toString() + "温度" + currentTemperature);
-            textReportData.set("称重 " + weight.toString() + ";距离 " + capacity.toString() + "mm;温度 " +
-                    currentTemperature+"度;门磁 "+magDoorSwitch+";杆状态 "+rodSwitchInt+";锁状态 "+lockSwitch+";杆开门次数 "+rodNumberInt+";开锁次数 "+lockNumberInt+";被夹次数"+queryCurrent
-            );
-
-            String  text = "称重 " + weight.toString() + ";距离 " + capacity.toString() + "mm;温度 " + currentTemperature+"度;门磁 "+magDoorSwitch+";杆状态 "+
-                    rodSwitchInt+";锁状态 "+lockSwitch+";杆开门次数 "+rodNumberInt+";开锁次数 "+lockNumberInt+";被夹次数"+queryCurrent+"------------------------------";
-            Log.i(TAG, text + "=textReportData---------------------");
+                    System.out.println(IMEI+"DeviceId");
+                    reportData.put("IMEI", new ValueWrapper.StringValueWrapper(IMEI));
+                    locationMap.put("longitude", new ValueWrapper.DoubleValueWrapper(longitude));
+                    locationMap.put("latitude", new ValueWrapper.DoubleValueWrapper(latitude));
+                    locationMap.put("altitude", new ValueWrapper.DoubleValueWrapper(523.1));
+                    reportData.put("GeoLocation", new ValueWrapper.StructValueWrapper(locationMap)); //
+
+                    int queryCurrent=SPUtils.getInstance().getInt("queryCurrent");
+                    Log.i(TAG, "称重" + weight.toString() + "距离" + capacity.toString() + "温度" + currentTemperature);
+                    textReportData.set("称重 " + weight.toString() + ";距离 " + capacity.toString() + "mm;温度 " +
+                            currentTemperature+"度;门磁 "+magDoorSwitch+";杆状态 "+rodSwitchInt+";锁状态 "+lockSwitch+";杆开门次数 "+rodNumberInt+";开锁次数 "+lockNumberInt+";被夹次数"+queryCurrent+";运行状态"+runningStateInt
+                    );
+
+                    String  text = "称重 " + weight.toString() + ";距离 " + capacity.toString() + "mm;温度 " + currentTemperature+"度;门磁 "+magDoorSwitch+";杆状态 "+
+                            rodSwitchInt+";锁状态 "+lockSwitch+";杆开门次数 "+rodNumberInt+";开锁次数 "+lockNumberInt+";被夹次数"+queryCurrent+"------------------------------";
+                    Log.i(TAG, text + "=textReportData---------------------");
                     mHandler.postDelayed(new Runnable() {
                         @Override
                         public void run() {
@@ -1123,6 +1199,11 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
                 } catch (Exception e) {
                     e.printStackTrace();
                 }
+
+            }
+        });
+           thread.start();
+
     }
    /*
    * 上报给蓝牙的数据格式
@@ -1255,35 +1336,50 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
         return reportData.toString();
     }
     //设备事件上报
-    public static void reportDeviceEvent(String identifier){
-        HashMap<String, ValueWrapper> hashMap = new HashMap<>();
+    public static void reportDeviceEvent(String identifier, String event, int num){
+       /* HashMap<String, ValueWrapper> hashMap = new HashMap<>();
         // TODO 用户根据实际情况设置
         // hashMap.put("ErrorCode", new ValueWrapper.IntValueWrapper(0));
-        hashMap.put("ErrorCode",new ValueWrapper.IntValueWrapper(3));
-//        hashMap.put("event",identifier);
+        if(num==1){
+            hashMap.put("warnEvent",new ValueWrapper.StringValueWrapper(event));
+        }else if(num==2){
+            hashMap.put("errorEvent",new ValueWrapper.StringValueWrapper(event));
+        }
         OutputParams params = new OutputParams(hashMap);
         Log.i("设备故障",identifier+"====="+params);
-//        int networkInfo=netWorkInfo();
 
-//        if(netWorkInfo!=0){
-//
-//        }
-//        LinkKit.getInstance().getDeviceThing().thingEventPost(identifier, params, new IPublishResourceListener() {
-//            @Override
-//            public void onSuccess(String resId, Object o) { // 事件上报成功
-//                Log.i("事件上报","上报成功");
-//            }
-//            @Override
-//            public void onError(String resId, AError aError) { // 事件上报失败
-//                Log.i("事件上报","上报失败");
-//            }
-//        });
+        LinkKit.getInstance().getDeviceThing().thingEventPost(identifier, params, new IPublishResourceListener() {
+            @Override
+            public void onSuccess(String resId, Object o) { // 事件上报成功
+                Log.i("事件上报","上报成功");
+            }
+            @Override
+            public void onError(String resId, AError aError) { // 事件上报失败
+                Log.i("事件上报","上报失败");
+            }
+        });*/
     }
     private void getDeviceProperty(String identifier){
         // 根据 identifier 获取当前物模型中该属性的值
-        LinkKit.getInstance().getDeviceThing().getPropertyValue(identifier);
+
+        Log.i("获取属性","-----------------------");
+        Log.i("获取属性",""+LinkKit.getInstance().getDeviceThing().getPropertyValue("Weight"));
+        Log.i("获取属性",""+LinkKit.getInstance().getDeviceThing());
+        Log.i("获取属性",""+LinkKit.getInstance().getDeviceThing().toString());
+        Log.i("获取属性",""+LinkKit.getInstance().getDeviceThing().getPropertyValue("Weight").getValue());
+        ValueWrapper.IntValueWrapper weight= (ValueWrapper.IntValueWrapper) LinkKit.getInstance().getDeviceThing().getPropertyValue("Weight");
+        Log.i("获取属性",""+weight.getValue());
         // 获取所有属性
-        LinkKit.getInstance().getDeviceThing().getProperties();
+//        LinkKit.getInstance().getDeviceThing().getProperties();
+        for(int i=0;i<LinkKit.getInstance().getDeviceThing().getProperties().size();i++){
+            Log.i("全部属性---------",""+LinkKit.getInstance().getDeviceThing().getProperties().get(i).getName());
+            Log.i("全部属性---------",""+LinkKit.getInstance().getDeviceThing().getProperties().get(i).getAccessMode());
+            Log.i("全部属性---------",""+LinkKit.getInstance().getDeviceThing().getProperties().get(i).getDesc());
+            Log.i("全部属性---------",""+LinkKit.getInstance().getDeviceThing().getProperties().get(i).getIdentifier());
+            Log.i("全部属性---------",""+LinkKit.getInstance().getDeviceThing().getProperties().get(i).getDataType());
+        }
+        Log.i("全部属性---------",""+LinkKit.getInstance().getDeviceThing().getProperties());
+
     }
 
     public void registerAliIoTListener(){
@@ -1394,9 +1490,7 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
         publishRequest.topic = "/a13H8L6bDyf/device2/user/checkOnlineStatus";
         publishRequest.payloadObj = "{\"id\":"+ publishRequest.msgId+", \"version\":\"1.0\",\"time\":" + System.currentTimeMillis() + "}";
         Integer networkInt=netWorkInfo();
-
         Log.i(TAG,"network网络"+networkInt);
-
             LinkKit.getInstance().publish(publishRequest, new IConnectSendListener() {
                 @Override
                 public void onResponse(ARequest aRequest, AResponse aResponse) {
@@ -1912,31 +2006,40 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
             mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
             System.exit(0);
     }
-
+    public void restartAndroid(){
+        //获取root权限,前提是设备已经root过
+            try {
+                Process process = Runtime.getRuntime().exec("su");
+                //执行重启命令
+                Runtime.getRuntime().exec("su -c reboot");
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+    }
     private Object getSystemService(String name) {
         return getApplication().getSystemService(name);
     }
 
     public void repeatTask() {
         Log.i("----------------------","ok");
-        task3 =new TimerTask(){
-            public void run(){
-                publishRepeat();
-                Log.i("Task","300秒循环");
-            }
-        };
-        timer.schedule(task3,60000,300000);
-        Calendar calendar = Calendar.getInstance();
-        calendar.setTimeInMillis(System.currentTimeMillis());
-        calendar.set(Calendar.HOUR_OF_DAY, 11);
-        calendar.set(Calendar.MINUTE, 26);
-        task2=new TimerTask() {
-            @Override
-            public void run() {
-                openLight();
-            }
-        };
-        timer.schedule(task2,0,1800000);
+//        task3 =new TimerTask(){
+//            public void run(){
+//                publishRepeat();
+//                Log.i("Task","300秒循环");
+//            }
+//        };
+//        timer.schedule(task3,60000,600000);
+//        Calendar calendar = Calendar.getInstance();
+//        calendar.setTimeInMillis(System.currentTimeMillis());
+//        calendar.set(Calendar.HOUR_OF_DAY, 11);
+//        calendar.set(Calendar.MINUTE, 26);
+//        task2=new TimerTask() {
+//            @Override
+//            public void run() {
+//                openLight();
+//            }
+//        };
+//        timer.schedule(task2,0,1800000);
 
         task1=new TimerTask() {
             @Override
@@ -1944,7 +2047,7 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
                 publish();
             }
         };
-        timer.schedule(task1,600000,600000);
+        timer.schedule(task1,600000,1800000);
     }
     private void publishRepeat(){
         Integer currentTemperature= SerialPortUtil.getInstance().getOtherDevice().geTemperature();//温度
@@ -1955,37 +2058,30 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
             SPUtils.getInstance().put("queryCurrent",num+1);//记录被夹次数
             SerialPortUtil.getInstance().getOtherDevice().clearCurrent();
         }
-        if(currentTemperature>90){
+        if(currentTemperature>60){
             SPUtils.getInstance().put("RunningState",2);//温度过高
             Log.i(TAG,"温度过高");
             Integer networkInt=netWorkInfo();
             if(networkInt!=0){
-                reportProperty();
+//                reportProperty();
                 //短信通知
                 SendSmsResponse("温度过高");
 
             }
         }
-        if(currentTemperature>40){
-//            SerialPortUtil.getInstance().getOtherDevice().openuFan();//打开分钟
+        if(currentTemperature>25){
+//            SerialPortUtil.getInstance().getOtherDevice().openuFan();//打开风扇
+            SerialPortUtil.getInstance().getOtherDevice().openLight4();
         }else{
-            //            SerialPortUtil.getInstance().getOtherDevice().closeFan();//打开分钟
+            //            SerialPortUtil.getInstance().getOtherDevice().closeFan();//打开风扇
+            SerialPortUtil.getInstance().getOtherDevice().closeLight4();
         }
 
         if(magDoorSwitch==1){
             if(SPUtils.getInstance().getString("magDoorSwitch").equals("0")){
                 SPUtils.getInstance().put("RunningState",3);
                 Log.i(TAG,"收运门意外打开");
-                Integer networkInt=netWorkInfo();
-                      /*  if(networkInt!=0){
-                            reportProperty();
-                            //短信通知
-                            try {
-                                SendSmsResponse("收运门意外打开");
-                            } catch (ClientException e) {
-                                e.printStackTrace();
-                            }
-                        }*/
+                SendSmsResponse("收运门意外打开");
             }
         }
 //                if(currentTemperature<100&magDoorSwitch==0) {
@@ -2004,18 +2100,26 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
 
     public void openLight(){
         Log.i("d定时","ok");
-        if(readTime()>19||readTime()<1){
+        if(readTime()>18||readTime()<1){
             Log.i("night","开灯");
-//            SerialPortUtil.getInstance().getOtherDevice().openLight1();
+            SerialPortUtil.getInstance().getOtherDevice().openLight4();
         }else {
             Log.i("day","关灯");
-//            SerialPortUtil.getInstance().getOtherDevice().closeLight1();
+            SerialPortUtil.getInstance().getOtherDevice().closeLight4();
         }
     }
 
 
     public static void SendSmsResponse(String event){
-        Log.i("短信","发送"+event);
+        if(event.equals("温度超声波失灵")){
+            reportDeviceEvent("errorEvent","温度超声波失灵",2);
+            Log.i("警告","发送"+event);
+        }else {
+            reportDeviceEvent("warnEvent",event,1);
+            Log.i("报警","发送"+event);
+        }
+
+
         /*DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4FcFSGUX9ngzehwMMU6M", "SxG0xU9U7bqpCDoK0nMGo4pSXAdNHc");
         IAcsClient client = new DefaultAcsClient(profile);
         CommonRequest request = new CommonRequest();
@@ -2038,10 +2142,10 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
         } catch (ClientException e) {
             e.printStackTrace();
         }*/
-        /*try {
+      /*  try {
             Response response = OkHttpUtils.post()
-                    .url("")
-                    .addParams("event", event)
+                    .url("/api/v1/sendMessage/send")
+                    .addParams("code", event)
                     .build().execute();
             if (response.isSuccessful()) {
                 String jsonStr = response.body().string();

+ 263 - 0
app/src/main/java/com/siwei/recyclebox/utils/LocationUtils.java

xqd
@@ -0,0 +1,263 @@
+package com.siwei.recyclebox.utils;
+
+import android.util.Log;
+
+import com.amap.api.location.AMapLocation;
+import com.amap.api.location.AMapLocationClient;
+import com.amap.api.location.AMapLocationClientOption;
+import com.amap.api.location.AMapLocationListener;
+import com.siwei.recyclebox.application.AppApplication;
+import com.siwei.recyclebox.entity.MapLocationInfo;
+
+/**
+ * 定位帮助类
+ */
+public class LocationUtils {
+
+    private AMapLocationClient client = null;
+    private AMapLocationClientOption mOption, DIYoption;
+    private Object objLock = new Object();
+
+    public AMapLocationListener myListener = new MyLocationListener();
+    private LocationListener mLocationListener;
+
+    private static LocationUtils mInstance;
+
+    public static LocationUtils getInstance() {
+        if (mInstance == null) {
+            mInstance = new LocationUtils();
+        }
+        return mInstance;
+    }
+
+
+    public void onCreate(LocationListener locationListener) {
+        mLocationListener = locationListener;
+        registerListener(myListener);   //注册监听函数
+        setLocationOption(getDefaultLocationClientOption());
+    }
+
+    /***
+     *
+     */
+    public LocationUtils() {
+        synchronized (objLock) {
+            if (client == null) {
+                client = new AMapLocationClient(AppApplication.getInstance());
+                client.setLocationOption(getDefaultLocationClientOption());
+            }
+        }
+    }
+
+    /***
+     * @param listener
+     * @return
+     */
+
+    public boolean registerListener(AMapLocationListener listener) {
+        boolean isSuccess = false;
+        if (listener != null) {
+            client.setLocationListener(listener);
+            isSuccess = true;
+        }
+        return isSuccess;
+    }
+
+    public void unregisterListener(AMapLocationListener listener) {
+        if (listener != null) {
+            client.unRegisterLocationListener(listener);
+        }
+    }
+
+    /***
+     * @param option
+     * @return isSuccessSetOption
+     */
+    public boolean setLocationOption(AMapLocationClientOption option) {
+        boolean isSuccess = false;
+        Log.i("locationFail", option.toString());
+        if (option != null) {
+            if (client.isStarted())
+                client.stopLocation();
+            DIYoption = option;
+            client.setLocationOption(option);
+            isSuccess = true;
+        }
+        return isSuccess;
+    }
+
+    public AMapLocationClientOption getOption() {
+        return DIYoption;
+    }
+
+    /***
+     * @return DefaultLocationClientOption
+     */
+    public AMapLocationClientOption getDefaultLocationClientOption() {
+
+        if (mOption == null) {
+            mOption = new AMapLocationClientOption();
+//            mOption.setLocationMode(LocationMode.Hight_Accuracy);//可选,默认高精度,设置定位模式,高精度,低功耗,仅设备
+//            mOption.setCoorType("bd09ll");//可选,默认gcj02,设置返回的定位结果坐标系,如果配合百度地图使用,建议设置为bd09ll;
+//            mOption.setScanSpan(1000);//可选,默认0,即仅定位一次,设置发起定位请求的间隔需要大于等于1000ms才是有效的
+//            mOption.setIsNeedAddress(true);//可选,设置是否需要地址信息,默认不需要
+//            mOption.setOpenGps(true);// 可选,默认false,设置是否使用gps
+//            mOption.setIsNeedLocationDescribe(false);//可选,设置是否需要地址描述
+//            mOption.setNeedDeviceDirect(false);//可选,设置是否需要设备方向结果
+//            mOption.setLocationNotify(false);//可选,默认false,设置是否当gps有效时按照1S1次频率输出GPS结果
+//            mOption.setIgnoreKillProcess(false);//可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死
+//            mOption.setIsNeedLocationDescribe(false);//可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于“在北京天安门附近”
+//            mOption.setIsNeedLocationPoiList(false);//可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到
+//            mOption.SetIgnoreCacheException(true);//可选,默认false,设置是否收集CRASH信息,默认收集
+
+            int span = 1000;
+            mOption.setInterval(span);// 可选,默认0,即仅定位一次,设置发起定位请求的间隔需要大于等于1000ms才是有效的
+            mOption.setNeedAddress(true);// 可选,设置是否需要地址信息,默认不需要
+            mOption.setLocationCacheEnable(false);
+            //mOption.setOpenGps(true);// 可选,默认false,设置是否使用gps
+            //mOption.setLocationNotify(true);// 可选,默认false,设置是否当gps有效时按照1S1次频率输出GPS结果
+            //mOption.setIsNeedLocationDescribe(true);// 可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于“在北京天安门附近”
+            //mOption.setIsNeedLocationPoiList(true);// 可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到
+            //mOption.setIgnoreKillProcess(false);// 可选,默认false,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认杀死
+            //mOption.SetIgnoreCacheException(false);// 可选,默认false,设置是否收集CRASH信息,默认收集
+            //mOption.setEnableSimulateGps(false);// 可选,默认false,设置是否需要过滤gps仿真结果,默认需要
+
+//            mOption.setIsNeedAltitude(false);//可选,默认false,设置定位时是否需要海拔信息,默认不需要,除基础定位版本都可用
+        }
+        Log.i("locationFail", mOption.toString());
+        return mOption;
+    }
+
+    public void start() {
+        synchronized (objLock) {
+            if (client != null) {
+                client.startLocation();
+            }
+        }
+    }
+
+    public void stop() {
+        synchronized (objLock) {
+            if (client != null) {
+                client.stopLocation();
+            }
+        }
+    }
+
+    /**
+     * 设置定位相关参数
+     */
+//    private void setLocationOption() {
+//        if (mOption != null) return;
+//        mOption = new LocationClientOption();
+//        mOption.setLocationMode(LocationMode.Hight_Accuracy);//设置定位模式
+//        mOption.setCoorType("bd09ll");//返回的定位结果是百度经纬度,默认值gcj02
+//        mOption.setScanSpan(5000);//设置发起定位请求的间隔时间为5000ms
+//        mOption.setIsNeedAddress(true);//可选,设置是否需要地址信息,默认不需要
+////        option.setIsNeedLocationDescribe(true);//可选,设置是否需要地址描述
+////        option.setNeedDeviceDirect(false);//可选,设置是否需要设备方向结果
+//        mOption.setLocationNotify(true);//可选,默认false,设置是否当gps有效时按照1S1次频率输出GPS结果
+////        option.setEnableSimulateGps(false);//可选,默认false,设置是否需要过滤gps仿真结果,默认需要
+//        mOption.setIgnoreKillProcess(true);//可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死
+//        mOption.setOpenGps(true);
+//        mOption.setIsNeedLocationPoiList(false);//可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到
+//        mOption.SetIgnoreCacheException(true);//可选,默认false,设置是否收集CRASH信息,默认收集
+//        mLocationClient.setLocOption(mOption);
+//
+//    }
+
+
+    /**
+     * 发起定位
+     */
+    public void startLocationInfo() {
+        start();
+    }
+
+    /**
+     * 停止定位
+     */
+    public void stopLocationClient() {
+        unregisterListener(myListener); //注销掉监听
+        stop(); //停止定位服务
+    }
+
+
+    /**
+     * 定位监听
+     * 百度地图
+     * 61 : GPS定位结果,GPS定位成功。
+     * 62 : 无法获取有效定位依据,定位失败,请检查运营商网络或者WiFi网络是否正常开启,尝试重新请求定位。
+     * 63 : 网络异常,没有成功向服务器发起请求,请确认当前测试手机网络是否通畅,尝试重新请求定位。
+     * 65 : 定位缓存的结果。
+     * 66 : 离线定位结果。通过requestOfflineLocaiton调用时对应的返回结果。
+     * 67 : 离线定位失败。通过requestOfflineLocaiton调用时对应的返回结果。
+     * 68 : 网络连接失败时,查找本地离线定位时对应的返回结果。
+     * 161: 网络定位结果,网络定位成功。
+     * 162: 请求串密文解析失败,一般是由于客户端SO文件加载失败造成,请严格参照开发指南或demo开发,放入对应SO文件。
+     * 167: 服务端定位失败,请您检查是否禁用获取位置信息权限,尝试重新请求定位。
+     * 502: AK参数错误,请按照说明文档重新申请AK。
+     * 505:AK不存在或者非法,请按照说明文档重新申请AK。
+     * 601: AK服务被开发者自己禁用,请按照说明文档重新申请AK。
+     * 602: key mcode不匹配,您的AK配置过程中安全码设置有问题,请确保:SHA1正确,“;”分号是英文状态;且包名是您当前运行应用的包名,请按照说明文档重新申请AK。
+     * 501~700:AK验证失败,请按照说明文档重新申请AK。
+     * 高德地图
+     * 6: LOCATION_TYPE_CELL 定位结果类型:基站定位结果 属于网络定位
+     * 3: LOCATION_TYPE_FAST 已过时。 已合并到AMapLocation.LOCATION_TYPE_SAME_REQ
+     * 4: LOCATION_TYPE_FIX_CACHE 定位结果类型:缓存定位结果 返回一段时间前设备在相同的环境中缓存下来的网络定位结果,节省无必要的设备定位消耗
+     * 1: LOCATION_TYPE_GPS 定位结果类型:GPS定位结果 通过设备GPS定位模块返回的定位结果
+     * 8: LOCATION_TYPE_OFFLINE 定位结果类型: 离线定位结果
+     * 2: LOCATION_TYPE_SAME_REQ 定位结果类型:前次定位结果 网络定位请求低于1秒、或两次定位之间设备位置变化非常小时返回,设备位移通过传感器感知
+     * 5: LOCATION_TYPE_WIFI 定位结果类型:Wifi定位结果 属于网络定位,定位精度相对基站定位会更好
+     *
+     * @author Administrator
+     */
+    public class MyLocationListener implements AMapLocationListener {
+        @Override
+        public void onLocationChanged(AMapLocation location) {
+            MapLocationInfo mapLocationInfo = null;
+            String message = "定位失败,请检查网络后重试!";
+            Log.i("location000", location.toString());
+            if (null != location) {
+                message = location.getLocationType() + ":" + message;
+                String address = location.getCity() + location.getDistrict() + location.getStreet() + location.getStreetNum() + location.getAoiName();
+                if (location.getLocationType() == AMapLocation.LOCATION_TYPE_GPS) {// GPS定位结果
+                    //gps定位成功
+                    mapLocationInfo = new MapLocationInfo(address, location.getProvince(),
+                            location.getCity(), location.getDistrict(), location.getStreet(), location.getLatitude(), location.getLongitude(), location.getAoiName(), location.getPoiName());
+                } else if (location.getLocationType() == AMapLocation.LOCATION_TYPE_CELL || location.getLocationType() == AMapLocation.LOCATION_TYPE_WIFI) {// 网络定位结果
+                    //网络定位成功
+                    mapLocationInfo = new MapLocationInfo(address, location.getProvince(),
+                            location.getCity(), location.getDistrict(), location.getStreet(), location.getLatitude(), location.getLongitude(), location.getAoiName(), location.getPoiName());
+                } else if (location.getLocationType() == AMapLocation.LOCATION_TYPE_OFFLINE) {// 离线定位结果
+                    //离线定位成功,离线定位结果也是有效的
+                    mapLocationInfo = new MapLocationInfo(address, location.getProvince(),
+                            location.getCity(), location.getDistrict(), location.getStreet(), location.getLatitude(), location.getLongitude(), location.getAoiName(), location.getPoiName());
+                }
+                stop();
+//                else if (location.getLocType() == BDLocation.TypeServerError) {
+                //服务端网络定位失败,可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com,会有人追查原因
+//                } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
+                //网络不同导致定位失败,请检查查网络是否流畅
+//                } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
+                // 无法获取有效定位依据导致定位失败,一般是由于手机的原因,处于飞行模式下一般会造成这种结果,可以试下重启手机
+//                }
+            }
+            if (mLocationListener == null) return;
+            if (mapLocationInfo != null) {
+                mLocationListener.locationSuccess(mapLocationInfo, message);
+            } else {
+                mLocationListener.locationFail(message);
+            }
+        }
+    }
+
+    //定位监听
+    public interface LocationListener {
+        //定位成功
+        void locationSuccess(MapLocationInfo mapLocationInfo, String locationType);
+
+        //定位失败
+        void locationFail(String message);
+    }
+}

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

xqd xqd
@@ -278,6 +278,26 @@
                     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.btnClickSendMsg}"
+                    android:text="事件测试"
+                    android:textSize="24sp"
+                    />
+                <Button
+                    android:layout_width="150dp"
+                    android:layout_height="100dp"
+                    android:onClick="@{viewModal.btnClickGetDeviceValue}"
+                    android:text="获取属性"
+                    android:textSize="24sp"
+                    />
+            </LinearLayout>
             <LinearLayout
                 android:layout_width="match_parent"
                 android:layout_height="130dp"
@@ -324,12 +344,33 @@
                 android:padding="16dp">
 
                 <Button
-                    android:layout_width="131dp"
+                    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"
+                    />
+            </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.btnClickrestartAndroid}"
+                    android:text="重启系统"
+                    android:textSize="24sp"
+                    />
+
             </LinearLayout>
 
         </LinearLayout>

이 변경점에서 너무 많은 파일들이 변경되어 몇몇 파일들은 표시되지 않았습니다.