餐品配比终端初始化

This commit is contained in:
马增飞
2025-01-22 11:53:25 +08:00
parent 74010127c7
commit e50fa8e6f5
542 changed files with 60062 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
/build
+131
View File
@@ -0,0 +1,131 @@
plugins {
id 'com.android.application'
}
android {
compileSdk 33
def app_version_code = 10
def app_version_name = '1.0'
defaultConfig {
applicationId "com.sw.ingredient"
minSdk 26
targetSdk 33
versionCode app_version_code
versionName app_version_name
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
multiDexEnabled true
manifestPlaceholders = [
JPUSH_PKGNAME: applicationId,
JPUSH_APPKEY : "e09fd1a00814b34bb15492a8", //JPush 上注册的包名对应的 Appkey.
JPUSH_CHANNEL: "developer-default", //暂时填写默认值即可.
]
ndk {
abiFilters 'armeabi-v7a'
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
signingConfigs {
debug {
storeFile file("system_3568.keystore")
storePassword "android"
keyAlias "androiddebugkey"
keyPassword "android"
}
}
android.applicationVariants.all {
variant ->
variant.outputs.all {
outputFileName = "app-release${app_version_name}.apk"
}
}
packagingOptions {
pickFirst 'lib/armeabi-v7a/libserial_port.so'
// pickFirst 'lib/arme64-v8a/libserial_port.so'
}
buildTypes {
debug {
signingConfig signingConfigs.debug
}
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar", "*.aar"])
implementation 'androidx.appcompat:appcompat:1.3.0-alpha02'
// 引入support支持库的multidex库
implementation 'com.android.support:multidex:1.0.3'
//或androidx支持库的multidex库
implementation 'androidx.multidex:multidex:2.0.1'
// implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.google.android.material:material:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation project(path: ':MPChartLib')
// implementation project(path: ':jiguang')
// implementation files('libs\\libWeighingscale.jar')
implementation files('libs\\org.eclipse.paho.client.mqttv3-1.2.5.jar')
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.github.bumptech.glide:glide:4.12.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'
implementation 'com.jakewharton:butterknife:10.2.3'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.3'
implementation 'com.lzy.net:okgo:3.0.4'
implementation('com.lzy.net:okrx2:2.0.2')
implementation("io.reactivex.rxjava2:rxandroid:2.0.1")
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'com.gyf.immersionbar:immersionbar:3.0.0'
implementation 'com.youth.banner:banner:2.1.0'
implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:3.0.4'
implementation 'com.scwang.smart:refresh-layout-kernel:2.0.3' //核心必须依赖
implementation 'com.scwang.smart:refresh-header-classics:2.0.3' //经典刷新头
implementation 'com.github.li-xiaojun:XPopup:2.9.19'
implementation 'com.hyman:flowlayout-lib:1.1.2'
// implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'
implementation 'com.umeng.umsdk:common:9.4.2'// 必选
implementation 'com.umeng.umsdk:asms:1.4.1'// 必选
implementation 'com.umeng.umsdk:apm:1.4.2'
implementation files('libs/WbIntelligentHardwareSDK-debug.aar')
implementation files('libs/utilcode.jar')
// 串口
// implementation 'com.licheedev:android-serialport:2.1.2'
// implementation 'com.licheedev:hardwareutils:1.0.0'
// implementation 'com.licheedev:logplus:1.0.0'
// eventbus
implementation 'org.greenrobot:eventbus:3.2.0'
implementation 'pub.devrel:easypermissions:3.0.0'
implementation 'com.github.bingoogolapple.BGAQRCode-Android:zxing:1.3.8'
def roomVersion = "2.2.5"
implementation("androidx.room:room-runtime:$roomVersion")
annotationProcessor("androidx.room:room-compiler:$roomVersion")
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+21
View File
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
@@ -0,0 +1,26 @@
package com.sw.arcdemo;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.sw.arcdemo", appContext.getPackageName());
}
}
+167
View File
@@ -0,0 +1,167 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.sw.st">
<!-- android:sharedUserId="android.uid.system"-->
<!-- ================================================ -->
<!-- Special broadcasts that only the system can send -->
<!-- ================================================ -->
<protected-broadcast android:name="MqttService.pingSender.sw" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.READ_PRIVILEGED_PHONE_STATE"
tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
<!-- 声明使用usb -->
<uses-feature
android:name="android.hardware.usb.host"
android:required="true" />
<application
android:name="com.sw.st.application.App"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:networkSecurityConfig="@xml/network_security_config"
android:requestLegacyExternalStorage="true"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<meta-data
android:name="android.max_aspect"
android:value="2.4" />
<!--适配华为(huawei)刘海屏-->
<meta-data
android:name="android.notch_support"
android:value="true" />
<!--适配小米(xiaomi)刘海屏-->
<meta-data
android:name="notch.config"
android:value="portrait|landscape" />
<activity
android:name="com.sw.st.ui.setting.FoodSettingActivity"
android:exported="true"
android:screenOrientation="landscape">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.sw.st.ui.addfood.AddFoodActivity"
android:screenOrientation="landscape">
</activity>
<!-- <activity-->
<!-- android:name="com.sw.st.ui.device.DeviceActivity"-->
<!-- android:screenOrientation="portrait">-->
<!-- </activity>-->
<activity
android:name="com.sw.st.ui.device.ChengListActivity"
android:screenOrientation="portrait"></activity>
<!-- <activity-->
<!-- android:name="com.sw.st.ui.device.ComListActivity"-->
<!-- android:screenOrientation="portrait">-->
<!-- </activity>-->
<!-- <activity-->
<!-- android:name="com.sw.st.ui.login.LoginActivity"-->
<!-- android:configChanges="screenSize|smallestScreenSize|screenLayout|orientation|keyboardHidden"-->
<!-- android:screenOrientation="portrait">-->
<!-- <intent-filter>-->
<!-- <action android:name="android.intent.action.MAIN" />-->
<!-- <category android:name="android.intent.category.LAUNCHER" />-->
<!-- </intent-filter>-->
<!-- </activity>-->
<!-- <activity-->
<!-- android:name="com.sw.st.ui.rfid.RfidMainActivity"-->
<!-- android:configChanges="screenSize|smallestScreenSize|screenLayout|orientation|keyboardHidden"-->
<!-- android:screenOrientation="landscape"></activity>-->
<!-- <activity-->
<!-- android:name="com.sw.st.ui.rfid.RfidBindActivity"-->
<!-- android:screenOrientation="portrait">-->
<!-- </activity>-->
<activity
android:name=".ui.init.InitActivity"
android:exported="true"
android:screenOrientation="landscape">
<!-- <intent-filter>-->
<!-- <action android:name="android.intent.action.MAIN" />-->
<!-- <category android:name="android.intent.category.LAUNCHER" />-->
<!-- </intent-filter>-->
</activity>
<activity
android:name=".ui.foodinfo.FoodInfoActivity"
android:launchMode="singleTask"
android:screenOrientation="landscape">
<!-- <intent-filter>-->
<!-- <action android:name="android.intent.action.MAIN" />-->
<!-- <category android:name="android.intent.category.LAUNCHER" />-->
<!-- <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />-->
<!-- </intent-filter>-->
</activity>
<!-- <receiver android:name="cn.jpush.android.asus.AsusPushMessageReceiver"></receiver>-->
<!-- <provider-->
<!-- android:name="cn.jpush.android.service.DataProvider"-->
<!-- android:authorities="com.sw.st.DataProvider"-->
<!-- android:exported="false"-->
<!-- android:process=":pushcore" />-->
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
<meta-data
android:name="JPUSH_APPKEY"
android:value="e09fd1a00814b34bb15492a8" />
<!-- Required SDK核心功能 -->
<receiver
android:name=".BootReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="1000">
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<service android:name=".utils.mqtt.service.MqttService" />
</application>
<!-- <uses-permission android:name="com.sw.st.permission.JPUSH_MESSAGE" />-->
<!-- <permission-->
<!-- android:name="com.sw.st.permission.JPUSH_MESSAGE"-->
<!-- android:protectionLevel="signature" />-->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
</manifest>
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,27 @@
package com.sw.st;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.sw.st.ui.foodinfo.FoodInfoActivity;
import com.sw.st.ui.init.InitActivity;
import com.sw.st.ui.setting.FoodSettingActivity;
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Intent newIntent = new Intent(context, FoodSettingActivity.class); // 要启动的Activity
//1.如果自启动APP,参数为需要自动启动的应用包名
//Intent intent = getPackageManager().getLaunchIntentForPackage(packageName);
//这句话必须加上才能开机自动运行app的界面
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//2.如果自启动Activity
context.startActivity(newIntent);
//3.如果自启动服务
//context.startService(newIntent);
}
}
}
@@ -0,0 +1,16 @@
package com.sw.st;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.sw.st.R;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
+252
View File
@@ -0,0 +1,252 @@
package com.sw.st;
import android.util.Log;
import com.google.gson.Gson;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class Test {
public static List<Long> getDate(String startTime, String endTime) {
//定义时间格式
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
List<Long> list = new ArrayList<>();
try {
// 转化成日期类型
Date startDate = simpleDateFormat.parse(startTime);
Date endDate = simpleDateFormat.parse(endTime);
//用Calendar 进行日期比较判断
Calendar calendar = Calendar.getInstance();
while (startDate.getTime() <= endDate.getTime()) {
// 把日期添加到集合
// list.add(simpleDateFormat.format(startDate));
list.add(startDate.getTime());
// 设置日期
calendar.setTime(startDate);
//把日期增加一分
calendar.add(Calendar.MINUTE, 1);
// 获取增加后的日期
startDate = calendar.getTime();
}
} catch (ParseException e) {
e.printStackTrace();
}
return list;
}
public static String formatLong2StringSDC(long time) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String date_string = sdf.format(new Date(time)) + ":00";
return date_string;
}
public static void main(String[] args) throws Exception {
// System.out.println(formatLong2StringSDC(1677564000000l));
//
// List<Long> betweenDate = getDate("2023-2-28 14:00:00", "2023-3-1 13:59:00");
// System.out.println(betweenDate.size());
//
// for (int i = 1; i < betweenDate.size(); i++) {
// System.out.println(betweenDate.get(i - 1) + "=" + betweenDate.get(i));
// }
// String startTime = "2019-05-15 10:00:00";
// String endTime = "2019-05-15 12:00:00";
//
// List<String> list = getMinutes(startTime,endTime);
// System.out.println(list.size());
// for (String time : list) {
// System.out.println(time);
// }
// long startMillis = System.currentTimeMillis() - 1000 * 60 * 60 * 14 * 1;
// long millis = System.currentTimeMillis();
// for (String s : getBetweenDays(startMillis, millis)) {
// System.out.println(s);
// }
// for (String s : getTwoDaysSpace("2023-3-15", "2023-3-17")) {
// System.out.println(s);
// }
}
/**
* 姓名脱敏
*
* @param fullName
* @return
*/
public static String desensitizedName(String fullName) {
if (fullName == null || fullName.length() <= 1) {
return fullName;
}
char[] nameArr = fullName.toCharArray();
if (nameArr.length > 2) {
for (int i = 1; i < nameArr.length - 1; i++) {
nameArr[i] = '*';
}
} else {
nameArr[1] = '*';
}
return new String(nameArr);
}
public static float[] stringToArray(String str) {
str = str.replace("[", "").replace("]", "");
String[] strings = str.split(",");
float[] floatArray = new float[strings.length];
for (int i = 1; i < strings.length; i++) {
floatArray[i] = Float.parseFloat(strings[i]);
}
return floatArray;
}
/**
* 获取某段时间内每分钟
*
* @param startTime
* @param endTime
* @return
* @throws Exception
*/
public static List<String> getMinutes(String startTime, String endTime) throws Exception {
List<String> list = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar c1 = Calendar.getInstance();
c1.setTime(sdf.parse(startTime));
Calendar c2 = Calendar.getInstance();
c2.setTime(sdf.parse(endTime));
while (c1.before(c2)) {
list.add(sdf.format(c1.getTime()));
c1.add(Calendar.MINUTE, 1);
}
return list;
}
private static List<String> getBetweenDays(long start, long current) {
List<String> dateList = new ArrayList<>();
// 将毫秒数转换成Instant对象
Instant startInstant = Instant.ofEpochMilli(start);
Instant currentInstant = Instant.ofEpochMilli(current);
// 将Instant对象转换成LocalDate对象
LocalDate currentDate = currentInstant.atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate startDate = startInstant.atZone(ZoneId.systemDefault()).toLocalDate();
// 计算两个日期之间的天数
long daysBetween = ChronoUnit.DAYS.between(startDate, currentDate);
// 输出每一天的日期
for (int i = 0; i < daysBetween; i++) {
dateList.add(startDate.plusDays(i).toString());
}
return dateList;
}
public static List<String> getTwoDaysSpace(String startDate, String endDate) {
List<String> dateList = new ArrayList<>();
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dateOne = sdf.parse(startDate);
Date dateTwo = sdf.parse(endDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateOne);
dateList.add(startDate);
while (dateTwo.after(calendar.getTime())) {
calendar.add(Calendar.DAY_OF_MONTH, 1);
dateList.add(sdf.format(calendar.getTime()));
}
} catch (Exception e) {
e.printStackTrace();
}
return dateList;
}
public static String removeDuplicates(String nums) {
ArrayList<Integer> arrayList = new ArrayList<>();
for (int i = nums.length() - 1; i > -1; i--) {
int value = Integer.parseInt(String.valueOf(nums.charAt(i)));
arrayList.add(value);
}
ArrayList<Integer> removeList = new ArrayList<>();
for (int j = 0; j < 10; j++) {
if (!nums.contains(j + "")) {
continue;
}
int count = 0;
for (int i = 0; i < arrayList.size(); i++) {
int value = arrayList.get(i);
if (value == j) {
count++;
if (count > 2) {
removeList.add(i);
}
}
}
}
Collections.sort(removeList);
int temp = 0;
for (int i : removeList) {
// System.out.println(i + "===" + temp);
arrayList.remove(i + temp);
temp--;
}
StringBuilder sb = new StringBuilder();
for (int i = arrayList.size() - 1; i > -1; i--) {
sb.append(arrayList.get(i) + "");
}
return sb.toString();
}
public static String delete(String str) {
// 建立一个 HashMap 来存放每个数字出现的次数
Map<Character, Integer> map = new HashMap<>();
// 创建一个 StringBuilder 来存放最终结果
StringBuilder sb = new StringBuilder();
// 遍历字符串中的每个字符
for (char c : str.toCharArray()) {
// 如果 HashMap 中存在当前字符,则将该字符出现的次数加 1
if (map.containsKey(c)) {
int count = map.get(c);
// 如果该字符出现的次数大于 2,则跳过
if (count >= 2) {
continue;
}
map.put(c, count + 1);
} else {
// 如果不存在,则将该字符出现的次数设置为 1
map.put(c, 1);
}
// 将字符加入 StringBuilder 中
sb.append(c);
}
// 返回最终结果
return sb.toString();
}
}
@@ -0,0 +1,47 @@
package com.sw.st;
import java.io.IOException;//导入IOException类
import java.net.DatagramPacket;//导入DatagramPacket类
import java.net.DatagramSocket;//导入DatagramSocket类
import java.net.InetAddress;//导入InetAddress类
import java.util.Scanner;//导入Scanner类
/*
* 服务器端,实现基于UDP的用户登陆
*/
public class UDPServer {//公共类
public static void main(String[] args) throws IOException {//主程序入口
/*
* 接收客户端发送的数据
*/
DatagramSocket socket = new DatagramSocket(8800); // 1.创建服务器端DatagramSocket,指定端口
// 2.创建数据报,用于接收客户端发送的数据
byte[] data = new byte[1024];//创建字节数组,指定接收的数据包的大小
DatagramPacket packet = new DatagramPacket(data, data.length);
// 3.接收客户端发送的数据
System.out.println("****服务器端已经启动,等待客户端发送数据");//输出提示信息
while (true) {//通过循环不停的向客户端发送数据和接收数据
socket.receive(packet);// 此方法在接收到数据报之前会一直阻塞
// 4.读取数据
String info = new String(data, 0, packet.getLength());//创建字符串对象
System.out.println("我是服务器,客户端说:" + info);//输出提示信息
/*
* 向客户端响应数据
*/
// 1.定义客户端的地址、端口号、数据
InetAddress address = packet.getAddress();//获取发送端的地址
int port = packet.getPort();//获取 发送端进程所绑定的端口
// Scanner scanner = new Scanner(System.in);//从键盘接受数据
// String send = scanner.nextLine();//nextLine方式接受字符串
String send = "swServer:http://192.168.6.144:8800";
byte[] data2 = send.getBytes();//将接收到的数据转换为字节数组
DatagramPacket packet2 = new DatagramPacket(data2, data2.length, address, port);// 2.创建数据报,包含响应的数据信息
socket.send(packet2); // 3.响应客户端
}
}
}
@@ -0,0 +1,521 @@
package com.sw.st.api;
import com.google.gson.JsonObject;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okrx2.adapter.ObservableBody;
import com.sw.st.application.App;
import com.sw.st.application.AppConst;
import com.sw.st.model.DeviceMacModel;
import com.sw.st.model.DinnerType;
import com.sw.st.model.FoodGoodsInfo;
import com.sw.st.model.FoodInfoModel;
import com.sw.st.model.MealRecordsInfo;
import com.sw.st.model.NewFoodInfoModel;
import com.sw.st.model.RecommendValueModel;
import com.sw.st.model.ResponseData;
import com.sw.st.model.UserFaceModel;
import com.sw.st.model.UserInfo;
import com.sw.st.net.helper.JsonConvert;
import com.sw.st.ui.device.BindDeviceModel;
import com.sw.st.ui.setting.FoodListModel;
import com.sw.st.utils.AppUtil;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import io.reactivex.Observable;
import static com.sw.st.ui.init.InitActivity.BASE_URL;
public class SwService {
private static final String BASE_URL = "http://192.168.10.7:9092";
// private static final String BASE_URL = "http://192.168.1.250:9999/";
// private static final String BASE_URL = "http://192.168.1.199:9999/";
// private static final String BASE_URL = "http://vip.shuziweidao.com";
public static String getServerAddress = "/equipment/stEquipment/queryByEquipmentCode";//外网服务获取业务服务器地址
public static final String checkUpdate = "/app/stApp/appVersionPpgrade";
public static String getUserFace = "/stapi/cquser/getUserFaceCache";//获取人脸信息
public static String rfidBindUser = "/zhstapi/zhst/bindUser";//绑定RFID
public static String getUserInfo = "/zhstapi/zhst/getUserInfo";//rfid获取用户信息
public static String getUserInfoById = "/stapi/cquser/getUserInfo";//获取用户信息
public static String getDinnerType = "/zhstapi/zhst/getDinnerType";//实时获取当前餐次
public static String getRestInfoByRestNo = "/zhstapi/zhst/getRestInfoByRestNo/";//查询食堂信息
public static String createRecord = "/rest/slMealRecordsController/create";//创建就餐记录
// public static String getRestInfoFoodsByType = "/zhstapi/zhst/getRestInfoFoodsByType/";//菜品信息
public static String getUserNutrition = "/zhstapi/zhst/getUserNutrition";//获取用户本餐次信息
// public static String getUserFace = + "rest/zhctUserController/getUserFaceCache";//获取人脸信息
public static String getUserFaceByIds = "/rest/zhctUserController/getUserFaceCacheByIds";//获取人脸信息
// public static String getUserInfo = + "rest/slBaseController/getUserInfo";//获取用户信息
public static String bindDeviceMac = "/rest/zhctUserController/bindDeviceMac";//用户id与设备绑定
public static String getDeviceMac = "/rest/zhctUserController/getDeviceMac";//获取用户id与设备绑定
public static String getFoodInfoByMac = "/rest/slBaseDeviceController/getFoodInfoByMac";//获取当前设备菜品信息
public static String getMealRecordsInfo = "/rest/zhctController/getMealRecordsInfo";//获取用户本餐所需能量
// public static String getDinnerType = + "rest/slBaseController/getDinnerType";//实时获取当前餐次
public static String getFoodList = "/rest/zhctController/getFoodList";//搜索菜品
public static String changeDeviceFood = "/rest/slBaseDeviceController/changeDeviceFood";//切换当前设备展示信息
public static String relRest = "/rest/slBaseDeviceController/relRest";//根据食堂编码和设备MAC绑定信息
public static String addFoodTotalWeight = "/rest/slMealRecordsController/addFoodTotalWeight";//增加菜品总量
// public static String getRestInfoByRestNo = + "rest/zhctController/getRestInfoByRestNo";//查询店铺信息
public static String onLineRenewal = "/rest/slBaseDeviceController/onLineRenewal";//上传在线状态
public static String addDeviceInit = "/equipment/stEquipment/addInitialize";//设备初始化
//================================新版本=======================================
public static String getRestInfoFoodsByType = "/shuwei-zhct/scales/getRestInfoFoodsByType";//菜品信息
public static String getUserNutritionData = "/shuwei-zhct/scales/getFoodInfoByplateNumber";//获取用户本餐次就餐数据
public static String startMealService = "/shuwei-zhct/scales/startMealService";//开餐
public static String userEatFood = "/shuwei-zhct/scales/userEatFood";//取餐
public static String getToken = "/shuwei-zhct/scales/generateToken";//获取token
public static String getDeviceInfoByEquipmentId = "/shuwei-zhct/scales/queryByEquipmentId";//查询设备参数
public static String saveMarginWeight = "/shuwei-zhct/scales/margin/saveMargin";//定时提交菜品重量
public static String getRecommendValue = "/shuwei-zhct/scales/getRecommended/values";//查询推荐值
public static String submitTakeFoodState = "/shuwei-zhct/scales/getFoodInfoByplateNumber/state";//提交餐盘信息,解决数据查询为空问题
public static String getGoodsUseList = "/shuwei-zhct/scales/goodsUseList";//获取菜品食材信息
public static String saveFoodGoodsUseInfo = "/shuwei-zhct/scales/saveFoodGoodsUseInfo";//提交菜品食材信息
public static Observable<ResponseData<ArrayList<UserFaceModel>>> getUserFace() {
return OkGo.<ResponseData<ArrayList<UserFaceModel>>>get(BASE_URL + getUserFace)
// .params("restNo", restNo)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<ResponseData<ArrayList<UserFaceModel>>>() {
})
.adapt(new ObservableBody<ResponseData<ArrayList<UserFaceModel>>>());
}
public static Observable<String> rfidBindUser(String uid,
String rfid,
String restId) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("userId", uid);
jsonObject.put("deviceCode", rfid);
jsonObject.put("restId", restId);
} catch (JSONException e) {
e.printStackTrace();
}
return OkGo.<String>post(BASE_URL + rfidBindUser)
.upJson(jsonObject)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<String>() {
})
.adapt(new ObservableBody<String>());
}
public static Observable<String> getUserInfo(String rfid) {
return OkGo.<String>get(BASE_URL + getUserInfo + "/" + rfid)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<String>() {
})
.adapt(new ObservableBody<String>());
}
public static Observable<String> getUserNutritionData(String foodId,
String eaId,
String plateNumber) {
return OkGo.<String>get(BASE_URL + getUserNutritionData)
.params("foodId", foodId)
.params("eaId", eaId)
.params("plateNumber", plateNumber)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<String>() {
})
.adapt(new ObservableBody<String>());
}
public static Observable<String> submitTakeFoodState(
String eaId,
String plateNumber) {
return OkGo.<String>get(BASE_URL + submitTakeFoodState)
.params("eaId", eaId)
.params("plateNumber", plateNumber)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<String>() {
})
.adapt(new ObservableBody<String>());
}
public static Observable<String> getUserInfoById(String uId) {
return OkGo.<String>get(BASE_URL + getUserInfoById + "/" + uId)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<String>() {
})
.adapt(new ObservableBody<String>());
}
/**
* @param restId
* @param type 0全部 1餐次
* @return
*/
public static Observable<ResponseData<ArrayList<NewFoodInfoModel>>> getRestInfoFoodsByType(String restId, String type) {
return OkGo.<ResponseData<ArrayList<NewFoodInfoModel>>>get(BASE_URL + getRestInfoFoodsByType)
.params("eaId", restId)
.params("type", type)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<ResponseData<ArrayList<NewFoodInfoModel>>>() {
})
.adapt(new ObservableBody<ResponseData<ArrayList<NewFoodInfoModel>>>());
}
/**
* 搜索菜品
*
* @param restId
* @param foodName
* @return
*/
public static Observable<ResponseData<ArrayList<NewFoodInfoModel>>> getRestInfoFoodsByName(String restId, String foodName) {
return OkGo.<ResponseData<ArrayList<NewFoodInfoModel>>>get(BASE_URL + getRestInfoFoodsByType)
.params("eaId", restId)
.params("type", 0)
.params("foodName", foodName)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<ResponseData<ArrayList<NewFoodInfoModel>>>() {
})
.adapt(new ObservableBody<ResponseData<ArrayList<NewFoodInfoModel>>>());
}
/**
* @param foodId
* @return
*/
public static Observable<ResponseData<ArrayList<FoodInfoModel>>> getRestInfoFoodsByFoodId(String restId, String foodId) {
return OkGo.<ResponseData<ArrayList<FoodInfoModel>>>get(BASE_URL + getRestInfoFoodsByType)
.params("eaId", restId)
.params("foodId", foodId)
.params("type", 0)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<ResponseData<ArrayList<FoodInfoModel>>>() {
})
.adapt(new ObservableBody<ResponseData<ArrayList<FoodInfoModel>>>());
}
/**
* @param foodId
* @param type 1开餐,2加菜
* @param foodWeight
* @param restId
* @return
*/
public static Observable<String> startMealService(String foodId,
int type,
double foodWeight,
String restId) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("foodId", foodId);
jsonObject.put("type", type);
jsonObject.put("foodWeight", foodWeight);
jsonObject.put("eaId", restId);
jsonObject.put("deviceId", AppUtil.getUDID(App.getmContext()));
} catch (JSONException e) {
e.printStackTrace();
}
return OkGo.<String>post(BASE_URL + startMealService)
.upJson(jsonObject)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<String>() {
})
.adapt(new ObservableBody<String>());
}
public static Observable<String> saveMarginWeight(String foodId,
String eaId,
double marginWeight) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("foodId", foodId);
jsonObject.put("eaId", eaId);
jsonObject.put("marginWeight", marginWeight);
jsonObject.put("deviceId", AppUtil.getUDID(App.getmContext()));
} catch (JSONException e) {
e.printStackTrace();
}
return OkGo.<String>post(BASE_URL + saveMarginWeight)
.upJson(jsonObject)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<String>() {
})
.adapt(new ObservableBody<String>());
}
public static Observable<String> userEatFood(String plateNumber,
String foodId,
String eaId,
double eatWeight,
double foodWeight) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("foodId", foodId);
jsonObject.put("plateNumber", plateNumber);
jsonObject.put("eaId", eaId);
jsonObject.put("eatWeight", eatWeight);
jsonObject.put("foodWeight", foodWeight);
jsonObject.put("deviceId", AppUtil.getUDID(App.getmContext()));
} catch (JSONException e) {
e.printStackTrace();
}
return OkGo.<String>post(BASE_URL + userEatFood)
.upJson(jsonObject)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<String>() {
})
.adapt(new ObservableBody<String>());
}
public static Observable<String> getUserNutrition(String restId,
String userId) {
return OkGo.<String>get(BASE_URL + getUserNutrition)
.params("restId", restId)
.params("userId", userId)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<String>() {
})
.adapt(new ObservableBody<String>());
}
// public static Observable<ResponseData<UserInfo>> getUserInfo(String rfid) {
// return OkGo.<ResponseData<UserInfo>>get(getUserInfo + "/" + rfid)
// .cacheMode(CacheMode.NO_CACHE)
// .converter(new JsonConvert<ResponseData<UserInfo>>() {
// })
// .adapt(new ObservableBody<ResponseData<UserInfo>>());
// }
public static Observable<ResponseData<ArrayList<UserFaceModel>>> getUserFaceByIds(String ids) {
return OkGo.<ResponseData<ArrayList<UserFaceModel>>>post(BASE_URL + getUserFaceByIds + "/" + ids)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<ResponseData<ArrayList<UserFaceModel>>>() {
})
.adapt(new ObservableBody<ResponseData<ArrayList<UserFaceModel>>>());
}
public static Observable<ResponseData<String>> bindDeviceMac(String uid, String deviceMac) {
return OkGo.<ResponseData<String>>post(BASE_URL + bindDeviceMac + "/" + uid + "/" + deviceMac)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<ResponseData<String>>() {
})
.adapt(new ObservableBody<ResponseData<String>>());
}
public static Observable<ResponseData<DeviceMacModel>> getDeviceMac(String uid) {
return OkGo.<ResponseData<DeviceMacModel>>post(BASE_URL + getDeviceMac + "/" + uid)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<ResponseData<DeviceMacModel>>() {
})
.adapt(new ObservableBody<ResponseData<DeviceMacModel>>());
}
public static Observable<ResponseData<FoodInfoModel>> getFoodInfoByMac(String deviceMac) {
return OkGo.<ResponseData<FoodInfoModel>>get(BASE_URL + getFoodInfoByMac + "/" + deviceMac)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<ResponseData<FoodInfoModel>>() {
})
.adapt(new ObservableBody<ResponseData<FoodInfoModel>>());
}
public static Observable<ResponseData<MealRecordsInfo>> getMealRecordsInfo(String userId) {
return OkGo.<ResponseData<MealRecordsInfo>>get(BASE_URL + getMealRecordsInfo + "/" + userId)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<ResponseData<MealRecordsInfo>>() {
})
.adapt(new ObservableBody<ResponseData<MealRecordsInfo>>());
}
public static Observable<ResponseData<DinnerType>> getDinnerType() {
return OkGo.<ResponseData<DinnerType>>get(BASE_URL + getDinnerType)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<ResponseData<DinnerType>>() {
})
.adapt(new ObservableBody<ResponseData<DinnerType>>());
}
public static Observable<ResponseData<BindDeviceModel>> relRest(String deviceMac, String restId, String deviceDesc) {
return OkGo.<ResponseData<BindDeviceModel>>post(BASE_URL + relRest + "/" + deviceMac + "/" + restId)
.params("deviceDesc", deviceDesc)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<ResponseData<BindDeviceModel>>() {
})
.adapt(new ObservableBody<ResponseData<BindDeviceModel>>());
}
public static Observable<ResponseData<String>> createRecord(String userId, String foodId, double intake, double residueWeight) {
return OkGo.<ResponseData<String>>post(BASE_URL + createRecord + "/" + userId + "/" + foodId + "/" + intake + "?residueWeight=" + residueWeight)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<ResponseData<String>>() {
})
.adapt(new ObservableBody<ResponseData<String>>());
}
public static Observable<String> getToken(String devId) {
return OkGo.<String>get(BASE_URL + getToken)
.params("deviceId", devId)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<String>() {
})
.adapt(new ObservableBody<String>());
}
public static Observable<String> getBaseToken(String url, String devId) {
return OkGo.<String>get(url + getToken)
.params("deviceId", devId)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<String>() {
})
.adapt(new ObservableBody<String>());
}
public static Observable<String> getServerAddress(String url, String devId) {
return OkGo.<String>get(url + getServerAddress)
.params("equipmentCode", devId)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<String>() {
})
.adapt(new ObservableBody<String>());
}
public static Observable<String> appCheckUpdate(String versionNo,
String packageName) {
return OkGo.<String>get(BASE_URL + checkUpdate)
.params("appVersion", versionNo)
.params("appName", packageName)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<String>() {
})
.adapt(new ObservableBody<String>());
}
public static Observable<String> addDeviceInit(String devId, String packageName) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("status", 0);//0:不需要,1:需要分配虹软
jsonObject.put("equipmentName", packageName);
jsonObject.put("equipmentCode", devId);
} catch (JSONException e) {
e.printStackTrace();
}
return OkGo.<String>post(BASE_URL + addDeviceInit)
.upJson(jsonObject)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<String>() {
})
.adapt(new ObservableBody<String>());
}
public static Observable<String> getDeviceInfoByEquipmentId(String devId) {
return OkGo.<String>get(BASE_URL + getDeviceInfoByEquipmentId)
.params("equipmentCode", devId)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<String>() {
})
.adapt(new ObservableBody<String>());
}
/**
* @param foodId 菜品ID
* @param type 是否开餐(0开餐,1加餐)
* @param totalWeight 菜品增重
* @return
*/
public static Observable<String> addFoodTotalWeight(String foodId, int type, double totalWeight, String deviceMac) {
return OkGo.<String>post(BASE_URL + addFoodTotalWeight + "/" + foodId + "/" + type + "/" + totalWeight + "/" + deviceMac)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<String>() {
})
.adapt(new ObservableBody<String>());
}
public static Observable<String> getRestInfoByRestNo(String restNo) {
return OkGo.<String>get(BASE_URL + getRestInfoByRestNo + restNo)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<String>() {
})
.adapt(new ObservableBody<String>());
}
public static Observable<String> onLineRenewal(String deviceMac) {
return OkGo.<String>get(BASE_URL + onLineRenewal + "/" + deviceMac)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<String>() {
})
.adapt(new ObservableBody<String>());
}
public static Observable<String> uploadCrashLog(String url, String data) {
return OkGo.<String>post(url)
.upJson(data)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<String>() {
})
.adapt(new ObservableBody<String>());
}
public static Observable<ResponseData<RecommendValueModel>> getRecommendValue() {
return OkGo.<ResponseData<RecommendValueModel>>get(BASE_URL + getRecommendValue)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<ResponseData<RecommendValueModel>>() {
})
.adapt(new ObservableBody<ResponseData<RecommendValueModel>>());
}
public static Observable<String> getGoodsUseList(String foodId, double foodWeight) {
return OkGo.<String>get(BASE_URL + getGoodsUseList)
.params("foodId", foodId)
.params("foodWeight", foodWeight)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<String>() {
})
.adapt(new ObservableBody<String>());
}
public static Observable<String> saveFoodGoodsUseInfo(String foodId, double foodWeight, ArrayList<FoodGoodsInfo> goodsInfo) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("foodId", foodId);
jsonObject.put("foodWeight", foodWeight);
jsonObject.put("voList", goodsInfo);
} catch (JSONException e) {
e.printStackTrace();
}
return OkGo.<String>post(BASE_URL + saveFoodGoodsUseInfo)
.upJson(jsonObject)
.cacheMode(CacheMode.NO_CACHE)
.converter(new JsonConvert<String>() {
})
.adapt(new ObservableBody<String>());
}
}
@@ -0,0 +1,152 @@
//package com.sw.st.api;
//
//import com.xmjjdz.serialportapi.libweighingscale.API;
//
//import java.io.ByteArrayOutputStream;
//import java.io.File;
//import java.io.IOException;
//import java.io.InputStream;
//import java.util.Arrays;
//import java.util.Comparator;
//
//import android_serialport_api.SerialPort;
//import android_serialport_api.SerialPortFinder;
//
//public class WeightApi {
// private SerialPort serialPort;
// private ResponseListener responseListener;
// private ReceiveThread receiveThread;
//
// public WeightApi() {
// }
//
// public String[] getSerialPorts() {
// String[] result = new String[0];
//
// try {
// SerialPortFinder serialPortFinder = new SerialPortFinder();
// result = serialPortFinder.getAllDevicesPath();
// Arrays.sort(result, new Comparator<String>() {
// public int compare(String o1, String o2) {
// return o1.compareTo(o2);
// }
// });
// } catch (Exception var3) {
// }
//
// return result;
// }
//
// public void openPort(String serialPortDevicePath, int baudrate, ResponseListener responseListener) throws IOException, SecurityException {
// if (this.serialPort != null) {
// this.closePort();
// }
//
// this.responseListener = responseListener;
// this.serialPort = new SerialPort(new File(serialPortDevicePath), baudrate, 0);
// this.receiveThread = new ReceiveThread(this.serialPort.getInputStream());
// this.receiveThread.start();
// }
//
// public void closePort() {
// if (this.serialPort != null) {
// this.receiveThread.terminated = true;
// this.serialPort.close();
// this.serialPort = null;
// }
//
// }
//
// public void sendCmd(byte[] cmdBytes) throws IOException {
// this.serialPort.getOutputStream().write(cmdBytes);
// }
//
// public void sendCmd(byte[] cmdBytes, int startPos, int length) throws IOException {
// this.serialPort.getOutputStream().write(Arrays.copyOfRange(cmdBytes, startPos, startPos + length));
// }
//
// private class ReceiveThread extends Thread {
// boolean terminated = false;
// final InputStream inputStream;
// byte[] buffer = new byte[256];
//
// ReceiveThread(InputStream inputStream) {
// this.inputStream = inputStream;
// }
//
// public void run() {
// super.run();
// int lenTotalRead = 0;
// byte lenNeed = 2;
//
// long sleepMillis;
// try {
//
// for (; !this.terminated; Thread.sleep(sleepMillis)) {
// int lenAvailable;
// if ((lenAvailable = this.inputStream.available()) > 0) {
// int lenWillRead = Math.min(lenAvailable, lenNeed - lenTotalRead);
// lenTotalRead += this.inputStream.read(this.buffer, lenTotalRead, lenWillRead);
// }
//
// if (lenNeed == lenTotalRead) {
// String bufferString = new String(this.buffer, 0, lenTotalRead);
// if (lenTotalRead == 2) {
// if (!bufferString.equals("OK") && !bufferString.equals("ER")) {
// lenNeed = 50;
// sleepMillis = 5L;
// } else {
// if (WeightApi.this.responseListener != null) {
// WeightApi.this.responseListener.onGetCmdResult(Arrays.copyOf(this.buffer, lenTotalRead));
// }
//
// lenTotalRead = 0;
// lenNeed = 2;
// sleepMillis = 5L;//50L
// }
// } else {
// if (WeightApi.this.responseListener != null) {
// WeightApi.this.responseListener.onGetWeightInfo(Arrays.copyOf(this.buffer, lenTotalRead));
//
//// WeightApi.this.responseListener.onGetWeightInfo(readStream(inputStream));
// }
//
// lenTotalRead = 0;
// lenNeed = 2;
// sleepMillis = 5L;//50L
// }
// } else {
// sleepMillis = lenTotalRead == 0 ? 5L : 5L;//sleepMillis = lenTotalRead == 0 ? 50L : 5L;
// }
// }
// } catch (IOException var7) {
// var7.printStackTrace();
// this.terminated = true;
// } catch (InterruptedException var8) {
// var8.printStackTrace();
// this.terminated = true;
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// }
// }
//
// public interface ResponseListener {
// void onGetCmdResult(byte[] var1);
//
// void onGetWeightInfo(byte[] var1);
// }
//
// public byte[] readStream(InputStream inStream) throws Exception {
// ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
// byte[] buffer = new byte[1024];
// int len = -1;
// while ((len = inStream.read(buffer)) != -1) {
// outSteam.write(buffer, 0, len);
// }
// outSteam.close();
// inStream.close();
// return outSteam.toByteArray();
// }
//}
@@ -0,0 +1,101 @@
package com.sw.st.application;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.graphics.Typeface;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.cookie.CookieJarImpl;
import com.lzy.okgo.cookie.store.SPCookieStore;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.sw.st.utils.CrashHandler;
import java.lang.reflect.Field;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import okhttp3.OkHttpClient;
public class App extends Application {
public static List<Activity> activities = new LinkedList<>();
private static Context mContext;
@Override
public void onCreate() {
super.onCreate();
mContext = this.getApplicationContext();
initOkGo();
// activeEngine();
// JPushInterface.setDebugMode(true);
// JPushInterface.init(this);
// //设置LOG开关,默认为false
// UMConfigure.setLogEnabled(true);
//
// //友盟预初始化
// UMConfigure.preInit(getApplicationContext(), "611e20f11fee2e303c2a51e4", "Umeng");
//
// UMConfigure.init(getApplicationContext(), "611e20f11fee2e303c2a51e4", "Umeng", UMConfigure.DEVICE_TYPE_PHONE, "");
// // 选用AUTO页面采集模式
// MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO);
// 测试默认打开红外灯,否者个别红外摄像头没画面
// YNHAPI.init(getApplicationContext());
// YNHAPI.setLightState(YNHAPI.Light.Light_InfraredLed, true);
// LogcatHelper.getInstance(this).start();
CrashHandler.getInstance().init(mContext);
}
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
// MultiDex.install(this);
}
/**
* 初始化okgo
*/
private void initOkGo() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
//使用sp保持cookie,如果cookie不过期,则一直有效
builder.cookieJar(new CookieJarImpl(new SPCookieStore(this)));
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
//log颜色级别,决定了log在控制台显示的颜色
loggingInterceptor.setColorLevel(Level.INFO);
builder.addInterceptor(loggingInterceptor);
// builder.addInterceptor(new TokenInterceptor());
OkGo.getInstance()
.init(this)
.setOkHttpClient(builder.build()) //设置OkHttpClient,不设置将使用默认的
.setCacheMode(CacheMode.NO_CACHE)
.setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)
.setRetryCount(0);
}
public static Context getmContext() {
return mContext;
}
/**
* 退出程序
*/
public static void exit() {
for (Activity activity : activities) {
activity.finish();
}
}
}
@@ -0,0 +1,20 @@
package com.sw.st.application;
import android.os.Environment;
public class AppConst {
public static final String BASE_FILE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/sw";
public static final String BASE_IMG_URL = "https://zhst.rk-health.com/systemController/showOrDownByurlFTP.do?dbPath=";
public static final String WEB_BASE_URL = "http://47.105.49.67/";
// public static final String WEB_BASE_URL = "http://192.168.6.76:8080/";
public static final String BASE_URL = "http://zhst.rk-health.com/";
// public static final String BASE_URL = "http://192.168.31.36:8089/zhst/";
public static final String SOCKET_SERVICE_URL = "ws://192.168.5.110:22211";
public static final String ARCSOFT_APP_ID = "J6jt8Lgou3cTW9Y1k9T8Zx4nP51ZgcHRv668znCcUu5g";
public static final String ARCSOFT_SDK_KEY = "8necG4J6MQeTnz4gvcZuaRUywJynZindJCt2geuBnYv9";
}
@@ -0,0 +1,217 @@
package com.sw.st.base;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
import com.sw.st.R;
import com.sw.st.application.App;
import com.sw.st.view.CustomDialog;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import butterknife.ButterKnife;
public abstract class BaseActivity<V, T extends BasePresenter<V>> extends AppCompatActivity {
protected T mPresenter;
private CustomDialog mDialogWaiting;
protected Context mContext;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
App.activities.add(this);
mContext = this;
init();
//判断是否使用MVP模式
mPresenter = createPresenter();
if (mPresenter != null) {
mPresenter.attachView((V) this);//因为之后所有的子类都要实现对应的View接口
}
//子类不再需要设置布局ID,也不再需要使用ButterKnife.bind()
setContentView(provideContentViewId());
ButterKnife.bind(this);
// excuteStatesBar();
initData();
initView();
initListener();
}
/**
* 解决4.4设置状态栏颜色之后,布局内容嵌入状态栏位置问题
*/
private void excuteStatesBar() {
ViewGroup mContentView = (ViewGroup) getWindow().findViewById(Window.ID_ANDROID_CONTENT);
View mChildView = mContentView.getChildAt(0);
if (mChildView != null) {
//注意不是设置 ContentView 的 FitsSystemWindows,
// 而是设置 ContentView 的第一个子 View ,预留出系统 View 的空间.
mChildView.setFitsSystemWindows(true);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mPresenter != null) {
mPresenter.detachView();
}
}
//在setContentView()调用之前调用,可以设置WindowFeature(如:this.requestWindowFeature(Window.FEATURE_NO_TITLE);)
public void init() {
}
//得到当前界面的布局文件id(由子类实现)
protected abstract int provideContentViewId();
public abstract void initView();
public abstract void initData();
public abstract void initListener();
//用于创建Presenter和判断是否使用MVP模式(由子类实现)
protected abstract T createPresenter();
/**
* 显示等待提示框
*/
public Dialog showWaitingDialog(String tip) {
hideWaitingDialog();
View view = View.inflate(this, R.layout.dialog_waiting, null);
if (!TextUtils.isEmpty(tip))
((TextView) view.findViewById(R.id.tvTip)).setText(tip);
mDialogWaiting = new CustomDialog(this, view, R.style.MyDialog);
mDialogWaiting.show();
mDialogWaiting.setCancelable(true);
return mDialogWaiting;
}
/**
* 隐藏等待提示框
*/
public void hideWaitingDialog() {
if (mDialogWaiting != null) {
mDialogWaiting.dismiss();
mDialogWaiting = null;
}
}
/**
* 权限检查
*
* @param neededPermissions 需要的权限
* @return 是否全部被允许
*/
protected boolean checkPermissions(String[] neededPermissions) {
if (neededPermissions == null || neededPermissions.length == 0) {
return true;
}
boolean allGranted = true;
for (String neededPermission : neededPermissions) {
allGranted &= ContextCompat.checkSelfPermission(this, neededPermission) == PackageManager.PERMISSION_GRANTED;
}
return allGranted;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
boolean isAllGranted = true;
for (int grantResult : grantResults) {
isAllGranted &= (grantResult == PackageManager.PERMISSION_GRANTED);
}
afterRequestPermission(requestCode, isAllGranted);
}
/**
* 请求权限的回调
*
* @param requestCode 请求码
* @param isAllGranted 是否全部被同意
*/
protected abstract void afterRequestPermission(int requestCode, boolean isAllGranted);
protected void showToast(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
protected void showLongToast(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
}
/**
* 系统弹框提示
*
* @param s
*/
protected void showTipsDialog(String s) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("提示");
builder.setMessage(s);
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Intent wifiSettingsIntent = new Intent("android.settings.WIFI_SETTINGS");
// startActivity(wifiSettingsIntent);
}
});
builder.show();
}
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
hideStatusBar();
}
private void hideStatusBar() {
if (Build.VERSION.SDK_INT < 16) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
} else {
View decorView = getWindow().getDecorView();
// int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
// decorView.setSystemUiVisibility(uiOptions);
int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
//布局位于状态栏下方
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
//全屏
View.SYSTEM_UI_FLAG_FULLSCREEN |
//隐藏导航栏
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
uiOptions |= 0x00001000;
decorView.setSystemUiVisibility(uiOptions);
}
}
}
@@ -0,0 +1,74 @@
package com.sw.st.base;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import butterknife.ButterKnife;
public abstract class BaseFragment<V, T extends BasePresenter<V>> extends Fragment {
protected T mPresenter;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
//判断是否使用MVP模式
mPresenter = createPresenter();
if (mPresenter != null) {
mPresenter.attachView((V) this);//因为之后所有的子类都要实现对应的View接口
}
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(provideContentViewId(), container, false);
ButterKnife.bind(this, rootView);
initView(rootView);
return rootView;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initData();
initListener();
}
@Override
public void onDestroy() {
super.onDestroy();
if (mPresenter != null) {
mPresenter.detachView();
}
}
public void init() {
}
public void initView(View rootView) {
}
public void initData() {
}
public void initListener() {
}
//用于创建Presenter和判断是否使用MVP模式(由子类实现)
protected abstract T createPresenter();
//得到当前界面的布局文件id(由子类实现)
protected abstract int provideContentViewId();
}
@@ -0,0 +1,35 @@
package com.sw.st.base;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
public abstract class BasePresenter<V> {
protected Reference<V> mViewRef;
public void attachView(V view) {
mViewRef = new WeakReference<V>(view);
}
protected V getView() {
if (mViewRef != null) {
return mViewRef.get();
} else {
return null;
}
}
public boolean isViewAttached() {
return mViewRef != null && mViewRef.get() != null;
}
public void detachView() {
if (mViewRef != null) {
mViewRef.clear();
mViewRef = null;
}
}
}
@@ -0,0 +1,10 @@
package com.sw.st.base;
public interface BaseView {
void showProgress(String tipString);
void hideProgress();
}
@@ -0,0 +1,13 @@
package com.sw.st.model;
public class DeviceMacModel {
private String deviceMac;
public String getDeviceMac() {
return deviceMac;
}
public void setDeviceMac(String deviceMac) {
this.deviceMac = deviceMac;
}
}
@@ -0,0 +1,27 @@
package com.sw.st.model;
public class DinnerModel {
private float dinnerMin;
private float dinnerMax;
public DinnerModel(float dinnerMin, float dinnerMax) {
this.dinnerMin = dinnerMin;
this.dinnerMax = dinnerMax;
}
public float getDinnerMin() {
return dinnerMin;
}
public void setDinnerMin(float dinnerMin) {
this.dinnerMin = dinnerMin;
}
public float getDinnerMax() {
return dinnerMax;
}
public void setDinnerMax(float dinnerMax) {
this.dinnerMax = dinnerMax;
}
}
@@ -0,0 +1,13 @@
package com.sw.st.model;
public class DinnerType {
private int dinnerType;
public int getDinnerType() {
return dinnerType;
}
public void setDinnerType(int dinnerType) {
this.dinnerType = dinnerType;
}
}
@@ -0,0 +1,67 @@
package com.sw.st.model;
public class FoodGoodsInfo {
private String foodId;
private String foodName;
private double foodWeight;
private String goodsId;
private String goodsName;
private double useWeight;
private double useRealWeight;
public String getFoodId() {
return foodId;
}
public void setFoodId(String foodId) {
this.foodId = foodId;
}
public String getFoodName() {
return foodName;
}
public void setFoodName(String foodName) {
this.foodName = foodName;
}
public double getFoodWeight() {
return foodWeight;
}
public void setFoodWeight(double foodWeight) {
this.foodWeight = foodWeight;
}
public String getGoodsId() {
return goodsId;
}
public void setGoodsId(String goodsId) {
this.goodsId = goodsId;
}
public String getGoodsName() {
return goodsName;
}
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
public double getUseWeight() {
return useWeight;
}
public void setUseWeight(double useWeight) {
this.useWeight = useWeight;
}
public double getUseRealWeight() {
return useRealWeight;
}
public void setUseRealWeight(double useRealWeight) {
this.useRealWeight = useRealWeight;
}
}
@@ -0,0 +1,235 @@
package com.sw.st.model;
import java.io.Serializable;
public class FoodInfoModel implements Serializable {
private String id;
private String foodName;
private String imgUrl;
private String foodLabel;
private stFoodInfoSetting stFoodInfoSetting;
private stFoodInfoMaterial stFoodInfoMaterial;
private stFoodInfoPagodaAPPVO stFoodInfoPagodaAPPVO;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFoodName() {
return foodName;
}
public void setFoodName(String foodName) {
this.foodName = foodName;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public void setFoodLabel(String foodLabel) {
this.foodLabel = foodLabel;
}
public String getFoodLabel() {
return foodLabel;
}
public FoodInfoModel.stFoodInfoSetting getStFoodInfoSetting() {
return stFoodInfoSetting;
}
public void setStFoodInfoSetting(FoodInfoModel.stFoodInfoSetting stFoodInfoSetting) {
this.stFoodInfoSetting = stFoodInfoSetting;
}
public FoodInfoModel.stFoodInfoMaterial getStFoodInfoMaterial() {
return stFoodInfoMaterial;
}
public void setStFoodInfoMaterial(FoodInfoModel.stFoodInfoMaterial stFoodInfoMaterial) {
this.stFoodInfoMaterial = stFoodInfoMaterial;
}
public FoodInfoModel.stFoodInfoPagodaAPPVO getStFoodInfoPagodaAPPVO() {
return stFoodInfoPagodaAPPVO;
}
public void setStFoodInfoPagodaAPPVO(FoodInfoModel.stFoodInfoPagodaAPPVO stFoodInfoPagodaAPPVO) {
this.stFoodInfoPagodaAPPVO = stFoodInfoPagodaAPPVO;
}
public class stFoodInfoMaterial implements Serializable {
private float energyKcal;//热量
private float fat;//脂肪
private float protein;//蛋白质
private float cho;//碳水化合物
private float na;//钠
private float sugar;//糖
public float getEnergyKcal() {
return energyKcal;
}
public void setEnergyKcal(float energyKcal) {
this.energyKcal = energyKcal;
}
public float getFat() {
return fat;
}
public void setFat(float fat) {
this.fat = fat;
}
public float getProtein() {
return protein;
}
public void setProtein(float protein) {
this.protein = protein;
}
public float getCho() {
return cho;
}
public void setCho(float cho) {
this.cho = cho;
}
public float getNa() {
return na;
}
public void setNa(float na) {
this.na = na;
}
public float getSugar() {
return sugar;
}
public void setSugar(float sugar) {
this.sugar = sugar;
}
}
public class stFoodInfoPagodaAPPVO implements Serializable {
private double oil;
private double salt;
private double meat;
private double vegetable;
private double fruits;
private double grain;
private double soya;
private double sugar;
public double getOil() {
return oil;
}
public void setOil(double oil) {
this.oil = oil;
}
public double getSalt() {
return salt;
}
public void setSalt(double salt) {
this.salt = salt;
}
public double getMeat() {
return meat;
}
public void setMeat(double meat) {
this.meat = meat;
}
public double getVegetable() {
return vegetable;
}
public void setVegetable(double vegetable) {
this.vegetable = vegetable;
}
public double getFruits() {
return fruits;
}
public void setFruits(double fruits) {
this.fruits = fruits;
}
public double getGrain() {
return grain;
}
public void setGrain(double grain) {
this.grain = grain;
}
public double getSoya() {
return soya;
}
public void setSoya(double soya) {
this.soya = soya;
}
public double getSugar() {
return sugar;
}
public void setSugar(double sugar) {
this.sugar = sugar;
}
}
public class stFoodInfoSetting {
private int addFoodWeight;
private boolean tablewareStatus;
private int tablewareWeight;
public int getAddFoodWeight() {
return addFoodWeight;
}
public void setAddFoodWeight(int addFoodWeight) {
this.addFoodWeight = addFoodWeight;
}
public boolean isTablewareStatus() {
return tablewareStatus;
}
public void setTablewareStatus(boolean tablewareStatus) {
this.tablewareStatus = tablewareStatus;
}
public int getTablewareWeight() {
return tablewareWeight;
}
public void setTablewareWeight(int tablewareWeight) {
this.tablewareWeight = tablewareWeight;
}
}
}
@@ -0,0 +1,277 @@
package com.sw.st.model;
import java.io.Serializable;
public class MealRecordsInfo implements Serializable {
private NeedEnergyVo needEnergyVo;
private foodExtInfoVo foodExtInfoVo;
private float totalWeight;
public void setNeedEnergyVo(NeedEnergyVo needEnergyVo) {
this.needEnergyVo = needEnergyVo;
}
public NeedEnergyVo getNeedEnergyVo() {
return needEnergyVo;
}
public MealRecordsInfo.foodExtInfoVo getFoodExtInfoVo() {
return foodExtInfoVo;
}
public void setFoodExtInfoVo(MealRecordsInfo.foodExtInfoVo foodExtInfoVo) {
this.foodExtInfoVo = foodExtInfoVo;
}
public float getTotalWeight() {
return totalWeight;
}
public void setTotalWeight(float totalWeight) {
this.totalWeight = totalWeight;
}
public class foodExtInfoVo implements Serializable {
private float energyKcal;
private float protein;
private float fat;
private float cho;
public float getEnergyKcal() {
return energyKcal;
}
public void setEnergyKcal(float energyKcal) {
this.energyKcal = energyKcal;
}
public float getProtein() {
return protein;
}
public void setProtein(float protein) {
this.protein = protein;
}
public float getFat() {
return fat;
}
public void setFat(float fat) {
this.fat = fat;
}
public float getCho() {
return cho;
}
public void setCho(float cho) {
this.cho = cho;
}
}
public class NeedEnergyVo implements Serializable {
private double bmi;
private int energy;
private String min;
private String max;
private float dinner1Min;
private float dinner1Max;
private float dinner2Min;
private float dinner2Max;
private float dinner3Min;
private float dinner3Max;
private double proteinMin;
private double proteinMax;
private double fatMin;
private double fatMax;
private double choMin;
private double choMax;
private double proteinMinKcal;
private double proteinMaxKcal;
private double fatMinKcal;
private double fatMaxKcal;
private double choMinKcal;
private double choMaxKcal;
public void setBmi(double bmi) {
this.bmi = bmi;
}
public double getBmi() {
return bmi;
}
public void setEnergy(int energy) {
this.energy = energy;
}
public int getEnergy() {
return energy;
}
public void setMin(String min) {
this.min = min;
}
public String getMin() {
return min;
}
public void setMax(String max) {
this.max = max;
}
public String getMax() {
return max;
}
public void setDinner1Min(float dinner1Min) {
this.dinner1Min = dinner1Min;
}
public float getDinner1Min() {
return dinner1Min;
}
public void setDinner1Max(float dinner1Max) {
this.dinner1Max = dinner1Max;
}
public float getDinner1Max() {
return dinner1Max;
}
public void setDinner2Min(float dinner2Min) {
this.dinner2Min = dinner2Min;
}
public float getDinner2Min() {
return dinner2Min;
}
public void setDinner2Max(float dinner2Max) {
this.dinner2Max = dinner2Max;
}
public float getDinner2Max() {
return dinner2Max;
}
public void setDinner3Min(float dinner3Min) {
this.dinner3Min = dinner3Min;
}
public float getDinner3Min() {
return dinner3Min;
}
public void setDinner3Max(float dinner3Max) {
this.dinner3Max = dinner3Max;
}
public float getDinner3Max() {
return dinner3Max;
}
public void setProteinMin(double proteinMin) {
this.proteinMin = proteinMin;
}
public double getProteinMin() {
return proteinMin;
}
public void setProteinMax(double proteinMax) {
this.proteinMax = proteinMax;
}
public double getProteinMax() {
return proteinMax;
}
public void setFatMin(double fatMin) {
this.fatMin = fatMin;
}
public double getFatMin() {
return fatMin;
}
public void setFatMax(double fatMax) {
this.fatMax = fatMax;
}
public double getFatMax() {
return fatMax;
}
public void setChoMin(double choMin) {
this.choMin = choMin;
}
public double getChoMin() {
return choMin;
}
public void setChoMax(double choMax) {
this.choMax = choMax;
}
public double getChoMax() {
return choMax;
}
public void setProteinMinKcal(double proteinMinKcal) {
this.proteinMinKcal = proteinMinKcal;
}
public double getProteinMinKcal() {
return proteinMinKcal;
}
public void setProteinMaxKcal(double proteinMaxKcal) {
this.proteinMaxKcal = proteinMaxKcal;
}
public double getProteinMaxKcal() {
return proteinMaxKcal;
}
public void setFatMinKcal(double fatMinKcal) {
this.fatMinKcal = fatMinKcal;
}
public double getFatMinKcal() {
return fatMinKcal;
}
public void setFatMaxKcal(double fatMaxKcal) {
this.fatMaxKcal = fatMaxKcal;
}
public double getFatMaxKcal() {
return fatMaxKcal;
}
public void setChoMinKcal(double choMinKcal) {
this.choMinKcal = choMinKcal;
}
public double getChoMinKcal() {
return choMinKcal;
}
public void setChoMaxKcal(double choMaxKcal) {
this.choMaxKcal = choMaxKcal;
}
public double getChoMaxKcal() {
return choMaxKcal;
}
}
}
@@ -0,0 +1,44 @@
package com.sw.st.model;
import java.io.Serializable;
public class MessageEvent implements Serializable {
public static final int MESSAGE_UPDATE_FOOD = 1;
public static final int MESSAGE_EVENT_ZERO = 2;//完成清零
public static final int MESSAGE_WEIGHT_INFO = 3;//重量信息
private int type;
private int weight;
private String message;
public MessageEvent(int type, String message) {
this.type = type;
this.message = message;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
@@ -0,0 +1,217 @@
package com.sw.st.model;
import java.io.Serializable;
import java.util.List;
public class NewFoodInfoModel implements Serializable {
private String id;
private String foodName;
private String img;
private List<String> labList;
private double price;
private double vipPrice;
private int priceUnit;
private List<String> diseaseList;
private float energyKcal;
private double cho;
private double fat;
private double protein;
private String mainIngredientList;
private String assistIngredientList;
private String seasoningList;
private int tablewareWeight;
private double meal;
private double vegetable;
private double fruits;
private double grain;
private double mixedBeans;
private double soyaNew;
private boolean isSelect = false;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getTablewareWeight() {
return tablewareWeight;
}
public void setTablewareWeight(int tablewareWeight) {
this.tablewareWeight = tablewareWeight;
}
public String getFoodName() {
return foodName;
}
public void setFoodName(String foodName) {
this.foodName = foodName;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public List<String> getLabList() {
return labList;
}
public void setLabList(List<String> labList) {
this.labList = labList;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public double getVipPrice() {
return vipPrice;
}
public void setVipPrice(double vipPrice) {
this.vipPrice = vipPrice;
}
public int getPriceUnit() {
return priceUnit;
}
public void setPriceUnit(int priceUnit) {
this.priceUnit = priceUnit;
}
public List<String> getDiseaseList() {
return diseaseList;
}
public void setDiseaseList(List<String> diseaseList) {
this.diseaseList = diseaseList;
}
public float getEnergyKcal() {
return energyKcal;
}
public void setEnergyKcal(float energyKcal) {
this.energyKcal = energyKcal;
}
public double getCho() {
return cho;
}
public void setCho(double cho) {
this.cho = cho;
}
public double getFat() {
return fat;
}
public void setFat(double fat) {
this.fat = fat;
}
public double getProtein() {
return protein;
}
public void setProtein(double protein) {
this.protein = protein;
}
public String getMainIngredientList() {
return mainIngredientList;
}
public void setMainIngredientList(String mainIngredientList) {
this.mainIngredientList = mainIngredientList;
}
public String getAssistIngredientList() {
return assistIngredientList;
}
public void setAssistIngredientList(String assistIngredientList) {
this.assistIngredientList = assistIngredientList;
}
public String getSeasoningList() {
return seasoningList;
}
public void setSeasoningList(String seasoningList) {
this.seasoningList = seasoningList;
}
public double getMeal() {
return meal;
}
public void setMeal(double meal) {
this.meal = meal;
}
public double getVegetable() {
return vegetable;
}
public void setVegetable(double vegetable) {
this.vegetable = vegetable;
}
public double getFruits() {
return fruits;
}
public void setFruits(double fruits) {
this.fruits = fruits;
}
public double getGrain() {
return grain;
}
public void setGrain(double grain) {
this.grain = grain;
}
public double getMixedBeans() {
return mixedBeans;
}
public void setMixedBeans(double mixedBeans) {
this.mixedBeans = mixedBeans;
}
public double getSoyaNew() {
return soyaNew;
}
public void setSoyaNew(double soyaNew) {
this.soyaNew = soyaNew;
}
public boolean isSelect() {
return isSelect;
}
public void setSelect(boolean select) {
isSelect = select;
}
}
@@ -0,0 +1,40 @@
package com.sw.st.model;
public class RecommendValueModel {
private String heat;
private String main;
private String fruits;
private String meatAndEggs;
public String getHeat() {
return heat;
}
public void setHeat(String heat) {
this.heat = heat;
}
public String getMain() {
return main;
}
public void setMain(String main) {
this.main = main;
}
public String getFruits() {
return fruits;
}
public void setFruits(String fruits) {
this.fruits = fruits;
}
public String getMeatAndEggs() {
return meatAndEggs;
}
public void setMeatAndEggs(String meatAndEggs) {
this.meatAndEggs = meatAndEggs;
}
}
@@ -0,0 +1,54 @@
package com.sw.st.model;
import java.io.Serializable;
public class ResponseData<T> implements Serializable {
private static final long serialVersionUID = 5213230387175987834L;
/**
* respCode : -1
* ok : false
* message : 食堂编码不存在
*/
private int code;
private boolean success;
private String msg;
private T data;
public static long getSerialVersionUID() {
return serialVersionUID;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
@@ -0,0 +1,78 @@
package com.sw.st.model;
import java.io.Serializable;
public class ScalesFoodList implements Serializable {
private String userFoodIds;
private String foodId;
private String foodName;
private float price;
private float vipPrice;
private float priceSum;
private float vipPriceSum;
private int foodWeight;
public String getUserFoodIds() {
return userFoodIds;
}
public void setUserFoodIds(String userFoodIds) {
this.userFoodIds = userFoodIds;
}
public String getFoodId() {
return foodId;
}
public void setFoodId(String foodId) {
this.foodId = foodId;
}
public String getFoodName() {
return foodName;
}
public void setFoodName(String foodName) {
this.foodName = foodName;
}
public float getVipPrice() {
return vipPrice;
}
public void setVipPrice(float vipPrice) {
this.vipPrice = vipPrice;
}
public float getPriceSum() {
return priceSum;
}
public void setPriceSum(float priceSum) {
this.priceSum = priceSum;
}
public float getVipPriceSum() {
return vipPriceSum;
}
public void setVipPriceSum(float vipPriceSum) {
this.vipPriceSum = vipPriceSum;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public int getFoodWeight() {
return foodWeight;
}
public void setFoodWeight(int foodWeight) {
this.foodWeight = foodWeight;
}
}
@@ -0,0 +1,33 @@
package com.sw.st.model;
import java.io.Serializable;
public class UserFaceModel implements Serializable {
String userFaceId;
String userId;
String faceFeature;
public String getUserFaceId() {
return userFaceId;
}
public void setUserFaceId(String userFaceId) {
this.userFaceId = userFaceId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getFaceFeature() {
return faceFeature;
}
public void setFaceFeature(String faceFeature) {
this.faceFeature = faceFeature;
}
}
@@ -0,0 +1,88 @@
package com.sw.st.model;
import java.io.Serializable;
public class UserInfo implements Serializable {
private String userId;
private String secondDepartId;
private String secondDepartName;
private String thirdDepartId;
private String thirdDepartName;
private String realname;
private String empIdcard;
private String mobilePhone;
private String token;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getSecondDepartId() {
return secondDepartId;
}
public void setSecondDepartId(String secondDepartId) {
this.secondDepartId = secondDepartId;
}
public String getSecondDepartName() {
return secondDepartName;
}
public void setSecondDepartName(String secondDepartName) {
this.secondDepartName = secondDepartName;
}
public String getThirdDepartId() {
return thirdDepartId;
}
public void setThirdDepartId(String thirdDepartId) {
this.thirdDepartId = thirdDepartId;
}
public String getThirdDepartName() {
return thirdDepartName;
}
public void setThirdDepartName(String thirdDepartName) {
this.thirdDepartName = thirdDepartName;
}
public String getRealname() {
return realname;
}
public void setRealname(String realname) {
this.realname = realname;
}
public String getEmpIdcard() {
return empIdcard;
}
public void setEmpIdcard(String empIdcard) {
this.empIdcard = empIdcard;
}
public String getMobilePhone() {
return mobilePhone;
}
public void setMobilePhone(String mobilePhone) {
this.mobilePhone = mobilePhone;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
@@ -0,0 +1,6 @@
package com.sw.st.model;
public class UserModel {
}
@@ -0,0 +1,105 @@
package com.sw.st.model;
import java.io.Serializable;
public class UserNutritionInfo implements Serializable {
private int recommendMax;
private int recommendMin;
private float foodWeight;
private int foodNum;
private float water;
private float energyKcal;
private float protein;
private float fat;
private float cho;
private float dietFiber;
private float na;
public int getRecommendMax() {
return recommendMax;
}
public void setRecommendMax(int recommendMax) {
this.recommendMax = recommendMax;
}
public int getRecommendMin() {
return recommendMin;
}
public void setRecommendMin(int recommendMin) {
this.recommendMin = recommendMin;
}
public float getFoodWeight() {
return foodWeight;
}
public void setFoodWeight(float foodWeight) {
this.foodWeight = foodWeight;
}
public int getFoodNum() {
return foodNum;
}
public void setFoodNum(int foodNum) {
this.foodNum = foodNum;
}
public float getWater() {
return water;
}
public void setWater(float water) {
this.water = water;
}
public float getEnergyKcal() {
return energyKcal;
}
public void setEnergyKcal(float energyKcal) {
this.energyKcal = energyKcal;
}
public float getProtein() {
return protein;
}
public void setProtein(float protein) {
this.protein = protein;
}
public float getFat() {
return fat;
}
public void setFat(float fat) {
this.fat = fat;
}
public float getCho() {
return cho;
}
public void setCho(float cho) {
this.cho = cho;
}
public float getDietFiber() {
return dietFiber;
}
public void setDietFiber(float dietFiber) {
this.dietFiber = dietFiber;
}
public float getNa() {
return na;
}
public void setNa(float na) {
this.na = na;
}
}
@@ -0,0 +1,172 @@
package com.sw.st.model;
import java.io.Serializable;
import java.util.ArrayList;
public class UserNutritionModel implements Serializable {
private float cho;
private float fat;
private float foodWeight;
private float fruits;
private String fruitsRecommend;
private float grain;
private String grainRecommend;
private float heatKcal;
private float meal;
private String mealRecommend;
private float price;
private float protein;
private float vegetable;
private String vegetableRecommend;
private float vipPrice;
private float soyaNew;
private float mixedBeans;
private ArrayList<ScalesFoodList> scalesFoodOrderListVOList;
public float getCho() {
return cho;
}
public void setCho(float cho) {
this.cho = cho;
}
public float getFat() {
return fat;
}
public void setFat(float fat) {
this.fat = fat;
}
public float getFoodWeight() {
return foodWeight;
}
public void setFoodWeight(float foodWeight) {
this.foodWeight = foodWeight;
}
public float getFruits() {
return fruits;
}
public void setFruits(float fruits) {
this.fruits = fruits;
}
public String getFruitsRecommend() {
return fruitsRecommend;
}
public void setFruitsRecommend(String fruitsRecommend) {
this.fruitsRecommend = fruitsRecommend;
}
public float getGrain() {
return grain;
}
public void setGrain(float grain) {
this.grain = grain;
}
public String getGrainRecommend() {
return grainRecommend;
}
public void setGrainRecommend(String grainRecommend) {
this.grainRecommend = grainRecommend;
}
public float getHeatKcal() {
return heatKcal;
}
public void setHeatKcal(float heatKcal) {
this.heatKcal = heatKcal;
}
public float getMeal() {
return meal;
}
public void setMeal(float meal) {
this.meal = meal;
}
public String getMealRecommend() {
return mealRecommend;
}
public void setMealRecommend(String mealRecommend) {
this.mealRecommend = mealRecommend;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public float getProtein() {
return protein;
}
public void setProtein(float protein) {
this.protein = protein;
}
public float getVegetable() {
return vegetable;
}
public void setVegetable(float vegetable) {
this.vegetable = vegetable;
}
public String getVegetableRecommend() {
return vegetableRecommend;
}
public void setVegetableRecommend(String vegetableRecommend) {
this.vegetableRecommend = vegetableRecommend;
}
public float getSoyaNew() {
return soyaNew;
}
public void setSoyaNew(float soyaNew) {
this.soyaNew = soyaNew;
}
public float getMixedBeans() {
return mixedBeans;
}
public void setMixedBeans(float mixedBeans) {
this.mixedBeans = mixedBeans;
}
public float getVipPrice() {
return vipPrice;
}
public void setVipPrice(float vipPrice) {
this.vipPrice = vipPrice;
}
public ArrayList<ScalesFoodList> getScalesFoodOrderListVOList() {
return scalesFoodOrderListVOList;
}
public void setScalesFoodOrderListVOList(ArrayList<ScalesFoodList> scalesFoodOrderListVOList) {
this.scalesFoodOrderListVOList = scalesFoodOrderListVOList;
}
}
@@ -0,0 +1,40 @@
package com.sw.st.model;
public class WeightModel {
private String uuid;
private String ip;
private int weight;
private String skin;
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public String getSkin() {
return skin;
}
public void setSkin(String skin) {
this.skin = skin;
}
}
@@ -0,0 +1,68 @@
package com.sw.st.net;
import android.content.Context;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.RequestOptions;
import com.sw.st.R;
import java.io.File;
/**
* 图片加载管理
*/
public class ImageLoaderManager {
public static void LoadRoundImage(Context context, String imgUrl, ImageView imageView, int roundingRadius) {
RequestOptions cropOptions = new RequestOptions();
cropOptions.transform(new RoundedCorners(roundingRadius));//new CenterCrop()
Glide.with(context)
.load(imgUrl)
.placeholder(R.mipmap.ic_launcher)
.dontAnimate() //解决圆形图显示占位图问题
.error(R.mipmap.ic_launcher)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.apply(cropOptions)
.into(imageView);
}
public static void LoadImage(Context context, String imgUrl, ImageView imageView) {
Glide.with(context)
.load(imgUrl)
.placeholder(R.mipmap.ic_launcher)
.dontAnimate() //解决圆形图显示占位图问题
.error(R.mipmap.ic_launcher)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imageView);
// Glide
// .with(myFragment)
// .load(url)
// .centerCrop()
// .placeholder(R.drawable.loading_spinner)
// .into(myImageView);
}
/**
* 缓存图片到本地
*/
public static File CacheFile(Context context, String imgUrl) {
File cacheFile = null;
FutureTarget<File> future = Glide.with(context)
.load(imgUrl)
.downloadOnly(500, 500);
try {
cacheFile = future.get();
} catch (Exception e) {
e.printStackTrace();
}
return cacheFile;
}
}
@@ -0,0 +1,54 @@
package com.sw.st.net;
import androidx.annotation.Nullable;
import com.sw.st.utils.L;
import org.jetbrains.annotations.NotNull;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;
public abstract class WsListener extends WebSocketListener {
public abstract void onWsDataChanged(String text);
@Override
public void onClosed(@NotNull WebSocket webSocket, int code, @NotNull String reason) {
super.onClosed(webSocket, code, reason);
}
@Override
public void onClosing(@NotNull WebSocket webSocket, int code, @NotNull String reason) {
super.onClosing(webSocket, code, reason);
}
@Override
public void onFailure(@NotNull WebSocket webSocket, @NotNull Throwable t, @Nullable Response response) {
super.onFailure(webSocket, t, response);
}
@Override
public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {
super.onMessage(webSocket, text);
L.e("客户端收到消息:" + text);
onWsDataChanged(text);
//测试发消息
webSocket.send("我是客户端,你好啊");
}
@Override
public void onMessage(@NotNull WebSocket webSocket, @NotNull ByteString bytes) {
super.onMessage(webSocket, bytes);
}
@Override
public void onOpen(@NotNull WebSocket webSocket, @NotNull Response response) {
super.onOpen(webSocket, response);
L.e("连接成功!");
}
}
@@ -0,0 +1,73 @@
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sw.st.net.helper;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.google.gson.stream.JsonReader;
import java.io.Reader;
import java.lang.reflect.Type;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:16/9/28
* 描 述: Gson 数据转换工具类
* 修订历史:
* ================================================
*/
public class Convert {
private static Gson create() {
return GsonHolder.gson;
}
private static class GsonHolder {
private static Gson gson = new Gson();
}
public static <T> T fromJson(String json, Class<T> type) throws JsonIOException, JsonSyntaxException {
return create().fromJson(json, type);
}
public static <T> T fromJson(String json, Type type) {
return create().fromJson(json, type);
}
public static <T> T fromJson(JsonReader reader, Type typeOfT) throws JsonIOException, JsonSyntaxException {
return create().fromJson(reader, typeOfT);
}
public static <T> T fromJson(Reader json, Class<T> classOfT) throws JsonSyntaxException, JsonIOException {
return create().fromJson(json, classOfT);
}
public static <T> T fromJson(Reader json, Type typeOfT) throws JsonIOException, JsonSyntaxException {
return create().fromJson(json, typeOfT);
}
public static String toJson(Object src) {
return create().toJson(src);
}
public static String toJson(Object src, Type typeOfSrc) {
return create().toJson(src, typeOfSrc);
}
}
@@ -0,0 +1,165 @@
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sw.st.net.helper;
import com.google.gson.stream.JsonReader;
import com.lzy.okgo.convert.Converter;
import org.json.JSONArray;
import org.json.JSONObject;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import okhttp3.Response;
import okhttp3.ResponseBody;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:16/9/11
* 描 述:
* 修订历史:
* ================================================
*/
public class JsonConvert<T> implements Converter<T> {
private Type type;
private Class<T> clazz;
public JsonConvert() {
}
public JsonConvert(Type type) {
this.type = type;
}
public JsonConvert(Class<T> clazz) {
this.clazz = clazz;
}
/**
* 该方法是子线程处理,不能做ui相关的工作
* 主要作用是解析网络返回的 response 对象,生成onSuccess回调中需要的数据对象
* 这里的解析工作不同的业务逻辑基本都不一样,所以需要自己实现,以下给出的时模板代码,实际使用根据需要修改
*/
@Override
public T convertResponse(Response response) throws Throwable {
// 重要的事情说三遍,不同的业务,这里的代码逻辑都不一样,如果你不修改,那么基本不可用
// 重要的事情说三遍,不同的业务,这里的代码逻辑都不一样,如果你不修改,那么基本不可用
// 重要的事情说三遍,不同的业务,这里的代码逻辑都不一样,如果你不修改,那么基本不可用
// 如果你对这里的代码原理不清楚,可以看这里的详细原理说明: https://github.com/jeasonlzy/okhttp-OkGo/wiki/JsonCallback
// 如果你对这里的代码原理不清楚,可以看这里的详细原理说明: https://github.com/jeasonlzy/okhttp-OkGo/wiki/JsonCallback
// 如果你对这里的代码原理不清楚,可以看这里的详细原理说明: https://github.com/jeasonlzy/okhttp-OkGo/wiki/JsonCallback
if (type == null) {
if (clazz == null) {
// 如果没有通过构造函数传进来,就自动解析父类泛型的真实类型(有局限性,继承后就无法解析到)
Type genType = getClass().getGenericSuperclass();
type = ((ParameterizedType) genType).getActualTypeArguments()[0];
} else {
return parseClass(response, clazz);
}
}
if (type instanceof ParameterizedType) {
return parseParameterizedType(response, (ParameterizedType) type);
} else if (type instanceof Class) {
return parseClass(response, (Class<?>) type);
} else {
return parseType(response, type);
}
}
private T parseClass(Response response, Class<?> rawType) throws Exception {
if (rawType == null) return null;
ResponseBody body = response.body();
if (body == null) return null;
JsonReader jsonReader = new JsonReader(body.charStream());
if (rawType == String.class) {
//noinspection unchecked
return (T) body.string();
} else if (rawType == JSONObject.class) {
//noinspection unchecked
return (T) new JSONObject(body.string());
} else if (rawType == JSONArray.class) {
//noinspection unchecked
return (T) new JSONArray(body.string());
} else {
T t = Convert.fromJson(jsonReader, rawType);
response.close();
return t;
}
}
private T parseType(Response response, Type type) throws Exception {
if (type == null) return null;
ResponseBody body = response.body();
if (body == null) return null;
JsonReader jsonReader = new JsonReader(body.charStream());
// 泛型格式如下: new JsonCallback<任意JavaBean>(this)
T t = Convert.fromJson(jsonReader, type);
response.close();
return t;
}
private T parseParameterizedType(Response response, ParameterizedType type) throws Exception {
if (type == null) return null;
ResponseBody body = response.body();
if (body == null) return null;
JsonReader jsonReader = new JsonReader(body.charStream());
Type rawType = type.getRawType(); // 泛型的实际类型
Type typeArgument = type.getActualTypeArguments()[0]; // 泛型的参数
if (rawType != LzyResponse.class) {
// 泛型格式如下: new JsonCallback<外层BaseBean<内层JavaBean>>(this)
T t = Convert.fromJson(jsonReader, type);
response.close();
return t;
} else {
if (typeArgument == Void.class) {
// 泛型格式如下: new JsonCallback<LzyResponse<Void>>(this)
SimpleResponse simpleResponse = Convert.fromJson(jsonReader, SimpleResponse.class);
response.close();
//noinspection unchecked
return (T) simpleResponse.toLzyResponse();
} else {
// 泛型格式如下: new JsonCallback<LzyResponse<内层JavaBean>>(this)
LzyResponse lzyResponse = Convert.fromJson(jsonReader, type);
response.close();
int code = lzyResponse.code;
//这里的0是以下意思
//一般来说服务器会和客户端约定一个数表示成功,其余的表示失败,这里根据实际情况修改
if (code == 0) {
//noinspection unchecked
return (T) lzyResponse;
} else if (code == 104) {
throw new IllegalStateException("用户授权信息无效");
} else if (code == 105) {
throw new IllegalStateException("用户收取信息已过期");
} else {
//直接将服务端的错误信息抛出,onError中可以获取
throw new IllegalStateException("错误代码:" + code + ",错误信息:" + lzyResponse.msg);
}
}
}
}
}
@@ -0,0 +1,45 @@
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sw.st.net.helper;
import java.io.Serializable;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:16/9/28
* 描 述:
* 修订历史:
* ================================================
*/
public class LzyResponse<T> implements Serializable {
private static final long serialVersionUID = 5213230387175987834L;
public int code;
public String msg;
public T data;
@Override
public String toString() {
return "LzyResponse{\n" +//
"\tcode=" + code + "\n" +//
"\tmsg='" + msg + "\'\n" +//
"\tdata=" + data + "\n" +//
'}';
}
}
@@ -0,0 +1,42 @@
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sw.st.net.helper;
import java.io.Serializable;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:16/9/28
* 描 述:
* 修订历史:
* ================================================
*/
public class SimpleResponse implements Serializable {
private static final long serialVersionUID = -1477609349345966116L;
public int code;
public String msg;
public LzyResponse toLzyResponse() {
LzyResponse lzyResponse = new LzyResponse();
lzyResponse.code = code;
lzyResponse.msg = msg;
return lzyResponse;
}
}
@@ -0,0 +1,95 @@
package com.sw.st.net.helper.interceptor;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.nio.charset.Charset;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
/**
* userlqm
* desctoken验证令牌失效拦截器,token过期时刷新token或弹dialog跳转到登录界面
* src:https://www.jianshu.com/p/62ab11ddacc8
*/
public class TokenInterceptor implements Interceptor {
private static final Charset UTF8 = Charset.forName("UTF-8");
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// try the request
Response originalResponse = chain.proceed(request);
/**通过如下的办法曲线取到请求完成的数据
*
* 原本想通过 originalResponse.body().string()
* 去取到请求完成的数据,但是一直报错,不知道是okhttp的bug还是操作不当
*
* 然后去看了okhttp的源码,找到了这个曲线方法,取到请求完成的数据后,根据特定的判断条件去判断token过期
*/
ResponseBody responseBody = originalResponse.body();
BufferedSource source = responseBody.source();
source.request(Long.MAX_VALUE); // Buffer the entire body.
Buffer buffer = source.buffer();
Charset charset = UTF8;
MediaType contentType = responseBody.contentType();
if (contentType != null) {
charset = contentType.charset(UTF8);
}
String bodyString = buffer.clone().readString(charset);
Log.d("body---------->", bodyString);
/***************************************/
JSONObject extrasJson = null;
try {
if (extrasJson == null){
extrasJson = new JSONObject(bodyString);
}
} catch (JSONException e) {
e.printStackTrace();
}
int code = Integer.parseInt(extrasJson.optString("errorCode")); //根据后台返回数据执行修改
// if (response shows expired token){//根据和服务端的约定判断token过期
if (code == 401){ //假设服务端返回码401为token过期
// TODO 弹出全局的dialog或者用以下代码刷新token (全局dialog可以用WindowManager相应实现)
//取出本地的refreshToken
String refreshToken = "sssgr122222222";
// 通过一个特定的接口获取新的token,此处要用到同步的retrofit请求
// ApiService service = ServiceManager.getService(ApiService.class);
// Call<String> call = service.refreshToken(refreshToken);
//要用retrofit的同步方式
// String newToken = call.execute().body();
String newToken = "sssssssss ne wtoken";
// create a new request and modify it accordingly using the new token
Request newRequest = request.newBuilder().header("token", newToken)
.build();
// retry the request
originalResponse.body().close();
return chain.proceed(newRequest);
}
// otherwise just pass the original response on
return originalResponse;
}
}
@@ -0,0 +1,48 @@
package com.sw.st.net.helper.rxjavahelper;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
/**
* 自己的Observer,减少实现不必要的回调
*/
public abstract class RxObserver<T> implements Observer<T> {
@Override
public void onSubscribe(Disposable d) {
_onSubscribe(d);
}
@Override
public void onNext(T t) {
_onNext(t);
}
@Override
public void onError(Throwable e) {
_onError(e.getMessage());
}
@Override
public void onComplete() {
_onComplete();
}
public void _onSubscribe(Disposable d) {
}
public void _onComplete() {
}
//抽象方法,必须实现
public abstract void _onNext(T t);
public abstract void _onError(String errorMessage);
}
@@ -0,0 +1,73 @@
package com.sw.st.net.helper.rxjavahelper;
import com.sw.st.model.ResponseData;
import org.jetbrains.annotations.NotNull;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.functions.Function;
/**
* 服务器的返回的数据格式一般都是一致的,所有我们每个网络请求都可以使
* 用compose(RxResultHelper.handleResult())来处理服务器返回,一般服务器返回成功码为200,
* 相应改一下返回码的判断就行了
*/
public class RxResultHelper {
private static final int RESPONSE_SUCCESS_CODE = 200; //大部分为200
private static final int RESPONSE_ERROR_CODE = -1;
public static <T> ObservableTransformer<ResponseData<T>, T> handleResult() {
return new ObservableTransformer<ResponseData<T>, T>() {
@Override
public ObservableSource<T> apply(Observable<ResponseData<T>> tObservable) {
return tObservable.flatMap(
new Function<ResponseData<T>, Observable<T>>() {
@Override
public Observable<T> apply(ResponseData<T> tResponseData) {
//可以相应更改
if (tResponseData.getCode() == RESPONSE_SUCCESS_CODE) {
return Observable.just(tResponseData.getData());
} else if (tResponseData.getCode() == RESPONSE_ERROR_CODE) {
return Observable.error(new Exception(tResponseData.getMsg()));
} else {
return Observable.empty();
}
}
}
);
}
};
}
/**
* 返回原始json
*
* @return
*/
public static ObservableTransformer<String, String> handleJsonResponse() {
return new ObservableTransformer<String, String>() {
@NotNull
@Override
public ObservableSource<String> apply(@NotNull Observable<String> tObservable) {
return tObservable.flatMap(
new Function<String, Observable<String>>() {
@Override
public Observable<String> apply(@NotNull String tResponseData) throws Exception {
//可以相应更改
return Observable.just(tResponseData);
}
}
);
}
};
}
}
@@ -0,0 +1,29 @@
package com.sw.st.net.helper.rxjavahelper;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
/**
* compose()里接收一个Transformer对象,ObservableTransformer
* 可以通过它将一种类型的Observable转换成另一种类型的Observable。
* 现在.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread())
* 的地方可以用.compose(RxSchedulersHelper.io_main())代替。
*/
public class RxSchedulersHelper {
public static <T> ObservableTransformer<T, T> io_main() {
return new ObservableTransformer<T, T>() {
@Override
public ObservableSource<T> apply(Observable<T> upstream) {
return upstream
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
};
}
}
@@ -0,0 +1,158 @@
package com.sw.st.ui.addfood;
import static com.sw.st.ui.setting.FoodSettingActivity.CURRENT_FOOD_DATA;
import static com.sw.st.ui.setting.FoodSettingActivity.REST_NUM;
import android.view.View;
import android.widget.TextView;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.BarHide;
import com.gyf.immersionbar.ImmersionBar;
import com.sw.st.R;
import com.sw.st.base.BaseActivity;
import com.sw.st.model.FoodInfoModel;
import com.sw.st.model.MessageEvent;
import com.sw.st.net.helper.Convert;
import com.sw.st.utils.L;
import com.sw.st.utils.PrefUtils;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import butterknife.BindView;
import butterknife.OnClick;
public class AddFoodActivity extends BaseActivity<AddFoodView, AddFoodPresenter> implements AddFoodView {
@BindView(R.id.foodName)
TextView foodName;
@BindView(R.id.currentWeight)
TextView currentWeight;
@BindView(R.id.addWeight)
TextView addWeight;
private int laseWeight = 0;
private int originalWeight = 0;
private int tablewareWeight = 0;
private FoodInfoModel foodInfo;
@Override
protected int provideContentViewId() {
return R.layout.activity_add_food;
}
@Override
public void initView() {
ImmersionBar.with(this)
.hideBar(BarHide.FLAG_HIDE_BAR)
.statusBarAlpha(0f)
.statusBarDarkFont(true)
.statusBarColor(R.color.white)
.init();
laseWeight = getIntent().getIntExtra("laseWeight", 0);
currentWeight.setText(laseWeight + "");
EventBus.getDefault().register(this);
}
@Override
public void initData() {
String foodInfoStr = PrefUtils.getString(mContext, CURRENT_FOOD_DATA, "");
foodInfo = Convert.fromJson(foodInfoStr, new TypeToken<FoodInfoModel>() {
}.getType());
foodName.setText(foodInfo.getFoodName());
}
@Override
public void initListener() {
}
@OnClick({R.id.back, R.id.start})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.back:
finish();
break;
case R.id.start:
showProgress("处理中...");
int totalWeight = originalWeight - laseWeight;
mPresenter.addFoodTotalWeight(foodInfo.getId(),
2,
totalWeight,
PrefUtils.getString(mContext, REST_NUM, ""));
break;
}
}
@Override
protected AddFoodPresenter createPresenter() {
return new AddFoodPresenter();
}
@Override
protected void afterRequestPermission(int requestCode, boolean isAllGranted) {
}
@Override
public void addFoodWeightSuccess(String info) {
hideProgress();
finish();
}
@Override
public void addFoodWeightFail(String info) {
hideProgress();
finish();
}
@Override
public void showProgress(String tipString) {
showWaitingDialog(tipString);
}
@Override
public void hideProgress() {
hideWaitingDialog();
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onReceiveMsg(MessageEvent eventModel) {
switch (eventModel.getType()) {
case MessageEvent.MESSAGE_WEIGHT_INFO:
if (foodInfo == null) {
return;
}
int weight = eventModel.getWeight();
if (foodInfo.getStFoodInfoSetting() != null
&& foodInfo.getStFoodInfoSetting().isTablewareStatus()) {
tablewareWeight = foodInfo.getStFoodInfoSetting().getTablewareWeight();
originalWeight = weight - tablewareWeight;
} else {
originalWeight = weight;
}
runOnUiThread(new Runnable() {
@Override
public void run() {
int totalWeight = originalWeight - laseWeight;
addWeight.setText(totalWeight + "");
}
});
break;
}
}
}
@@ -0,0 +1,63 @@
package com.sw.st.ui.addfood;
import com.sw.st.api.SwService;
import com.sw.st.base.BasePresenter;
import com.sw.st.net.helper.rxjavahelper.RxObserver;
import com.sw.st.net.helper.rxjavahelper.RxResultHelper;
import com.sw.st.net.helper.rxjavahelper.RxSchedulersHelper;
import org.json.JSONException;
import org.json.JSONObject;
import io.reactivex.disposables.Disposable;
public class AddFoodPresenter extends BasePresenter<AddFoodView> {
/**
* @param foodId 菜品ID
* @param type 是否开餐1开餐,2加菜
* @param totalWeight 菜品增重
* @return
*/
public void addFoodTotalWeight(String foodId, int type, double totalWeight, String deviceMac) {
SwService.startMealService(foodId, type, totalWeight, deviceMac)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleJsonResponse())
.subscribe(new RxObserver<String>() {
@Override
public void _onSubscribe(Disposable d) {
}
@Override
public void _onNext(String info) {
try {
JSONObject jsonObject = new JSONObject(info);
if (jsonObject.optInt("code") == 200) {
String data = jsonObject.optString("data");
if (getView() != null)
getView().addFoodWeightSuccess(data);
} else {
getView().addFoodWeightFail(jsonObject.optString("message"));
}
} catch (JSONException e) {
e.printStackTrace();
if (getView() != null)
getView().addFoodWeightFail("数据解析异常");
}
}
@Override
public void _onError(String errorMessage) {
if (getView() != null)
getView().addFoodWeightFail(errorMessage);
}
@Override
public void _onComplete() {
}
});
}
}
@@ -0,0 +1,16 @@
package com.sw.st.ui.addfood;
import com.sw.st.base.BaseView;
import com.sw.st.ui.setting.FoodListModel;
import java.util.ArrayList;
public interface AddFoodView extends BaseView {
void addFoodWeightSuccess(String info);
void addFoodWeightFail(String info);
}
@@ -0,0 +1,96 @@
package com.sw.st.ui.device;
import java.util.Date;
public class BindDeviceModel {
private int deviceNo;
private String deviceMac;
private String deviceDesc;
private String restId;
private String restName;
private String restNo;
private String createBy;
private String createDate;
private String updateBy;
private String updateDate;
public int getDeviceNo() {
return deviceNo;
}
public void setDeviceNo(int deviceNo) {
this.deviceNo = deviceNo;
}
public String getDeviceMac() {
return deviceMac;
}
public void setDeviceMac(String deviceMac) {
this.deviceMac = deviceMac;
}
public String getDeviceDesc() {
return deviceDesc;
}
public void setDeviceDesc(String deviceDesc) {
this.deviceDesc = deviceDesc;
}
public String getRestId() {
return restId;
}
public void setRestId(String restId) {
this.restId = restId;
}
public String getRestName() {
return restName;
}
public void setRestName(String restName) {
this.restName = restName;
}
public String getRestNo() {
return restNo;
}
public void setRestNo(String restNo) {
this.restNo = restNo;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public String getCreateDate() {
return createDate;
}
public void setCreateDate(String createDate) {
this.createDate = createDate;
}
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
public String getUpdateDate() {
return updateDate;
}
public void setUpdateDate(String updateDate) {
this.updateDate = updateDate;
}
}
@@ -0,0 +1,187 @@
package com.sw.st.ui.device;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.gyf.immersionbar.BarHide;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.sw.st.R;
import com.sw.st.base.BaseActivity;
import com.sw.st.base.BasePresenter;
import com.sw.st.model.WeightModel;
import com.sw.st.net.WsListener;
import com.sw.st.utils.PrefUtils;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;
import static com.sw.st.application.AppConst.SOCKET_SERVICE_URL;
public class ChengListActivity extends BaseActivity {
private final String CHENG_IP = "cheng_ip";
@BindView(R.id.title_name_tv)
TextView titleName;
@BindView(R.id.refreshLayout)
SmartRefreshLayout refreshLayout;
@BindView(R.id.recyclerView_content)
RecyclerView recyclerView;
private ChengListAdapter chengListAdapter;
private OkHttpClient mClient;
private WebSocket mWebSocket;
private Handler handler;
@Override
protected int provideContentViewId() {
return R.layout.activity_cheng_list;
}
@Override
public void initView() {
ImmersionBar.with(this)
.hideBar(BarHide.FLAG_HIDE_BAR)
.statusBarAlpha(0f)
.statusBarDarkFont(true)
.statusBarColor(R.color.white)
.init();
titleName.setText("请选择");
refreshLayout.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh(@NonNull RefreshLayout refreshLayout) {
send("refreshChengs");
}
});
refreshLayout.setEnableLoadMore(false);
chengListAdapter = new ChengListAdapter(chengDataList, ChengListActivity.this);
recyclerView.setAdapter(chengListAdapter);
}
private ArrayList<WeightModel> chengDataList = new ArrayList<>();
@Override
public void initData() {
initWebSocket();
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1://返回socket数据
refreshLayout.finishRefresh();
chengDataList.clear();
String msgStr = msg.obj.toString();
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray Jarray = parser.parse(msgStr).getAsJsonArray();
for (JsonElement obj : Jarray) {
WeightModel cse = gson.fromJson(obj, WeightModel.class);
chengDataList.add(cse);
}
chengListAdapter.notifyDataSetChanged();
break;
}
}
};
}
@Override
public void initListener() {
chengListAdapter.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
PrefUtils.setString(ChengListActivity.this, CHENG_IP, chengDataList.get(position).getIp());
finish();
}
});
}
@OnClick({R.id.title_back_iv})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.title_back_iv:
finish();
break;
}
}
//初始化WebSocket
public void initWebSocket() {
mClient = new OkHttpClient.Builder()
.readTimeout(10, TimeUnit.SECONDS)//设置读取超时时间
.writeTimeout(10, TimeUnit.SECONDS)//设置写的超时时间
.connectTimeout(10, TimeUnit.SECONDS)//设置连接超时时间
.build();
Request request = new Request.Builder()
.url(SOCKET_SERVICE_URL)
.build();
mWebSocket = mClient.newWebSocket(request, new WsListener() {
@Override
public void onWsDataChanged(String text) {
Message message = new Message();
message.what = 1;
message.obj = text;
handler.sendMessage(message);
}
});
send("refreshChengs");
}
//发送String消息
public void send(final String message) {
if (mWebSocket != null) {
mWebSocket.send(message);
}
}
//主动断开连接
public void disconnect(int code, String reason) {
if (mWebSocket != null)
mWebSocket.close(code, reason);
}
@Override
protected BasePresenter createPresenter() {
return null;
}
@Override
protected void afterRequestPermission(int requestCode, boolean isAllGranted) {
}
@Override
protected void onDestroy() {
super.onDestroy();
disconnect(1001, null);
}
}
@@ -0,0 +1,33 @@
package com.sw.st.ui.device;
import android.content.Context;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.sw.st.R;
import com.sw.st.model.WeightModel;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public class ChengListAdapter extends BaseQuickAdapter<WeightModel, BaseViewHolder> {
Context context;
public ChengListAdapter(@Nullable List<WeightModel> listModels, Context context) {
super(R.layout.item_cheng, listModels);
this.context = context;
addChildClickViewIds(R.id.item_cheng_open_com, R.id.item_cheng_close_com);
}
@Override
protected void convert(@NotNull BaseViewHolder baseViewHolder, WeightModel weightModel) {
baseViewHolder.setText(R.id.item_cheng_ip, "COM" + weightModel.getIp());
// baseViewHolder.setText(R.id.item_cheng_weight, "重量:" + weightModel.getWeight() + "g");
}
}
@@ -0,0 +1,225 @@
//package com.sw.st.ui.device;
//
//import android.os.Handler;
//import android.os.Message;
//import android.view.View;
//import android.widget.TextView;
//import android.widget.Toast;
//
//import androidx.annotation.NonNull;
//import androidx.recyclerview.widget.RecyclerView;
//
//import com.chad.library.adapter.base.BaseQuickAdapter;
//import com.chad.library.adapter.base.listener.OnItemChildClickListener;
//import com.chad.library.adapter.base.listener.OnItemClickListener;
//import com.gyf.immersionbar.BarHide;
//import com.gyf.immersionbar.ImmersionBar;
//import com.scwang.smart.refresh.layout.SmartRefreshLayout;
//import com.scwang.smart.refresh.layout.api.RefreshLayout;
//import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
//import com.sw.st.R;
//import com.sw.st.base.BaseActivity;
//import com.sw.st.base.BasePresenter;
//import com.sw.st.model.WeightModel;
//import com.sw.st.utils.L;
//import com.sw.st.utils.PrefUtils;
//
//import org.jetbrains.annotations.NotNull;
//
//import java.io.File;
//import java.util.ArrayList;
//import java.util.List;
//
//import aclasdriver.AclasScale;
//import butterknife.BindView;
//import butterknife.OnClick;
//
//public class ComListActivity extends BaseActivity {
//
// private final String COM_INFO = "com_info";
//
// @BindView(R.id.title_name_tv)
// TextView titleName;
// @BindView(R.id.refreshLayout)
// SmartRefreshLayout refreshLayout;
// @BindView(R.id.recyclerView_content)
// RecyclerView recyclerView;
// @BindView(R.id.weight_info)
// TextView weightInfo;
//
// private ChengListAdapter chengListAdapter;
//
//
// @Override
// protected int provideContentViewId() {
// return R.layout.activity_cheng_list;
// }
//
// @Override
// public void initView() {
// ImmersionBar.with(this)
// .hideBar(BarHide.FLAG_HIDE_BAR)
// .statusBarAlpha(0f)
// .statusBarDarkFont(true)
// .statusBarColor(R.color.white)
// .init();
// titleName.setText("请选择");
//
// refreshLayout.setOnRefreshListener(new OnRefreshListener() {
// @Override
// public void onRefresh(@NonNull RefreshLayout refreshLayout) {
//
// }
// });
// refreshLayout.setEnableLoadMore(false);
//
// chengListAdapter = new ChengListAdapter(chengDataList, ComListActivity.this);
// recyclerView.setAdapter(chengListAdapter);
// }
//
// private ArrayList<WeightModel> chengDataList = new ArrayList<>();
//
// @Override
// public void initData() {
// final List<String> list = AclasScale.getAvailableUartList();
// for (String com : list) {
// WeightModel weightModel = new WeightModel();
// weightModel.setIp(com);
// chengDataList.add(weightModel);
// }
//
// handler = new Handler() {
// @Override
// public void handleMessage(Message msg) {
// switch (msg.what) {
// case 1:
// weightInfo.setText(msg.obj.toString());
// break;
// }
// }
// };
//
// initAclasScaleListener();
// }
//
// @Override
// public void initListener() {
// chengListAdapter.setOnItemClickListener(new OnItemClickListener() {
// @Override
// public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
// PrefUtils.setString(ComListActivity.this, COM_INFO, chengDataList.get(position).getIp());
// finish();
// }
// });
// chengListAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
// @Override
// public void onItemChildClick(@NonNull @NotNull BaseQuickAdapter adapter, @NonNull @NotNull View view, int position) {
// switch (view.getId()) {
// case R.id.item_cheng_open_com:
// showToast("item_cheng_open_com" + "===" + position);
// openScale(chengDataList.get(position).getIp());
// break;
// case R.id.item_cheng_close_com:
// showToast("item_cheng_close_com" + "===" + position);
// CloseDevice();
// break;
// }
// }
// });
// }
//
// @OnClick({R.id.title_back_iv})
// public void onViewClicked(View view) {
// switch (view.getId()) {
// case R.id.title_back_iv:
// finish();
// break;
// }
// }
//
//
// @Override
// protected BasePresenter createPresenter() {
// return null;
// }
//
// @Override
// protected void afterRequestPermission(int requestCode, boolean isAllGranted) {
//
// }
//
// @Override
// protected void onDestroy() {
// super.onDestroy();
//
// CloseDevice();
// }
//
// private Handler handler;
//
// private AclasScale scale = null;
// AclasScale.AclasScaleListener listener = null;
//
// private void initAclasScaleListener() {
//
// listener = new AclasScale.AclasScaleListener() {
// public void OnError(int code) {
// L.e("OnError!!!!" + code);
// }
//
// public void OnDataReceive(AclasScale.St_Data data) {
// if (data.m_iStatus == -1) {
// L.e("data error");
// } else {
// L.e("data:" + (data.m_iStatus == 0 ? "Unstable" : "Stable") + " weight:" + String.format("%.3f", data.m_fWeight)
// + " price:" + String.format("%.3f", data.m_fPrice) + " total:"
// + data.m_fTotal + " key:" + data.m_stKey.m_iValue + " str:" + data.m_stKey.m_strKey);
// Message message = new Message();
// message.what = 1;
// message.obj = (data.m_iStatus == 0 ? "U" : "S") + " " + data.m_fWeight + data.m_strUnit;
// handler.sendMessage(message);
// }
// }
//
// public void OnReadTare(float fVal, boolean bFlag) {
// String string = bFlag ? String.valueOf(fVal) : "Error";
// L.d("data len OnReadTare:" + bFlag + " " + fVal);
// }
// };
// }
//
// private void openScale(String strAdd) {
// try {
// CloseDevice();
// int iType = 0;// 0:计重模式; 1:计价模式
// scale = new AclasScale(new File(strAdd), iType, listener);
// scale.bLogFlag = true;
// scale.open();
//// m_strDeviceId = scale.GetId();
// } catch (SecurityException e) {
// // TODO Auto-generated catch block
// scale = null;
// Toast.makeText(this, "OpenScale exception", Toast.LENGTH_SHORT).show();
// e.printStackTrace();
// } catch (Exception e) {
// // TODO: handle exception
// scale = null;
// Toast.makeText(this, "OpenScale exception", Toast.LENGTH_SHORT).show();
// e.printStackTrace();
// }
// if (scale != null) {
// L.e("scale start run thread");
// scale.StartRead();
// } else {
// L.e("scale null!!!!!!!!!!!!!!!!!!!");
// }
// }
//
// private void CloseDevice() {
// if (scale != null) {
// scale.StopRead();
// scale.close();
// scale = null;
// }
// }
//}
@@ -0,0 +1,277 @@
//package com.sw.st.ui.device;
//
//import android.app.AlertDialog;
//import android.app.Dialog;
//import android.content.Intent;
//import android.view.View;
//import android.widget.EditText;
//import android.widget.TextView;
//import android.widget.Toast;
//
//import com.gyf.immersionbar.BarHide;
//import com.gyf.immersionbar.ImmersionBar;
//import com.sw.st.R;
//import com.sw.st.base.BaseActivity;
//import com.sw.st.model.UserFaceModel;
//import com.sw.st.utils.AppUtil;
//import com.sw.st.utils.DeviceIdUtil;
//import com.sw.st.utils.PrefUtils;
//import com.sw.st.utils.faceserver.FaceServer;
//
//import java.util.ArrayList;
//
//import butterknife.BindView;
//import butterknife.OnClick;
//
//public class DeviceActivity extends BaseActivity<DeviceView, DevicePresenter> implements DeviceView {
//
// private final String REST_NUM = "restId";
// private final String COM_INFO = "com_info";
//
// @BindView(R.id.title_name_tv)
// TextView titleName;
// @BindView(R.id.device_restnum)
// EditText restNumEdit;
// @BindView(R.id.device_id)
// EditText deviceIdEdit;
// @BindView(R.id.device_description)
// EditText descriptionEdit;
// @BindView(R.id.device_cheng_ip)
// TextView chengIpTv;
//
//// private WeightApi weightApi;
//
// @Override
// protected int provideContentViewId() {
// return R.layout.activity_device;
// }
//
// @Override
// public void initView() {
//
// ImmersionBar.with(this)
// .hideBar(BarHide.FLAG_HIDE_BAR)
// .statusBarAlpha(0f)
// .statusBarDarkFont(true)
// .statusBarColor(R.color.white)
// .init();
//
//
// titleName.setText("食堂设置");
// deviceIdEdit.setText(DeviceIdUtil.getDeviceId(this));
// restNumEdit.setText(PrefUtils.getString(this, REST_NUM, null));
//
//// weightApi = new WeightApi();
// }
//
//
// @Override
// public void initData() {
//
// }
//
// @Override
// public void initListener() {
//// initAclasScaleListener();
// }
//
// @Override
// protected void onResume() {
// super.onResume();
//
// chengIpTv.setText(PrefUtils.getString(this, COM_INFO, "请选择串口"));
//// openScale(chengIpTv.getText().toString());
//
//
// }
//
// @OnClick({R.id.title_back_iv, R.id.device_bind_ok, R.id.device_cheng_ip, R.id.button_zero, R.id.refreshFaceInfo})
// public void onViewClicked(View view) {
// switch (view.getId()) {
// case R.id.title_back_iv:
// finish();
// break;
// case R.id.device_bind_ok:
// String restNum = restNumEdit.getText().toString();
// if (AppUtil.isEmpty(restNum)) {
// showToast("请输入食堂编号");
// return;
// }
// PrefUtils.setString(this, REST_NUM, restNum);
// mPresenter.relRest(deviceIdEdit.getText().toString(), restNum, descriptionEdit.getText().toString());
// break;
// case R.id.device_cheng_ip:
//// startActivity(new Intent(DeviceActivity.this, ComListActivity.class));
// break;
// case R.id.button_zero:
//// scale.SetZero();
//
//// try {
//// weightApi.openPort(chengIpTv.getText().toString(), 9600, responseListener);
//// } catch (Exception exception) {
//// exception.printStackTrace();
//// Toast.makeText(DeviceActivity.this, "打开失败",
//// Toast.LENGTH_SHORT).show();
//// }
////
//// byte[] cmd = new byte[]{0x53, 0x57, 0x02, 0x00, 0x00, 0x00, (byte) 0xAC};//置0指令
//// try {
//// weightApi.sendCmd(cmd);
//// } catch (Exception exception) {
//// exception.printStackTrace();
//// Toast.makeText(DeviceActivity.this, "请连接电子秤", Toast.LENGTH_SHORT).show();
//// }
// break;
// case R.id.refreshFaceInfo:
// mPresenter.getUserFace();
// break;
// }
// }
//
// @Override
// protected DevicePresenter createPresenter() {
// return new DevicePresenter();
// }
//
// @Override
// protected void afterRequestPermission(int requestCode, boolean isAllGranted) {
//
// }
//
// @Override
// protected void onDestroy() {
// super.onDestroy();
//// CloseDevice();
// }
//
// @Override
// public void relRestSuccess(String info) {
// showToast("绑定成功");
// }
//
// @Override
// public void relRestFail(String info) {
//
// showToast(info);
//
// }
//
// @Override
// public void getFaceFeatureSuccess(ArrayList<UserFaceModel> list) {
// if (list != null && list.size() > 0) {
// FaceServer.getInstance().clearAllFaces(this);
//
// for (int i = 0; i < list.size(); i++) {
// UserFaceModel faceModel = list.get(i);
// FaceServer.getInstance().saveFaceFeature(faceModel.getUserId() + ":" + faceModel.getUserFaceId(), faceModel.getFaceFeature());
// }
// showToast("人脸数据更新成功");
//
// Dialog alertDialog = new AlertDialog.Builder(this).
// setTitle("成功").
// setMessage("人脸数据更新成功").
// create();
// alertDialog.show();
// } else {
// showToast("人脸数据更新失败");
// }
// }
//
// @Override
// public void getFaceFeatureFail(String info) {
//
// }
//
// @Override
// public void showProgress(String tipString) {
//
// }
//
// @Override
// public void hideProgress() {
//
// }
//
//// API.ResponseListener responseListener = new API.ResponseListener() {
//// @Override
//// public void onGetCmdResult(final byte[] result) {
////
//// runOnUiThread(new Runnable() {
//// @Override
//// public void run() {
//// }
//// });
//// }
////
//// @Override
//// public void onGetWeightInfo(final byte[] weightInfo) {
//// runOnUiThread(new Runnable() {
//// @Override
//// public void run() {
//// }
//// });
//// }
//// };
//// private AclasScale scale = null;
//// AclasScale.AclasScaleListener listener = null;
////
//// private void initAclasScaleListener() {
////
//// listener = new AclasScale.AclasScaleListener() {
//// public void OnError(int code) {
//// L.e("OnError!!!!" + code);
//// }
////
//// public void OnDataReceive(AclasScale.St_Data data) {
//// if (data.m_iStatus == -1) {
//// L.e("data error");
//// } else {
//// L.e("data:" + (data.m_iStatus == 0 ? "Unstable" : "Stable") + " weight:" + String.format("%.3f", data.m_fWeight)
//// + " price:" + String.format("%.3f", data.m_fPrice) + " total:"
//// + data.m_fTotal + " key:" + data.m_stKey.m_iValue + " str:" + data.m_stKey.m_strKey);
////
//// }
//// }
////
//// public void OnReadTare(float fVal, boolean bFlag) {
//// String string = bFlag ? String.valueOf(fVal) : "Error";
//// L.d("data len OnReadTare:" + bFlag + " " + fVal);
//// }
//// };
//// }
////
//// private void openScale(String strAdd) {
//// try {
//// CloseDevice();
//// int iType = 0;// 0:计重模式; 1:计价模式
//// scale = new AclasScale(new File(strAdd), iType, listener);
//// scale.bLogFlag = true;
//// scale.open();
////// m_strDeviceId = scale.GetId();
//// } catch (SecurityException e) {
//// // TODO Auto-generated catch block
//// scale = null;
//// Toast.makeText(this, "OpenScale exception", Toast.LENGTH_SHORT).show();
//// e.printStackTrace();
//// } catch (Exception e) {
//// // TODO: handle exception
//// scale = null;
//// Toast.makeText(this, "OpenScale exception", Toast.LENGTH_SHORT).show();
//// e.printStackTrace();
//// }
//// if (scale != null) {
//// L.e("scale start run thread");
//// scale.StartRead();
//// } else {
//// L.e("scale null!!!!!!!!!!!!!!!!!!!");
//// }
//// }
////
//// private void CloseDevice() {
//// if (scale != null) {
//// scale.StopRead();
//// scale.close();
//// scale = null;
//// }
//// }
//}
@@ -0,0 +1,77 @@
package com.sw.st.ui.device;
import com.sw.st.api.SwService;
import com.sw.st.base.BasePresenter;
import com.sw.st.model.UserFaceModel;
import com.sw.st.net.helper.rxjavahelper.RxObserver;
import com.sw.st.net.helper.rxjavahelper.RxResultHelper;
import com.sw.st.net.helper.rxjavahelper.RxSchedulersHelper;
import java.util.ArrayList;
import io.reactivex.disposables.Disposable;
public class DevicePresenter extends BasePresenter<DeviceView> {
public void relRest(String deviceMac, String restNo, String deviceDesc) {
SwService.relRest(deviceMac, restNo, deviceDesc)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleResult())
.subscribe(new RxObserver<BindDeviceModel>() {
@Override
public void _onSubscribe(Disposable d) {
}
@Override
public void _onNext(BindDeviceModel info) {
if (getView() != null)
getView().relRestSuccess(info.getRestName());
}
@Override
public void _onError(String errorMessage) {
if (getView() != null)
getView().relRestFail(errorMessage);
}
@Override
public void _onComplete() {
if (getView() != null)
getView().hideProgress();
}
});
}
public void getUserFace() {
SwService.getUserFace()
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleResult())
.subscribe(new RxObserver<ArrayList<UserFaceModel>>() {
@Override
public void _onSubscribe(Disposable d) {
getView().showProgress("加载中...");
}
@Override
public void _onNext(ArrayList<UserFaceModel> list) {
getView().getFaceFeatureSuccess(list);
}
@Override
public void _onError(String errorMessage) {
getView().getFaceFeatureFail(errorMessage);
getView().hideProgress();
}
@Override
public void _onComplete() {
getView().hideProgress();
}
});
}
}
@@ -0,0 +1,18 @@
package com.sw.st.ui.device;
import com.sw.st.base.BaseView;
import com.sw.st.model.UserFaceModel;
import java.util.ArrayList;
public interface DeviceView extends BaseView {
void relRestSuccess(String info);
void relRestFail(String info);
void getFaceFeatureSuccess(ArrayList<UserFaceModel> list);
void getFaceFeatureFail(String info);
}
@@ -0,0 +1,40 @@
package com.sw.st.ui.foodinfo;
import android.content.Context;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.sw.st.R;
import com.sw.st.model.ScalesFoodList;
import com.sw.st.model.UserNutritionModel;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public class FoodDetailAdapter extends BaseQuickAdapter<ScalesFoodList, BaseViewHolder> {
Context context;
public FoodDetailAdapter(@Nullable List<ScalesFoodList> listModels, Context context) {
super(R.layout.item_food_detail, listModels);
this.context = context;
}
@Override
protected void convert(@NotNull BaseViewHolder baseViewHolder, ScalesFoodList info) {
baseViewHolder.setText(R.id.nameTv, info.getFoodName());
baseViewHolder.setText(R.id.weightTv, info.getFoodWeight() + "");
// if (info.getVipPriceSum() > 0) {
// baseViewHolder.setText(R.id.priceTv, info.getVipPriceSum() + "元");
// } else {
baseViewHolder.setText(R.id.priceTv, info.getPriceSum() + "");
// }
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,39 @@
package com.sw.st.ui.foodinfo;
import android.content.Context;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.sw.st.R;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public class FoodInfoAdapter extends BaseQuickAdapter<FoodNutritionModel, BaseViewHolder> {
Context context;
public FoodInfoAdapter(@Nullable List<FoodNutritionModel> listModels, Context context) {
super(R.layout.item_food_info, listModels);
this.context = context;
}
@Override
protected void convert(@NotNull BaseViewHolder baseViewHolder, FoodNutritionModel info) {
if (getItemPosition(info) % 2 == 0)
baseViewHolder.setBackgroundColor(R.id.foodLayout, context.getResources().getColor(R.color.foodNutritionItemBg));
String name = info.getName();
baseViewHolder.setText(R.id.nameTv, name);
if (name.equals("")) {
baseViewHolder.setText(R.id.weightTv, info.getWeight() + "(mg)");
} else {
baseViewHolder.setText(R.id.weightTv, info.getWeight() + "(g)");
}
baseViewHolder.setText(R.id.nrvTv, info.getNrv());
}
}
@@ -0,0 +1,275 @@
package com.sw.st.ui.foodinfo;
import com.google.gson.Gson;
import com.sw.st.api.SwService;
import com.sw.st.base.BasePresenter;
import com.sw.st.model.FoodInfoModel;
import com.sw.st.model.RecommendValueModel;
import com.sw.st.model.ResponseData;
import com.sw.st.model.UserInfo;
import com.sw.st.model.UserNutritionModel;
import com.sw.st.net.helper.rxjavahelper.RxObserver;
import com.sw.st.net.helper.rxjavahelper.RxResultHelper;
import com.sw.st.net.helper.rxjavahelper.RxSchedulersHelper;
import com.sw.st.utils.AppUtil;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import io.reactivex.disposables.Disposable;
public class FoodInfoPresenter extends BasePresenter<FoodInfoView> {
// public void getToken(String devId) {
// SwService.getToken(devId)
// .compose(RxSchedulersHelper.io_main())
// .compose(RxResultHelper.handleJsonResponse())
// .subscribe(new RxObserver<String>() {
// @Override
// public void _onSubscribe(Disposable d) {
// }
//
// @Override
// public void _onNext(String info) {
// try {
// JSONObject jsonObject = new JSONObject(info);
// if (jsonObject.optInt("code") == 200) {
// String data = jsonObject.optString("result");
// if (getView() != null)
// getView().getTokenSuccess(data);
// }
// } catch (JSONException e) {
// e.printStackTrace();
// if (getView() != null)
// getView().getTokenFail("数据解析异常");
// }
//
// }
//
// @Override
// public void _onError(String errorMessage) {
// if (getView() != null)
// getView().getTokenFail(errorMessage);
// }
//
// @Override
// public void _onComplete() {
// }
// });
// }
public void getUserNutritionData(String foodId,
String eaId,
String plateNumber) {
SwService.getUserNutritionData(foodId, eaId, plateNumber)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleJsonResponse())
.subscribe(new RxObserver<String>() {
@Override
public void _onSubscribe(Disposable d) {
if (getView() != null)
getView().showProgress("加载中...");
}
@Override
public void _onNext(String info) {
if (AppUtil.isEmpty(info)) {
if (getView() != null)
getView().getUserNutritionDataFail("数据为空");
return;
}
try {
JSONObject jsonObject = new JSONObject(info);
int code = jsonObject.optInt("code");
if (code == 200) {
UserNutritionModel userModel = new Gson().fromJson(jsonObject.optString("data"),
UserNutritionModel.class);
if (getView() != null)
getView().getUserNutritionDataSuccess(userModel);
} else {
if (getView() != null)
getView().getUserNutritionDataFail(jsonObject.optString("msg"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void _onError(String errorMessage) {
if (getView() != null) {
getView().getUserNutritionDataFail(errorMessage);
getView().hideProgress();
}
}
@Override
public void _onComplete() {
if (getView() != null)
getView().hideProgress();
}
});
}
private double lastWeight = 0;
public void saveMarginWeight(String foodId,
String eaId,
double marginWeight) {
if (lastWeight == marginWeight || marginWeight < 0) {
return;
}
lastWeight = marginWeight;
SwService.saveMarginWeight(foodId, eaId, marginWeight)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleJsonResponse())
.subscribe(new RxObserver<String>() {
@Override
public void _onSubscribe(Disposable d) {
}
@Override
public void _onNext(String info) {
if (getView() != null)
getView().saveMarginWeightSuccess(info);
}
@Override
public void _onError(String errorMessage) {
if (getView() != null)
getView().saveMarginWeightFail(errorMessage);
}
@Override
public void _onComplete() {
}
});
}
public static final int FOOD_WEIGHT_THRESHOLD = 5;//取餐阈值,包含设置值
public void createRecord(String plateNumber, String foodId, String eaId, float intake, double residueWeight) {
if (intake < FOOD_WEIGHT_THRESHOLD) {//小于5g忽略
return;
}
SwService.userEatFood(plateNumber, foodId, eaId, intake, residueWeight)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleJsonResponse())
.subscribe(new RxObserver<String>() {
@Override
public void _onSubscribe(Disposable d) {
}
@Override
public void _onNext(String info) {
if (getView() != null)
getView().createRecordSuccess(info);
}
@Override
public void _onError(String errorMessage) {
if (getView() != null)
getView().createRecordFail(errorMessage);
}
@Override
public void _onComplete() {
}
});
}
public void getRestInfoFoodsByFoodId(String restId, String foodId) {
SwService.getRestInfoFoodsByFoodId(restId, foodId)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleResult())
.subscribe(new RxObserver<ArrayList<FoodInfoModel>>() {
@Override
public void _onSubscribe(Disposable d) {
}
@Override
public void _onNext(ArrayList<FoodInfoModel> info) {
if (getView() != null)
getView().getFoodInfoSuccess(info);
}
@Override
public void _onError(String errorMessage) {
if (getView() != null)
getView().getFoodInfoFail(errorMessage);
}
@Override
public void _onComplete() {
if (getView() != null)
getView().hideProgress();
}
});
}
public void getRecommendValue() {
SwService.getRecommendValue()
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleResult())
.subscribe(new RxObserver<RecommendValueModel>() {
@Override
public void _onSubscribe(Disposable d) {
}
@Override
public void _onNext(RecommendValueModel info) {
if (getView() != null)
getView().getRecommendValueSuccess(info);
}
@Override
public void _onError(String errorMessage) {
if (getView() != null)
getView().getRecommendValueFail(errorMessage);
}
@Override
public void _onComplete() {
if (getView() != null)
getView().hideProgress();
}
});
}
public void submitTakeFoodState(String eaId,
String plateNumber) {
SwService.submitTakeFoodState(eaId, plateNumber)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleJsonResponse())
.subscribe(new RxObserver<String>() {
@Override
public void _onSubscribe(Disposable d) {
}
@Override
public void _onNext(String info) {
}
@Override
public void _onError(String errorMessage) {
}
@Override
public void _onComplete() {
}
});
}
}
@@ -0,0 +1,43 @@
package com.sw.st.ui.foodinfo;
import com.sw.st.base.BaseView;
import com.sw.st.model.FoodInfoModel;
import com.sw.st.model.RecommendValueModel;
import com.sw.st.model.UserInfo;
import com.sw.st.model.UserNutritionModel;
import com.sw.st.ui.setting.FoodListModel;
import java.util.ArrayList;
public interface FoodInfoView extends BaseView {
// void getTokenSuccess(String info);
//
// void getTokenFail(String info);
void getUserNutritionDataSuccess(UserNutritionModel userModel);
void getUserNutritionDataFail(String info);
void createRecordSuccess(String info);
void createRecordFail(String info);
void addFoodWeightSuccess(String info);
void addFoodWeightFail(String info);
void saveMarginWeightSuccess(String info);
void saveMarginWeightFail(String info);
void getFoodInfoSuccess(ArrayList<FoodInfoModel> info);
void getFoodInfoFail(String info);
void getRecommendValueSuccess(RecommendValueModel info);
void getRecommendValueFail(String info);
}
@@ -0,0 +1,31 @@
package com.sw.st.ui.foodinfo;
import android.content.Context;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.sw.st.R;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public class FoodLableAdapter extends BaseQuickAdapter<String, BaseViewHolder> {
Context context;
public FoodLableAdapter(@Nullable List<String> strs, Context context) {
super(R.layout.item_lable_tv, strs);
this.context = context;
}
@Override
protected void convert(@NotNull BaseViewHolder baseViewHolder, String info) {
baseViewHolder.setText(R.id.tv, info);
}
}
@@ -0,0 +1,40 @@
package com.sw.st.ui.foodinfo;
public class FoodNutritionModel {
private String name;
private float weight;
private float nutritionWeight;
private String nrv;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getWeight() {
return weight;
}
public void setWeight(float weight) {
this.weight = weight;
}
public float getNutritionWeight() {
return nutritionWeight;
}
public void setNutritionWeight(float nutritionWeight) {
this.nutritionWeight = nutritionWeight;
}
public String getNrv() {
return nrv;
}
public void setNrv(String nrv) {
this.nrv = nrv;
}
}
@@ -0,0 +1,36 @@
package com.sw.st.ui.foodinfo;
import android.content.Context;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.sw.st.R;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public class FoodWarnLableAdapter extends BaseQuickAdapter<String, BaseViewHolder> {
Context context;
public FoodWarnLableAdapter(@Nullable List<String> strs, Context context) {
super(R.layout.item_food_warn_lable_tv, strs);
this.context = context;
}
// @Override
// public int getItemCount() {
// return getItemCount() > 3 ? 3 : getItemCount();
// }
@Override
protected void convert(@NotNull BaseViewHolder baseViewHolder, String info) {
String arr[] = info.split("#");
baseViewHolder.setText(R.id.lable, arr[0]);
baseViewHolder.setText(R.id.text, arr[1]);
}
}
@@ -0,0 +1,21 @@
package com.sw.st.ui.foodinfo;
import java.util.LinkedList;
public class LimitedQueue<E> extends LinkedList<E> {
private static final long serialVersionUID = 1L;
private final int size;
public LimitedQueue(int size) {
this.size = size;
}
@Override
public boolean add(E o) {
super.add(o);
while (size() > size) {
super.remove();
}
return true;
}
}
@@ -0,0 +1,420 @@
package com.sw.st.ui.init;
import android.app.Dialog;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.CountDownTimer;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.gyf.immersionbar.BarHide;
import com.gyf.immersionbar.ImmersionBar;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lxj.xpopup.interfaces.XPopupCallback;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.HttpHeaders;
import com.sw.st.R;
import com.sw.st.base.BaseActivity;
import com.sw.st.ui.foodinfo.FoodInfoActivity;
import com.sw.st.utils.AppUtil;
import com.sw.st.utils.BatteryChangeReceiver;
import com.sw.st.utils.FileUtil;
import com.sw.st.utils.InputMethod;
import com.sw.st.utils.L;
import com.sw.st.utils.OnDoubleClickListener;
import com.sw.st.utils.PrefUtils;
import com.sw.st.utils.SystemCtrlUtil;
import com.sw.st.utils.mqtt.MqttIn;
import com.sw.st.view.BindDiningRoomPopup;
import com.sw.st.view.CustomDialog;
import com.sw.st.view.IPEditText;
import org.json.JSONException;
import org.json.JSONObject;
import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder;
public class InitActivity extends BaseActivity<InitView, InitPresenter>
implements InitView {
// private final String LOCAL_SERVICE_ADDRESS = "http://kuaijiexi1234.gnway.cc";
private final String LOCAL_SERVICE_ADDRESS = "http://192.168.10.173:9092";
// private final String LOCAL_SERVICE_ADDRESS = "https://vip.shuziweidao.com";
// private final String LOCAL_SERVICE_ADDRESS = "http://192.168.1.250/gateway/local";
// private final String LOCAL_SERVICE_ADDRESS = "http://192.168.10.6/gateway/local";
private final String INTERNET_SERVICE_ADDRESS = "http://device.shuziweidao.com:8889";
private String TAG = "InitActivity";
@BindView(R.id.radioGroup)
RadioGroup radioGroup;
@BindView(R.id.welcomeLayout)
LinearLayout welcomeLayout;
@BindView(R.id.imgQr)
ImageView imgQr;
@BindView(R.id.radioButton1)
RadioButton radioButton1;
@BindView(R.id.radioButton2)
RadioButton radioButton2;
public static String BASE_URL = "";
public static final String REST_NUM = "restId";
private BindDiningRoomPopup customPopup;
@Override
protected int provideContentViewId() {
return R.layout.activity_init;
}
@Override
public void init() {
super.init();
}
@Override
public void initView() {
ImmersionBar.with(InitActivity.this)
.hideBar(BarHide.FLAG_HIDE_BAR)
.init();
int netType = PrefUtils.getInt(mContext, NET_TYPE, 1);
switch (netType) {
case 1:
radioButton1.setChecked(true);
break;
case 2:
radioButton2.setChecked(true);
break;
}
}
private CountDownTimer checkNetworkCountDownTimer;
private int checkNetworkCount = 0;
@Override
public void initData() {
showProgress("网络连接中...");
checkNetworkCountDownTimer = new CountDownTimer(1000 * 3, 1000) {
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
L.e("检测网络连接状态" + AppUtil.isNetworkConnected(mContext));
if (AppUtil.isNetworkConnected(mContext)) {
BASE_URL = PrefUtils.getString(mContext, "ip", "");
if (!AppUtil.isEmpty(BASE_URL)) {
mPresenter.getToken(AppUtil.getUDID(mContext));
} else {
welcomeLayout.setVisibility(View.GONE);
}
hideProgress();
} else {
if (checkNetworkCount >= 10) {
showErrorDialog("网络出现错误!", R.mipmap.img_error_net);
welcomeLayout.setVisibility(View.GONE);
hideProgress();
} else {
checkNetworkCount++;
checkNetworkCountDownTimer.start();
}
}
}
};
checkNetworkCountDownTimer.start();
customPopup = new BindDiningRoomPopup(InitActivity.this);
Bitmap qrcode = QRCodeEncoder.syncEncodeQRCode("" + AppUtil.getUDID(mContext), 100);
imgQr.setImageBitmap(qrcode);
imgQr.setOnTouchListener(new OnDoubleClickListener(() -> {
resetDevice();
}));
String url = PrefUtils.getString(mContext, "crashUrl", "");
String data = PrefUtils.getString(mContext, "crashData", "");
L.e(url + "===" + data);
mPresenter.uploadCrashLog(mContext, url, data);
//当前无配置,默认写死
// HttpHeaders httpHeaders = new HttpHeaders();
// httpHeaders.headersMap.put("Authorization", "eyJhbGciOiJIUzUxMiJ9.eyJpZCI6MTQ2LCJ1c2VyTmFtZSI6IjEzNjgxNDQ4ODU2IiwibmFtZSI6IuW-kOejiiIsInBhc3N3b3JkIjoiZDU0M2E3ODI1ZjJhZThhYjJmMWQ3MWJmYTNjZjYzMGY2ZmRiM2JiOCIsInNhbHQiOiI0NmEzMzUzYWU4OTA0MDYxYjMzODU5ZWNlYTBlMGE2NyIsInBob25lIjoiMTM2ODE0NDg4NTYiLCJzdGF0dXMiOjEsInVzZXJUeXBlIjoyLCJjcmVhdGVVc2VyTm8iOiIxNDEiLCJjcmVhdGVUaW1lIjoxNjI2OTQzNDE2MDAwLCJ1cGRhdGVVc2VyTm8iOiIxNDEiLCJ1cGRhdGVUaW1lIjoxNjI2OTQzNDE2MDAwLCJpc0RlbCI6ZmFsc2UsImVhSWQiOjk5LCJlYUlkTGlzdCI6Ijk5IiwiaXNTaG9wTWFuYWdlciI6dHJ1ZSwidXNlck5vIjoiOTgxNmM0ZWEtMzJmYi00ODIwLWE0NGQtOGM0ZmQ5NDU5Zjk2In0.HCeetHT7Z9GwmA1kgfYN41iS4ELw_eyv7J6FxK6EbXRfsx-2rA4ZQIJ9vi8nrAD97qouA3072v2PjBJ2ybiZbA");
// OkGo.getInstance().addCommonHeaders(httpHeaders);
//
//
// BASE_URL = LOCAL_SERVICE_ADDRESS;
// PrefUtils.setString(mContext, "restName", "数味餐厅");
// PrefUtils.setString(mContext, "restId", "99");
// startActivity(new Intent(this, FoodInfoActivity.class));
}
private void resetDevice() {
new XPopup.Builder(mContext)
.isViewMode(true)
.asConfirm("提示", "确定清空数据进行设备初始化?",
new OnConfirmListener() {
@Override
public void onConfirm() {
new Thread() {
@Override
public void run() {
super.run();
PrefUtils.clearAllData(mContext);
Glide.get(mContext).clearDiskCache();
}
}.start();
Glide.get(mContext).clearMemory();
}
})
.show();
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onStop() {
super.onStop();
}
@Override
public void initListener() {
welcomeLayout.setOnClickListener(v -> {
welcomeLayout.setVisibility(View.GONE);
});
}
private final String NET_TYPE = "netType";//1内网 2外网
@OnClick({R.id.okButton})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.okButton:
if (!AppUtil.isNetworkConnected(mContext)) {
showErrorDialog("网络出现错误!", R.mipmap.img_error_net);
return;
}
switch (radioGroup.getCheckedRadioButtonId()) {
case R.id.radioButton1:
showProgress("加载中...");
PrefUtils.setInt(mContext, NET_TYPE, 1);
BASE_URL = LOCAL_SERVICE_ADDRESS;
mPresenter.getToken(AppUtil.getUDID(mContext));
break;
case R.id.radioButton2:
showProgress("加载中...");
PrefUtils.setInt(mContext, NET_TYPE, 2);
mPresenter.getBaseToken(INTERNET_SERVICE_ADDRESS, AppUtil.getUDID(mContext));
break;
case -1:
showToast("请选择服务器");
break;
}
break;
}
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected InitPresenter createPresenter() {
return new InitPresenter();
}
@Override
protected void afterRequestPermission(int requestCode, boolean isAllGranted) {
}
@Override
public void getTokenSuccess(String token) {
FileUtil.saveLog("getTokenSuccess", token, BASE_URL);
PrefUtils.setString(mContext, "ip", BASE_URL);
if (!TextUtils.isEmpty(token)) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.headersMap.put("Authorization", token);
OkGo.getInstance().addCommonHeaders(httpHeaders);
}
//=============================测试用===============================================
// BASE_URL = LOCAL_SERVICE_ADDRESS;
// PrefUtils.setString(mContext, "restName", "数味餐厅");
// PrefUtils.setString(mContext, "restId", "99");
// startActivity(new Intent(this, FoodInfoActivity.class));
//============================================================================
String devInfo = PrefUtils.getString(mContext, "devInfo", null);
if (AppUtil.isEmpty(devInfo)) {
mPresenter.getDeviceInfoByEquipmentId(AppUtil.getUDID(mContext));
} else {
initDevice(devInfo);
}
}
@Override
public void getTokenFail(String info) {
FileUtil.saveLog("getTokenFail", info);
if (!AppUtil.isEmpty(info)) {
showErrorDialog("系统故障!", R.mipmap.img_error_system);
welcomeLayout.setVisibility(View.GONE);
}
hideProgress();
}
@Override
public void addDeviceInitSuccess(String result) {
mPresenter.getDeviceInfoByEquipmentId(AppUtil.getUDID(mContext));
}
@Override
public void addDeviceInitFail(String info) {
}
@Override
public void getDeviceInfoSuccess(String info) {
L.e("mzf", info);
PrefUtils.setString(mContext, "devInfo", info);
initDevice(info);
}
@Override
public void getDeviceInfoFail(String info) {
showToast(info);
hideProgress();
}
@Override
public void getBaseTokenSuccess(String token) {
if (!TextUtils.isEmpty(token)) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.headersMap.put("X-Access-Token", token);
OkGo.getInstance().addCommonHeaders(httpHeaders);
}
mPresenter.getServiceAddress(INTERNET_SERVICE_ADDRESS, AppUtil.getUDID(mContext));
}
@Override
public void getBaseTokenFail(String info) {
if (!AppUtil.isEmpty(info))
showToast(info);
hideProgress();
}
@Override
public void getServiceAddressSuccess(String info) {
PrefUtils.setString(mContext, "devInfo", info);
try {
JSONObject jsonObject = new JSONObject(info);
BASE_URL = jsonObject.optString("appPackageUrl");
mPresenter.getToken(AppUtil.getUDID(mContext));
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void getServiceAddressFail(String info) {
}
@Override
public void showProgress(String tipString) {
showWaitingDialog(tipString);
}
@Override
public void hideProgress() {
hideWaitingDialog();
}
private void initDevice(String info) {
try {
JSONObject jsonObject = new JSONObject(info);
PrefUtils.setString(mContext, "restName", jsonObject.optString("canteenName"));
PrefUtils.setString(mContext, "restId", jsonObject.optString("canteenId"));
String mqttIp = jsonObject.optString("clientServerIp");
String mqttPort = jsonObject.optString("zhstServerIp");
MqttIn.getInstance(mContext).init(mqttIp, mqttPort);
} catch (JSONException e) {
e.printStackTrace();
}
hideProgress();
PrefUtils.setBoolean(mContext, "isInit", true);
startActivity(new Intent(this, FoodInfoActivity.class));
}
@Override
protected void onDestroy() {
super.onDestroy();
MqttIn.getInstance(mContext).destroy();
}
@Override
protected void onPause() {
super.onPause();
}
/**
* 显示错误提示框
*
* @param tip
* @param resId
* @return
*/
public Dialog showErrorDialog(String tip, int resId) {
View view = View.inflate(this, R.layout.dialog_error, null);
TextView tvTip = view.findViewById(R.id.tvTip);
tvTip.setText(tip);
ImageView img = view.findViewById(R.id.img);
img.setImageResource(resId);
TextView tvBack = view.findViewById(R.id.tvBack);
CustomDialog customDialog = new CustomDialog(this, view, R.style.MyDialog);
customDialog.show();
customDialog.setCancelable(false);
tvBack.setOnClickListener(v -> {
customDialog.dismiss();
});
return customDialog;
}
}
@@ -0,0 +1,251 @@
package com.sw.st.ui.init;
import android.content.Context;
import com.sw.st.api.SwService;
import com.sw.st.application.App;
import com.sw.st.base.BasePresenter;
import com.sw.st.net.helper.rxjavahelper.RxObserver;
import com.sw.st.net.helper.rxjavahelper.RxResultHelper;
import com.sw.st.net.helper.rxjavahelper.RxSchedulersHelper;
import com.sw.st.utils.AppUtil;
import com.sw.st.utils.PrefUtils;
import org.json.JSONException;
import org.json.JSONObject;
import io.reactivex.disposables.Disposable;
public class InitPresenter extends BasePresenter<InitView> {
public void getToken(String devId) {
SwService.getToken(devId)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleJsonResponse())
.subscribe(new RxObserver<String>() {
@Override
public void _onSubscribe(Disposable d) {
}
@Override
public void _onNext(String info) {
try {
JSONObject jsonObject = new JSONObject(info);
if (jsonObject.optInt("code") == 200) {
String data = jsonObject.optString("data");
if (getView() != null)
getView().getTokenSuccess(data);
} else {
if (getView() != null)
getView().getTokenFail(jsonObject.optString("msg"));
}
} catch (JSONException e) {
e.printStackTrace();
if (getView() != null)
getView().getTokenFail("数据解析异常");
}
}
@Override
public void _onError(String errorMessage) {
if (getView() != null)
getView().getTokenFail(errorMessage);
}
@Override
public void _onComplete() {
if (getView() != null)
getView().getTokenFail(null);
}
});
}
public void addDeviceInit(String devId, String packageName) {
SwService.addDeviceInit(devId, packageName)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleJsonResponse())
.subscribe(new RxObserver<String>() {
@Override
public void _onSubscribe(Disposable d) {
}
@Override
public void _onNext(String info) {
try {
JSONObject jsonObject = new JSONObject(info);
if (jsonObject.optInt("code") == 200) {
String data = jsonObject.optString("data");
if (getView() != null)
getView().addDeviceInitSuccess(data);
}
} catch (JSONException e) {
e.printStackTrace();
if (getView() != null)
getView().addDeviceInitFail("数据解析异常");
}
}
@Override
public void _onError(String errorMessage) {
if (getView() != null)
getView().addDeviceInitFail(errorMessage);
}
@Override
public void _onComplete() {
}
});
}
public void getDeviceInfoByEquipmentId(String devId) {
SwService.getDeviceInfoByEquipmentId(devId)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleJsonResponse())
.subscribe(new RxObserver<String>() {
@Override
public void _onSubscribe(Disposable d) {
}
@Override
public void _onNext(String info) {
try {
JSONObject jsonObject = new JSONObject(info);
if (jsonObject.optInt("code") == 200) {
String data = jsonObject.optString("data");
if (getView() != null)
getView().getDeviceInfoSuccess(data);
} else {
if (getView() != null)
getView().getDeviceInfoFail(jsonObject.optString("msg"));
}
} catch (JSONException e) {
e.printStackTrace();
if (getView() != null)
getView().getDeviceInfoFail("数据解析异常");
}
}
@Override
public void _onError(String errorMessage) {
if (getView() != null)
getView().getDeviceInfoFail(errorMessage);
}
@Override
public void _onComplete() {
}
});
}
public void getBaseToken(String url, String devId) {
SwService.getBaseToken(url, devId)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleJsonResponse())
.subscribe(new RxObserver<String>() {
@Override
public void _onSubscribe(Disposable d) {
}
@Override
public void _onNext(String info) {
try {
JSONObject jsonObject = new JSONObject(info);
if (jsonObject.optInt("code") == 200) {
String data = jsonObject.optString("data");
if (getView() != null)
getView().getBaseTokenSuccess(data);
}
} catch (JSONException e) {
e.printStackTrace();
if (getView() != null)
getView().getBaseTokenFail("数据解析异常");
}
}
@Override
public void _onError(String errorMessage) {
if (getView() != null)
getView().getBaseTokenFail(errorMessage);
}
@Override
public void _onComplete() {
if (getView() != null)
getView().getTokenFail(null);
}
});
}
public void getServiceAddress(String url, String devId) {
SwService.getServerAddress(url, devId)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleJsonResponse())
.subscribe(new RxObserver<String>() {
@Override
public void _onSubscribe(Disposable d) {
}
@Override
public void _onNext(String info) {
try {
JSONObject jsonObject = new JSONObject(info);
if (jsonObject.optInt("code") == 200) {
String data = jsonObject.optString("data");
if (getView() != null)
getView().getServiceAddressSuccess(data);
}
} catch (JSONException e) {
e.printStackTrace();
if (getView() != null)
getView().getServiceAddressFail("数据解析异常");
}
}
@Override
public void _onError(String errorMessage) {
if (getView() != null)
getView().getServiceAddressFail(errorMessage);
}
@Override
public void _onComplete() {
}
});
}
public void uploadCrashLog(Context context, String url, String data) {
if (AppUtil.isEmpty(url) || AppUtil.isEmpty(data)) {
return;
}
SwService.uploadCrashLog(url, data)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleJsonResponse())
.subscribe(new RxObserver<String>() {
@Override
public void _onSubscribe(Disposable d) {
}
@Override
public void _onNext(String info) {
PrefUtils.setString(context, "crashUrl", "");
PrefUtils.setString(context, "crashData", "");
}
@Override
public void _onError(String errorMessage) {
}
@Override
public void _onComplete() {
}
});
}
}
@@ -0,0 +1,27 @@
package com.sw.st.ui.init;
import com.sw.st.base.BaseView;
public interface InitView extends BaseView {
void getTokenSuccess(String token);
void getTokenFail(String info);
void addDeviceInitSuccess(String token);
void addDeviceInitFail(String info);
void getDeviceInfoSuccess(String info);
void getDeviceInfoFail(String info);
void getBaseTokenSuccess(String token);
void getBaseTokenFail(String info);
void getServiceAddressSuccess(String info);
void getServiceAddressFail(String info);
}
@@ -0,0 +1,30 @@
package com.sw.st.ui.login;
import android.content.Context;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.sw.st.R;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public class FoodTagAdapter extends BaseQuickAdapter<String, BaseViewHolder> {
Context context;
public FoodTagAdapter(@Nullable List<String> listModels, Context context) {
super(R.layout.item_food_tag_tv, listModels);
this.context = context;
}
@Override
protected void convert(@NotNull BaseViewHolder baseViewHolder, String info) {
baseViewHolder.setText(R.id.tv, "#" + info);
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,519 @@
package com.sw.st.ui.login;
import com.google.gson.Gson;
import com.sw.st.api.SwService;
import com.sw.st.base.BasePresenter;
import com.sw.st.model.DeviceMacModel;
import com.sw.st.model.DinnerType;
import com.sw.st.model.FoodInfoModel;
import com.sw.st.model.MealRecordsInfo;
import com.sw.st.model.UserFaceModel;
import com.sw.st.model.UserInfo;
import com.sw.st.model.UserNutritionInfo;
import com.sw.st.net.helper.rxjavahelper.RxObserver;
import com.sw.st.net.helper.rxjavahelper.RxResultHelper;
import com.sw.st.net.helper.rxjavahelper.RxSchedulersHelper;
import com.sw.st.utils.AppUtil;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import io.reactivex.disposables.Disposable;
/**
* 登录注册
*/
public class LoginRegistPresenter extends BasePresenter<LoginRegistView> {
// public void getUserFace() {
// SwService.getUserFace()
// .compose(RxSchedulersHelper.io_main())
// .compose(RxResultHelper.handleResult())
// .subscribe(new RxObserver<ArrayList<UserFaceModel>>() {
//
// @Override
// public void _onSubscribe(Disposable d) {
// getView().showProgress("加载中...");
// }
//
// @Override
// public void _onNext(ArrayList<UserFaceModel> list) {
// getView().getFaceFeatureSuccess(list);
// }
//
// @Override
// public void _onError(String errorMessage) {
// getView().getFaceFeatureFail(errorMessage);
//
// getView().hideProgress();
// }
//
// @Override
// public void _onComplete() {
// getView().hideProgress();
// }
//
// });
// }
public void getUserInfo(String rfid) {
SwService.getUserInfo(rfid)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleJsonResponse())
.subscribe(new RxObserver<String>() {
@Override
public void _onSubscribe(Disposable d) {
getView().showProgress("加载中...");
}
@Override
public void _onNext(String info) {
if (AppUtil.isEmpty(info)) {
getView().getUserInfoFail("数据为空");
return;
}
try {
JSONObject jsonObject = new JSONObject(info);
int code = jsonObject.optInt("code");
if (code == 200) {
UserInfo userModel = new Gson().fromJson(jsonObject.optString("result"),
UserInfo.class);
getView().getUserInfoSuccess(userModel);
} else {
getView().getUserInfoFail("");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void _onError(String errorMessage) {
getView().getUserInfoFail(errorMessage);
getView().hideProgress();
}
@Override
public void _onComplete() {
getView().hideProgress();
}
});
}
public void getUserInfoById(String uId) {
SwService.getUserInfoById(uId)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleJsonResponse())
.subscribe(new RxObserver<String>() {
@Override
public void _onSubscribe(Disposable d) {
getView().showProgress("加载中...");
}
@Override
public void _onNext(String info) {
if (AppUtil.isEmpty(info)) {
getView().getUserInfoFail("数据为空");
return;
}
try {
JSONObject jsonObject = new JSONObject(info);
int code = jsonObject.optInt("code");
if (code == 200) {
UserInfo userModel = new Gson().fromJson(jsonObject.optString("result"),
UserInfo.class);
getView().getUserInfoSuccess(userModel);
} else {
getView().getUserInfoFail("");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void _onError(String errorMessage) {
getView().getUserInfoFail(errorMessage);
getView().hideProgress();
}
@Override
public void _onComplete() {
getView().hideProgress();
}
});
}
public void bindDeviceMac(String uid, String deviceMac) {
SwService.bindDeviceMac(uid, deviceMac)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleResult())
.subscribe(new RxObserver<String>() {
@Override
public void _onSubscribe(Disposable d) {
}
@Override
public void _onNext(String info) {
}
@Override
public void _onError(String errorMessage) {
}
@Override
public void _onComplete() {
}
});
}
public void getDeviceMac(String uid) {
SwService.getDeviceMac(uid)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleResult())
.subscribe(new RxObserver<DeviceMacModel>() {
@Override
public void _onSubscribe(Disposable d) {
}
@Override
public void _onNext(DeviceMacModel info) {
if (getView() != null)
getView().getDeviceMacSuccess(info);
}
@Override
public void _onError(String errorMessage) {
if (getView() != null)
getView().getDeviceMacFail(errorMessage);
}
@Override
public void _onComplete() {
if (getView() != null)
getView().hideProgress();
}
});
}
public void getFoodInfoByMac(String deviceMac) {
SwService.getFoodInfoByMac(deviceMac)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleResult())
.subscribe(new RxObserver<FoodInfoModel>() {
@Override
public void _onSubscribe(Disposable d) {
}
@Override
public void _onNext(FoodInfoModel info) {
if (getView() != null)
getView().getFoodInfoByMacSuccess(info);
}
@Override
public void _onError(String errorMessage) {
if (getView() != null)
getView().getFoodInfoByMacFail(errorMessage);
}
@Override
public void _onComplete() {
if (getView() != null)
getView().hideProgress();
}
});
}
public void getMealRecordsInfo(String userId) {
SwService.getMealRecordsInfo(userId)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleResult())
.subscribe(new RxObserver<MealRecordsInfo>() {
@Override
public void _onSubscribe(Disposable d) {
}
@Override
public void _onNext(MealRecordsInfo info) {
if (getView() != null)
getView().getMealRecordsInfoSuccess(info);
}
@Override
public void _onError(String errorMessage) {
if (getView() != null)
getView().getMealRecordsInfoFail(errorMessage);
}
@Override
public void _onComplete() {
if (getView() != null)
getView().hideProgress();
}
});
}
public void getUserNutrition(String restNum, String userId) {
SwService.getUserNutrition(restNum, userId)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleJsonResponse())
.subscribe(new RxObserver<String>() {
@Override
public void _onSubscribe(Disposable d) {
getView().showProgress("加载中...");
}
@Override
public void _onNext(String info) {
if (AppUtil.isEmpty(info)) {
getView().getUserNutritionInfoFail("数据为空");
return;
}
try {
JSONObject jsonObject = new JSONObject(info);
int code = jsonObject.optInt("code");
if (code == 200) {
UserNutritionInfo nutritionInfo = new Gson().fromJson(jsonObject.optString("result"),
UserNutritionInfo.class);
getView().getUserNutritionInfoSuccess(nutritionInfo);
} else {
getView().getUserNutritionInfoFail("");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void _onError(String errorMessage) {
getView().getUserNutritionInfoFail(errorMessage);
getView().hideProgress();
}
@Override
public void _onComplete() {
getView().hideProgress();
}
});
}
public void getDinnerType() {
SwService.getDinnerType()
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleResult())
.subscribe(new RxObserver<DinnerType>() {
@Override
public void _onSubscribe(Disposable d) {
}
@Override
public void _onNext(DinnerType info) {
if (getView() != null)
getView().getDinnerTypeSuccess(info);
}
@Override
public void _onError(String errorMessage) {
if (getView() != null)
getView().getDinnerTypeFail(errorMessage);
}
@Override
public void _onComplete() {
if (getView() != null)
getView().hideProgress();
}
});
}
public void createRecord(String userId, String foodId, String restNo, float intake, double residueWeight) {
SwService.userEatFood(userId, foodId, restNo, intake, residueWeight)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleJsonResponse())
.subscribe(new RxObserver<String>() {
@Override
public void _onSubscribe(Disposable d) {
}
@Override
public void _onNext(String info) {
if (getView() != null)
getView().createRecordSuccess(info);
}
@Override
public void _onError(String errorMessage) {
if (getView() != null)
getView().createRecordFail(errorMessage);
}
@Override
public void _onComplete() {
}
});
}
// public void getToken() {
// SwService.getToken()
// .compose(RxSchedulersHelper.io_main())
// .compose(RxResultHelper.handleJsonResponse())
// .subscribe(new RxObserver<String>() {
// @Override
// public void _onSubscribe(Disposable d) {
// }
//
// @Override
// public void _onNext(String info) {
// try {
// JSONObject jsonObject = new JSONObject(info);
// if (jsonObject.optInt("respCode") == 0) {
// String data = jsonObject.optString("data");
// if (getView() != null)
// getView().getTokenSuccess(data);
// }
// } catch (JSONException e) {
// e.printStackTrace();
// if (getView() != null)
// getView().getTokenFail("数据解析异常");
// }
//
// }
//
// @Override
// public void _onError(String errorMessage) {
// if (getView() != null)
// getView().getTokenFail(errorMessage);
// }
//
// @Override
// public void _onComplete() {
// }
// });
// }
/**
* @param foodId 菜品ID
* @param type 是否开餐1开餐,2加菜
* @param totalWeight 菜品增重
* @return
*/
public void addFoodTotalWeight(String foodId, int type, double totalWeight, String deviceMac) {
SwService.startMealService(foodId, type, totalWeight, deviceMac)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleJsonResponse())
.subscribe(new RxObserver<String>() {
@Override
public void _onSubscribe(Disposable d) {
}
@Override
public void _onNext(String info) {
try {
JSONObject jsonObject = new JSONObject(info);
if (jsonObject.optInt("code") == 200) {
String data = jsonObject.optString("data");
if (getView() != null)
getView().addFoodWeightSuccess(data);
} else {
getView().addFoodWeightFail(jsonObject.optString("message"));
}
} catch (JSONException e) {
e.printStackTrace();
if (getView() != null)
getView().addFoodWeightFail("数据解析异常");
}
}
@Override
public void _onError(String errorMessage) {
if (getView() != null)
getView().addFoodWeightFail(errorMessage);
}
@Override
public void _onComplete() {
}
});
// SwService.addFoodTotalWeight(foodId, type, totalWeight, deviceMac)
// .compose(RxSchedulersHelper.io_main())
// .compose(RxResultHelper.handleJsonResponse())
// .subscribe(new RxObserver<String>() {
// @Override
// public void _onSubscribe(Disposable d) {
// }
//
// @Override
// public void _onNext(String info) {
// try {
// JSONObject jsonObject = new JSONObject(info);
// if (jsonObject.optInt("code") == 200) {
// String data = jsonObject.optString("data");
// if (getView() != null)
// getView().addFoodWeightSuccess(data);
// }
// } catch (JSONException e) {
// e.printStackTrace();
// if (getView() != null)
// getView().addFoodWeightFail("数据解析异常");
// }
// }
//
// @Override
// public void _onError(String errorMessage) {
// if (getView() != null)
// getView().addFoodWeightFail(errorMessage);
// }
//
// @Override
// public void _onComplete() {
// }
// });
}
public void onLineRenewal(String deviceMac) {
SwService.onLineRenewal(deviceMac)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleJsonResponse())
.subscribe(new RxObserver<String>() {
@Override
public void _onSubscribe(Disposable d) {
}
@Override
public void _onNext(String info) {
}
@Override
public void _onError(String errorMessage) {
}
@Override
public void _onComplete() {
}
});
}
}
@@ -0,0 +1,61 @@
package com.sw.st.ui.login;
import com.sw.st.base.BaseView;
import com.sw.st.model.DeviceMacModel;
import com.sw.st.model.DinnerType;
import com.sw.st.model.FoodInfoModel;
import com.sw.st.model.MealRecordsInfo;
import com.sw.st.model.UserFaceModel;
import com.sw.st.model.UserInfo;
import com.sw.st.model.UserNutritionInfo;
import java.util.ArrayList;
public interface LoginRegistView extends BaseView {
void upFaceFeatureSuccess();
void upFaceFeatureFail(String info);
void getFaceFeatureSuccess(ArrayList<UserFaceModel> list);
void getFaceFeatureFail(String info);
void getUserInfoSuccess(UserInfo userModel);
void getUserInfoFail(String info);
void getUserNutritionInfoSuccess(UserNutritionInfo userNutritionInfo);
void getUserNutritionInfoFail(String info);
void getDeviceMacSuccess(DeviceMacModel deviceMacModel);
void getDeviceMacFail(String info);
void getFoodInfoByMacSuccess(FoodInfoModel foodInfoModel);
void getFoodInfoByMacFail(String info);
void getMealRecordsInfoSuccess(MealRecordsInfo mealRecordsInfo);
void getMealRecordsInfoFail(String info);
void getDinnerTypeSuccess(DinnerType dinnerType);
void getDinnerTypeFail(String info);
void createRecordSuccess(String info);
void createRecordFail(String info);
void getTokenSuccess(String info);
void getTokenFail(String info);
void addFoodWeightSuccess(String info);
void addFoodWeightFail(String info);
}
@@ -0,0 +1,21 @@
package com.sw.st.ui.login;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import java.text.DecimalFormat;
public class MyAxisValueFormatter implements IAxisValueFormatter
{
private final DecimalFormat mFormat;
public MyAxisValueFormatter() {
mFormat = new DecimalFormat("###,###,###,##0.0");
}
@Override
public String getFormattedValue(float value, AxisBase axis) {
return mFormat.format(value) + " g";
}
}
@@ -0,0 +1,51 @@
package com.sw.st.ui.login;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import com.sw.st.R;
import com.sw.st.ui.setting.FoodListModel;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import java.util.List;
/**
* Created by Administrator on 2019/4/23 0023.
*/
public class MyFoodTagAdapters extends TagAdapter<String> {
private Context context;
public MyFoodTagAdapters(Context context, List<String> datas) {
super(datas);
this.context = context;
}
@Override
public View getView(FlowLayout parent, int position, String tag) {
LayoutInflater inflater = LayoutInflater.from(context);
TextView tv = (TextView) inflater.inflate(R.layout.item_food_tag_flow_tv, parent, false);
switch (position % 3) {
case 0:
tv.setBackground(context.getResources().getDrawable(R.drawable.bg_food_tag_red));
tv.setTextColor(0xFFFE4343);
break;
case 1:
tv.setBackground(context.getResources().getDrawable(R.drawable.bg_food_tag_yellow));
tv.setTextColor(0xFFDDCC0A);
break;
case 2:
tv.setBackground(context.getResources().getDrawable(R.drawable.bg_food_tag_blue));
tv.setTextColor(0xFF2CABF0);
break;
}
tv.setText(tag);
return tv;
}
}
@@ -0,0 +1,32 @@
package com.sw.st.ui.login;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import java.text.DecimalFormat;
public class MyXValueFormatter implements IAxisValueFormatter {
private final DecimalFormat mFormat;
public MyXValueFormatter() {
mFormat = new DecimalFormat("###,###,###,##0.0");
}
@Override
public String getFormattedValue(float value, AxisBase axis) {
if (value == 1) {
return "脂肪";
}
if (value == 2) {
return "蛋白质";
}
if (value == 3) {
return "碳水";
}
if (value == 4) {
return "";
}
return mFormat.format(value) + " g";
}
}
@@ -0,0 +1,69 @@
package com.sw.st.ui.login;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import com.sw.st.R;
import com.sw.st.base.BaseActivity;
import butterknife.BindView;
import butterknife.OnClick;
public class SelectIdentityActivity extends BaseActivity<SelectIdentityView, SelectIdentityPresenter> {
@BindView(R.id.vip_mobile_edittext)
EditText mobileEditText;
@BindView(R.id.vip_mobile_layout)
LinearLayout mobileLayout;
@BindView(R.id.anonymous_button)
Button anonymousButton;
@Override
protected int provideContentViewId() {
return R.layout.activity_select_identity;
}
@Override
public void initView() {
}
@Override
public void initData() {
}
@Override
public void initListener() {
}
@OnClick({R.id.vip_button, R.id.mobile_ok_button, R.id.anonymous_button})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.vip_button:
mobileLayout.setVisibility(View.VISIBLE);
anonymousButton.setVisibility(View.GONE);
break;
case R.id.mobile_ok_button:
finish();
break;
case R.id.anonymous_button:
finish();
break;
}
}
@Override
protected SelectIdentityPresenter createPresenter() {
return new SelectIdentityPresenter();
}
@Override
protected void afterRequestPermission(int requestCode, boolean isAllGranted) {
}
}
@@ -0,0 +1,13 @@
package com.sw.st.ui.login;
import com.sw.st.base.BasePresenter;
/**
* 登录注册
*/
public class SelectIdentityPresenter extends BasePresenter<SelectIdentityView> {
}
@@ -0,0 +1,13 @@
package com.sw.st.ui.login;
import com.sw.st.base.BaseView;
public interface SelectIdentityView extends BaseView {
void upFaceFeatureSuccess();
void upFaceFeatureFail(String info);
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,97 @@
package com.sw.st.ui.rfid;
import com.sw.st.api.SwService;
import com.sw.st.base.BasePresenter;
import com.sw.st.net.helper.rxjavahelper.RxObserver;
import com.sw.st.net.helper.rxjavahelper.RxResultHelper;
import com.sw.st.net.helper.rxjavahelper.RxSchedulersHelper;
import org.json.JSONException;
import org.json.JSONObject;
import io.reactivex.disposables.Disposable;
/**
* 登录注册
*/
public class RfidBindPresenter extends BasePresenter<RfidBindView> {
public void rfidBindUser(String uid,
String rfid,
String restId) {
SwService.rfidBindUser(uid, rfid, restId)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleJsonResponse())
.subscribe(new RxObserver<String>() {
@Override
public void _onNext(String info) {
try {
JSONObject jsonObject = new JSONObject(info);
if (jsonObject.optInt("code") == 200) {
String data = jsonObject.optString("result");
if (getView() != null) {
getView().bindUserSuccess(data);
}
} else {
String message = jsonObject.optString("message");
if (getView() != null) {
getView().bindUserFail(message);
}
}
} catch (JSONException e) {
e.printStackTrace();
if (getView() != null) {
getView().bindUserFail("数据解析异常");
}
}
if (getView() != null) {
getView().hideProgress();
}
}
@Override
public void _onError(String errorMessage) {
getView().bindUserFail(errorMessage);
}
});
}
public void getUserInfoByFaceFeatureData(String faceFeature) {
// SwService.getUserInfoByFaceFeatureData(faceFeature)
// .compose(RxSchedulersHelper.io_main())
// .compose(RxResultHelper.handleResult())
// .subscribe(new RxObserver<UserRootModel>() {
//
// @Override
// public void _onSubscribe(Disposable d) {
// if (getView() != null)
// getView().showProgress("查询中...");
// }
//
// @Override
// public void _onNext(UserRootModel userBean) {
// if (getView() != null)
// getView().getUserInfoSuccess(userBean);
// }
//
// @Override
// public void _onError(String errorMessage) {
// if (getView() != null) {
// getView().getUserInfoFail(errorMessage);
//
// getView().hideProgress();
// }
// }
//
// @Override
// public void _onComplete() {
// if (getView() != null)
// getView().hideProgress();
// }
//
// });
}
}
@@ -0,0 +1,11 @@
package com.sw.st.ui.rfid;
import com.sw.st.base.BaseView;
public interface RfidBindView extends BaseView {
void bindUserFail(String info);
void bindUserSuccess(String info);
}
@@ -0,0 +1,849 @@
//package com.sw.st.ui.rfid;
//
//import android.content.Intent;
//import android.os.CountDownTimer;
//import android.os.Handler;
//import android.os.Looper;
//import android.os.Message;
//import android.os.SystemClock;
//import android.util.Log;
//import android.view.View;
//import android.view.ViewTreeObserver;
//import android.widget.ImageView;
//import android.widget.LinearLayout;
//import android.widget.SeekBar;
//import android.widget.TextView;
//
//import androidx.annotation.Nullable;
//
//import com.bumptech.glide.Glide;
//import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
//import com.bumptech.glide.request.RequestOptions;
//import com.github.mikephil.charting.data.Entry;
//import com.github.mikephil.charting.highlight.Highlight;
//import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
//import com.gyf.immersionbar.BarHide;
//import com.gyf.immersionbar.ImmersionBar;
//import com.innohi.YNHAPI;
//import com.sw.st.R;
//import com.sw.st.base.BaseActivity;
//import com.sw.st.model.DeviceMacModel;
//import com.sw.st.model.DinnerModel;
//import com.sw.st.model.DinnerType;
//import com.sw.st.model.FoodInfoModel;
//import com.sw.st.model.MealRecordsInfo;
//import com.sw.st.model.UserFaceModel;
//import com.sw.st.model.UserInfo;
//import com.sw.st.model.UserNutritionInfo;
//import com.sw.st.ui.device.DeviceActivity;
//import com.sw.st.ui.login.LoginRegistPresenter;
//import com.sw.st.ui.login.LoginRegistView;
//import com.sw.st.ui.login.MyFoodTagAdapters;
//import com.sw.st.ui.login.SelectIdentityActivity;
//import com.sw.st.ui.setting.FoodSettingActivity;
//import com.sw.st.utils.AppUtil;
//import com.sw.st.utils.DeviceIdUtil;
//import com.sw.st.utils.L;
//import com.sw.st.utils.PrefUtils;
//import com.sw.st.utils.T;
//import com.sw.st.utils.faceserver.FaceServer;
//import com.zhy.view.flowlayout.TagFlowLayout;
//
//import java.io.UnsupportedEncodingException;
//import java.net.URLDecoder;
//import java.util.ArrayList;
//
//import butterknife.BindView;
//import butterknife.OnClick;
//
///**
// * desc:登录注册界面
// */
//
//public class RfidMainActivity extends BaseActivity<LoginRegistView, LoginRegistPresenter>
// implements LoginRegistView, ViewTreeObserver.OnGlobalLayoutListener, OnChartValueSelectedListener {
// private static final String TAG = "LoginActivity";
//
// private final String COM_INFO = "com_info";
// private final String REST_NUM = "restId";
//
// private final int OFFSET_WEIGHT = 2;
//
// private String mUid = null;
//
// @BindView(R.id.food_img)
// ImageView foodImg;
// @BindView(R.id.main_user_info_layout)
// LinearLayout userInfoLayout;
// @BindView(R.id.main_user_name_tv)
// TextView userNameTv;
// @BindView(R.id.main_user_company_tv)
// TextView userCompanyTv;
// @BindView(R.id.main_foodname_tv)
// TextView foodNameTv;
// @BindView(R.id.main_foodname_take_tv)
// TextView foodTakeTv;
// @BindView(R.id.main_foodname_take_kcal_tv)
// TextView foodTakeKcalTv;
// @BindView(R.id.main_form_calorie_num_tv)
// TextView calorieNumTv;
// @BindView(R.id.main_dinner_min_tv)
// TextView dinnerMinTv;
// @BindView(R.id.main_dinner_max_tv)
// TextView dinnerMaxTv;
// @BindView(R.id.seekBar)
// SeekBar mSeekBar;
// @BindView(R.id.title_content_fat)
// TextView titleContentFat;
// @BindView(R.id.title_content_protein)
// TextView titleContentProtein;
// @BindView(R.id.title_content_cho)
// TextView titleContentCho;
// @BindView(R.id.title_flowlayout)
// TagFlowLayout titleFlowLayout;
// @BindView(R.id.middle_fat)
// TextView middleFat;
// @BindView(R.id.middle_protein)
// TextView middleProtein;
// @BindView(R.id.middle_cho)
// TextView middleCho;
// @BindView(R.id.bottom_weight_tv)
// TextView bottomWeight;
// @BindView(R.id.bottom_fat_tv)
// TextView bottomFat;
// @BindView(R.id.bottom_protein_tv)
// TextView bottomProtein;
// @BindView(R.id.bottom_cho_tv)
// TextView bottomCho;
// @BindView(R.id.bottom_kcal_tv)
// TextView bottomKcal;
// @BindView(R.id.rfid)
// TextView rfidTv;
//
//
// private int firstWeight = 0;
// private int currentWeight = 0;
// private int intake = 0;
//
// private String restNum;
//
// @Override
// protected LoginRegistPresenter createPresenter() {
// return new LoginRegistPresenter();
// }
//
// @Override
// protected int provideContentViewId() {
// return R.layout.activity_rfid_main;
// }
//
// @Override
// protected void afterRequestPermission(int requestCode, boolean isAllGranted) {
//
// }
//
// @Override
// public void init() {
// super.init();
//
// //本地人脸库初始化
// FaceServer.getInstance().init(this);
//
// String strAdd = PrefUtils.getString(this, COM_INFO, "/dev/ttyS4");
//// SerialPortManager.instance().open(strAdd, "9600", responseListener);
//
// initTimer();
//
// //未设置餐厅或IP,自动跳转设置界面
// restNum = PrefUtils.getString(RfidMainActivity.this, REST_NUM, null);
// String comInfo = PrefUtils.getString(RfidMainActivity.this, COM_INFO, null);
// //AppUtil.isEmpty(deviceIp) ||
//// if (AppUtil.isEmpty(comInfo) || AppUtil.isEmpty(restNum)) {
//// startActivity(new Intent(LoginActivity.this, DeviceActivity.class));
//// return;
//// }
//
// }
//
// @Override
// public void initView() {
//
// ImmersionBar.with(this)
// .hideBar(BarHide.FLAG_HIDE_BAR)
// .statusBarAlpha(0f)
// .statusBarDarkFont(true)
// .statusBarColor(R.color.white)
// .init();
//
//// Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/FZYTK.TTF");
//// bottomKcal.setTypeface(typeface);
//
// }
//
// private void initFoodInfo() {
// currentFoodInfo = (FoodInfoModel) getIntent().getSerializableExtra("foodInfo");
//
// foodNameTv.setText(currentFoodInfo.getFoodName());
// foodNameTv.setTag(currentFoodInfo.getId());
//
// try {
// RequestOptions cropOptions = new RequestOptions();
// cropOptions.transform(new RoundedCorners(12));//new CenterCrop()
//
// Glide.with(this).load(URLDecoder.decode(currentFoodInfo.getImgUrl(), "UTF-8"))
// .apply(cropOptions)
// .into(foodImg);
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
//
// ArrayList<String> tagArr = new ArrayList<>();
// String foodLabel = currentFoodInfo.getFoodLabel();
// if (!AppUtil.isEmpty(foodLabel)) {
// String[] feedNameArr = foodLabel.split(",");
// for (String feedName : feedNameArr) {
// tagArr.add(feedName);
// }
// }
// if (tagArr.size() > 0) {
// MyFoodTagAdapters myFlowAdapters = new MyFoodTagAdapters(this, tagArr.size() > 4 ? tagArr.subList(0, 4) : tagArr);
// titleFlowLayout.setAdapter(myFlowAdapters);
// myFlowAdapters.notifyDataChanged();
// titleFlowLayout.setVisibility(View.VISIBLE);
// } else {
// titleFlowLayout.setVisibility(View.GONE);
// }
//
// //初始化营养信息
// float kcal = AppUtil.formatFloat2((currentFoodInfo.getStFoodInfoMaterial().getEnergyKcal()));
// float fat = AppUtil.formatFloat2(currentFoodInfo.getStFoodInfoMaterial().getFat());
// float protein = AppUtil.formatFloat2(currentFoodInfo.getStFoodInfoMaterial().getProtein());
// float cho = AppUtil.formatFloat2(currentFoodInfo.getStFoodInfoMaterial().getCho());
// float na = AppUtil.formatFloat2(currentFoodInfo.getStFoodInfoMaterial().getNa() / 1000);
//
// calorieNumTv.setText(kcal + "");
// titleContentFat.setText("脂肪/" + fat + "g");
// titleContentCho.setText("碳水/" + cho + "g");
// titleContentProtein.setText("蛋白质/" + protein + "g");
// }
//
// //设置数据
// private void setData(int weight, boolean isSetUserInfo) {
// if (currentFoodInfo == null) {
// return;
// }
// float kcal = AppUtil.formatFloat2((currentFoodInfo.getStFoodInfoMaterial().getEnergyKcal() * weight / 100));
//
// float fat = AppUtil.formatFloat2(currentFoodInfo.getStFoodInfoMaterial().getFat() * weight / 100);
// float protein = AppUtil.formatFloat2(currentFoodInfo.getStFoodInfoMaterial().getProtein() * weight / 100);
// float cho = AppUtil.formatFloat2(currentFoodInfo.getStFoodInfoMaterial().getCho() * weight / 100);
// float na = AppUtil.formatFloat2(currentFoodInfo.getStFoodInfoMaterial().getNa() / 1000 * weight / 100);
// if (isSetUserInfo) {
//// foodTakeTv.setText("取用量" + weight + "g"
//// + kcal
//// + "Kcal");
// foodTakeTv.setText(weight + "");
// foodTakeKcalTv.setText(kcal + "");
// setEnergyKcal(energyKcal + kcal);
//// formWeightTv.setText("" + weight + "g");
// middleFat.setText("脂肪/" + fat + "g");
// middleProtein.setText("蛋白质/" + protein + "g");
// middleCho.setText("碳水/" + cho + "g");
//
// setBottomData(weight, fat, protein, cho);
// } else {
//// foodTakeTv.setText("取用量" + 0 + "g"
//// + 0
//// + "Kcal");
// foodTakeTv.setText("0");
// foodTakeKcalTv.setText("0");
// setEnergyKcal(energyKcal);
// middleFat.setText("脂肪/--");
// middleProtein.setText("蛋白质/--");
// middleCho.setText("碳水/--");
// }
// }
//
// @Override
// protected void onResume() {
// super.onResume();
//
// }
//
// private void setBottomData(int weight, float fat, float protein, float cho) {
// if (userNutritionInfo != null) {
// bottomFat.setText(AppUtil.formatFloat2(userNutritionInfo.getFat() + fat) + "g");
// bottomProtein.setText(AppUtil.formatFloat2(userNutritionInfo.getProtein() + protein) + "g");
// bottomCho.setText(AppUtil.formatFloat2(userNutritionInfo.getCho() + cho) + "g");
// } else {
// bottomFat.setText(AppUtil.formatFloat2(fat) + "g");
// bottomProtein.setText(AppUtil.formatFloat2(protein) + "g");
// bottomCho.setText(AppUtil.formatFloat2(cho) + "g");
// }
// bottomWeight.setText(AppUtil.formatFloat2(totalWeight + weight) + "g");
// }
//
// private Handler handler;
//
// @Override
// public void initData() {
// handler = new Handler(Looper.getMainLooper()) {
// @Override
// public void handleMessage(Message msg) {
// switch (msg.what) {
// case 1://返回socket数据
// L.e("onLineRenewal-light===" + intake);
// openLedLight(YNHAPI.Light.Light_Red);
//
//// rfidTv.setText("RFID:" + rfId);
// //======================================
//// if (firstWeight == 0) {//保存首次重量
//// firstWeight = (int) deviceWeight;
//// }
//// currentWeight = (int) deviceWeight;
//// if (firstWeight - currentWeight > 0) {
//// intake = firstWeight - currentWeight;
//// setData(intake, true);
//// if (AppUtil.isEmpty(mUid) && intake > OFFSET_WEIGHT) {
//// L.e("onLineRenewal-light===" + intake);
////// openLedLight(YNHAPI.Light.Light_Red);
//// }
//// } else if (firstWeight - currentWeight == 0) {
//// intake = firstWeight - currentWeight;
//// setData(100, false);
//// setBottomData(0, 0, 0, 0);
//// }
// break;
// case 2://获取本餐信息
//// mPresenter.getMealRecordsInfo(mUid);
//
// mPresenter.getUserNutrition(restNum, mUid);
// break;
// }
// }
// };
// initFoodInfo();
// }
//
// private void openLedLight(YNHAPI.Light index) {
// if (YNHAPI.getLightState(index)) {
// return;
// }
// YNHAPI.setLightState(index, true);
// new Handler().postDelayed(new Runnable() {
// public void run() {
// YNHAPI.setLightState(index, false);
// }
// }, 5000); //5秒
// }
//
// private final long CLICK_INTERVAL_TIME = 300;
// private long lastClickTime = 0;
//
// @Override
// public void initListener() {
// userInfoLayout.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// long currentTimeMillis = SystemClock.uptimeMillis();
// if (currentTimeMillis - lastClickTime < CLICK_INTERVAL_TIME) {
// Intent intent = new Intent(RfidMainActivity.this, DeviceActivity.class);
// startActivity(intent);
// return;
// }
// lastClickTime = currentTimeMillis;
// }
// });
// foodNameTv.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// long currentTimeMillis = SystemClock.uptimeMillis();
// if (currentTimeMillis - lastClickTime < CLICK_INTERVAL_TIME) {
// Intent intent = new Intent(RfidMainActivity.this, FoodSettingActivity.class);
// intent.putExtra("current_food", foodNameTv.getText().toString());
// startActivity(intent);
// finish();
// return;
// }
// lastClickTime = currentTimeMillis;
// }
// });
// rfidTv.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// finish();
// }
// });
// }
//
// @Override
// public void onGlobalLayout() {
//
// }
//
// @OnClick({R.id.main_foodname_take_tv})
// public void onViewClicked(View view) {
// switch (view.getId()) {
// case R.id.main_foodname_take_tv:
// break;
// }
// }
//
//
// @Override
// protected void onPause() {
// super.onPause();
//
// }
//
// @Override
// protected void onDestroy() {
//// SerialPortManager.instance().close();
// super.onDestroy();
// }
//
// @Override
// public void showProgress(String tipString) {
//// showWaitingDialog(tipString);
// }
//
// @Override
// public void hideProgress() {
//// hideWaitingDialog();
// }
//
// @Override
// public void upFaceFeatureSuccess() {
// finish();
// startActivity(new Intent(this, SelectIdentityActivity.class));
// }
//
// @Override
// public void upFaceFeatureFail(String info) {
// T.showShort(this, info);
// finish();
// startActivity(new Intent(this, SelectIdentityActivity.class));
// }
//
// @Override
// public void getFaceFeatureSuccess(ArrayList<UserFaceModel> list) {
// if (list != null && list.size() > 0) {
// FaceServer.getInstance().clearAllFaces(this);
//
// for (int i = 0; i < list.size(); i++) {
// UserFaceModel faceModel = list.get(i);
// FaceServer.getInstance().saveFaceFeature(faceModel.getUserId() + ":" + faceModel.getUserFaceId(), faceModel.getFaceFeature());
// }
// } else {
// showToast("人脸数据获取失败");
// }
// }
//
// @Override
// public void getFaceFeatureFail(String info) {
//
// }
//
//
// @Override
// public void getUserInfoSuccess(UserInfo userModel) {
// if (userModel == null) {
// showToast("获取用户信息失败");
// return;
// }
// firstWeight = 0;
// mUid = userModel.getUserId();
//
// userInfoLayout.setVisibility(View.VISIBLE);
// userNameTv.setText(userModel.getRealname());
// userCompanyTv.setText(userModel.getSecondDepartName());
//// mPresenter.bindDeviceMac(mUid, DeviceIdUtil.getDeviceId(this));
//
// Message message = new Message();
// message.what = 2;
// handler.sendMessageDelayed(message, 700);
//
// if (mCountDownTimer != null) {
// mCountDownTimer.cancel();
// mCountDownTimer.start();
// }
// }
//
// @Override
// public void getUserInfoFail(String info) {
//// Intent i = new Intent(this, RfidBindActivity.class);
//// i.putExtra("rfid", rfId);
//// startActivityForResult(i, 1001);
// }
//
// @Override
// public void getUserNutritionInfoSuccess(UserNutritionInfo userModel) {
// userNutritionInfo = userModel;
//
// energyKcal = userNutritionInfo.getEnergyKcal();
// totalWeight = userNutritionInfo.getFoodWeight();
//
// setEnergyKcal(energyKcal);
// dinnerMinTv.setText(userNutritionInfo.getRecommendMin() + "kcal");
// dinnerMaxTv.setText(userNutritionInfo.getRecommendMax() + "kcal");
// setBottomData(0, 0, 0, 0);
// }
//
// @Override
// public void getUserNutritionInfoFail(String info) {
//
// }
//
//
// @Override
// protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
// super.onActivityResult(requestCode, resultCode, data);
// if (requestCode == 1001 && data != null) {
// mUid = data.getStringExtra("userId");
// mPresenter.getUserInfoById(mUid);
// }
//
// }
//
// @Override
// public void getDeviceMacSuccess(DeviceMacModel deviceMacModel) {
// if (!deviceMacModel.getDeviceMac().equals(DeviceIdUtil.getDeviceId(this))) {//绑定设备已切换
// createRecord();
// }
// }
//
// private double anonymousLastWeight = 0;
// private long lastTimeMillis = 0;
// private final long ANONYMOUS_SUBMIT_INTERVAL = 1000 * 60;
//
// private void createAnonymousRecord() {
// long currentTime = System.currentTimeMillis();
// if (lastTimeMillis == 0) {
// lastTimeMillis = currentTime;
// }
// if (anonymousLastWeight == 0) {
// anonymousLastWeight = deviceWeight;
// }
// if (currentTime - lastTimeMillis > ANONYMOUS_SUBMIT_INTERVAL) {
// lastTimeMillis = currentTime;
// double currentIntake = anonymousLastWeight - deviceWeight;
// Log.e("mzf", "createAnonymousRecord===" + currentIntake + "");
// if (AppUtil.isEmpty(mUid)
// && currentIntake > OFFSET_WEIGHT) {
// String anonymousId = "anonymous_" + restNum + "_user_id_000";
// mPresenter.createRecord(anonymousId,
// foodNameTv.getTag().toString(), restNum, (int) currentIntake, deviceWeight);
//
// runOnUiThread(new Runnable() {
// @Override
// public void run() {
// resetData();
// }
// });
// }
// anonymousLastWeight = deviceWeight;
// }
//
// }
//
// private void createRecord() {
// if (!AppUtil.isEmpty(mUid)
// && intake > OFFSET_WEIGHT
// && !AppUtil.isEmpty(foodNameTv.getTag().toString())) {
// mPresenter.createRecord(mUid, foodNameTv.getTag().toString(), restNum, intake, deviceWeight);
// anonymousLastWeight = deviceWeight;
// }
// if (!AppUtil.isEmpty(mUid)) {
// runOnUiThread(new Runnable() {
// @Override
// public void run() {
// resetData();
// }
// });
// }
// }
//
// private void resetData() {
// //--------------初始化状态------------------------
// mUid = null;
// rfId = null;
// userInfoLayout.setVisibility(View.INVISIBLE);
// userNameTv.setText(null);
// userCompanyTv.setText(null);
//
// firstWeight = 0;
// currentWeight = 0;
// intake = 0;
// energyKcal = 0;
// userNutritionInfo = null;
// totalWeight = 0;
// setBottomData(0, 0, 0, 0);
// setEnergyKcal(0);
// setData(100, false);
//
// if (mCountDownTimer != null) {
// mCountDownTimer.cancel();
// }
// }
//
// @Override
// public void getDeviceMacFail(String info) {
//
// }
//
// private FoodInfoModel currentFoodInfo;
//
// @Override
// public void getFoodInfoByMacSuccess(FoodInfoModel foodInfoModel) {
// foodNameTv.setText(foodInfoModel.getFoodName());
// foodNameTv.setTag(foodInfoModel.getId());
//
// try {
// RequestOptions cropOptions = new RequestOptions();
// cropOptions.transform(new RoundedCorners(12));//new CenterCrop()
//
// Glide.with(this).load(URLDecoder.decode(foodInfoModel.getImgUrl(), "UTF-8"))
// .apply(cropOptions)
// .into(foodImg);
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
//
// ArrayList<String> tagArr = new ArrayList<>();
// String foodLabel = foodInfoModel.getFoodLabel();
// if (!AppUtil.isEmpty(foodLabel)) {
// String[] feedNameArr = foodLabel.split(",");
// for (String feedName : feedNameArr) {
// tagArr.add(feedName);
// }
// }
// if (tagArr.size() > 0) {
// MyFoodTagAdapters myFlowAdapters = new MyFoodTagAdapters(this, tagArr.size() > 4 ? tagArr.subList(0, 4) : tagArr);
// titleFlowLayout.setAdapter(myFlowAdapters);
// myFlowAdapters.notifyDataChanged();
// titleFlowLayout.setVisibility(View.VISIBLE);
// } else {
// titleFlowLayout.setVisibility(View.GONE);
// }
//
// currentFoodInfo = foodInfoModel;
//// setData(100, false);
//
// //初始化营养信息
// float kcal = AppUtil.formatFloat2((currentFoodInfo.getStFoodInfoMaterial().getEnergyKcal()));
// float fat = AppUtil.formatFloat2(currentFoodInfo.getStFoodInfoMaterial().getFat());
// float protein = AppUtil.formatFloat2(currentFoodInfo.getStFoodInfoMaterial().getProtein());
// float cho = AppUtil.formatFloat2(currentFoodInfo.getStFoodInfoMaterial().getCho());
// float na = AppUtil.formatFloat2(currentFoodInfo.getStFoodInfoMaterial().getNa() / 1000);
//
// calorieNumTv.setText(kcal + "");
// titleContentFat.setText("脂肪/" + fat + "g");
// titleContentCho.setText("碳水/" + cho + "g");
// titleContentProtein.setText("蛋白质/" + protein + "g");
// }
//
// @Override
// public void getFoodInfoByMacFail(String info) {
//
// }
//
// private ArrayList<DinnerModel> dinnerList;
// private float energyKcal = 0;
// private UserNutritionInfo userNutritionInfo;
// private float totalWeight = 0;
//
// @Override
// public void getMealRecordsInfoSuccess(MealRecordsInfo mealRecordsInfo) {
//// if (mealRecordsInfo != null && mealRecordsInfo.getNeedEnergyVo() != null) {
//// MealRecordsInfo.NeedEnergyVo needEnergyVo = mealRecordsInfo.getNeedEnergyVo();
//// dinnerList = new ArrayList<>();
//// dinnerList.add(new DinnerModel(needEnergyVo.getDinner1Min(), needEnergyVo.getDinner1Max()));
//// dinnerList.add(new DinnerModel(needEnergyVo.getDinner2Min(), needEnergyVo.getDinner2Max()));
//// dinnerList.add(new DinnerModel(needEnergyVo.getDinner3Min(), needEnergyVo.getDinner3Max()));
//// if (mealRecordsInfo.getFoodExtInfoVo() != null) {
//// foodExtInfoVo = mealRecordsInfo.getFoodExtInfoVo();
//// energyKcal = foodExtInfoVo.getEnergyKcal();
//// }
//// totalWeight = mealRecordsInfo.getTotalWeight();
//// mPresenter.getDinnerType();
//// }
// }
//
// @Override
// public void getMealRecordsInfoFail(String info) {
//
// }
//
//// private DinnerModel currentDinner;
//
// @Override
// public void getDinnerTypeSuccess(DinnerType dinnerType) {
// DinnerModel dinnerModel = dinnerList.get(dinnerType.getDinnerType() - 1);
//
// if (dinnerModel == null) {
// return;
// }
//
//// currentDinner = dinnerModel;
//// setEnergyKcal(energyKcal);
//// dinnerMinTv.setText(currentDinner.getDinnerMin() + "kcal");
//// dinnerMaxTv.setText(currentDinner.getDinnerMax() + "kcal");
//// setBottomData(0, 0, 0, 0);
// }
//
// private void setEnergyKcal(float kcal) {
// kcal = AppUtil.formatFloat2(kcal);
// if (userNutritionInfo == null) {
// mSeekBar.setProgress(0);
// bottomKcal.setText(kcal + "");
// return;
// }
//
// mSeekBar.setProgress((int) (kcal / userNutritionInfo.getRecommendMax() * 100));
// bottomKcal.setText(kcal + "");
//// mSeekBar.setTextInfo(kcal + "kcal");
//
//// if (kcal > currentDinner.getDinnerMax()) {
//// kcalYellowTv.setVisibility(View.INVISIBLE);
//// kcalBlueTv.setVisibility(View.INVISIBLE);
//// kcalRedTv.setVisibility(View.VISIBLE);
//// kcalRedTv.setText("能量:" + kcal + "kcal");
//// } else if (kcal > currentDinner.getDinnerMin()) {
//// kcalYellowTv.setVisibility(View.INVISIBLE);
//// kcalBlueTv.setVisibility(View.VISIBLE);
//// kcalRedTv.setVisibility(View.INVISIBLE);
//// kcalBlueTv.setText("能量:" + kcal + "kcal");
//// } else {
//// kcalYellowTv.setVisibility(View.VISIBLE);
//// kcalBlueTv.setVisibility(View.INVISIBLE);
//// kcalRedTv.setVisibility(View.INVISIBLE);
//// kcalYellowTv.setText("能量:" + kcal + "kcal");
//// }
// }
//
// @Override
// public void getDinnerTypeFail(String info) {
//
// }
//
// @Override
// public void createRecordSuccess(String info) {
//
// }
//
// @Override
// public void createRecordFail(String info) {
//
// }
//
// @Override
// public void getTokenSuccess(String info) {
//
// }
//
// @Override
// public void getTokenFail(String info) {
//
// }
//
// @Override
// public void addFoodWeightSuccess(String info) {
//
// }
//
// @Override
// public void addFoodWeightFail(String info) {
//
// }
//
//
// private final long COUNT_TIME = 60000 * 5; //5分钟倒计时提交数据
// private CountDownTimer mCountDownTimer;
//
// private void initTimer() {
// mCountDownTimer = new CountDownTimer(COUNT_TIME, 1000) {
// @Override
// public void onTick(long millisUntilFinished) {
// L.e("mCountDownTimer", millisUntilFinished / 1000 + "s");
// }
//
// @Override
// public void onFinish() {
// L.e("mCountDownTimer", "onFinish");
// createRecord();
// }
// };
// }
//
//
// private double deviceWeight = 0;
// private String rfId = "";
// private final String RFID_DEFAULT = "00000000";
//
//// SerialReadThread.ResponseListener responseListener = new SerialReadThread.ResponseListener() {
////
//// @Override
//// public void onGetRfid(String id) {
//// EventBus.getDefault().post(id);
//// if (id.equals(RFID_DEFAULT)) {
//// if (!AppUtil.isEmpty(rfId) &&
//// !rfId.equals(RFID_DEFAULT)) {
//// if (intake > 0) {
//// createRecord();
//// } else {
//// runOnUiThread(new Runnable() {
//// @Override
//// public void run() {
//// resetData();
//// }
//// });
//// }
//// }
//// return;
//// }
//// if (rfId != null && rfId.equals(id)) {
//// return;
//// }
//// rfId = id;
//// mPresenter.getUserInfo(rfId);
//// }
////
//// @Override
//// public void onGetWeightInfo(int weight) {
//// deviceWeight = weight;
//// if (firstWeight == 0) {//保存首次重量
//// firstWeight = weight;
//// }
//// currentWeight = weight;
////
//// if (firstWeight - currentWeight >= 0) {
//// intake = firstWeight - currentWeight;
//// runOnUiThread(new Runnable() {
//// @Override
//// public void run() {
//// setData(intake, true);
//// }
//// });
//// } else if (currentWeight - firstWeight > 100) {//大于100 认为是加菜
//// firstWeight = weight;
//// mPresenter.addFoodTotalWeight(currentFoodInfo.getId(),
//// 2, deviceWeight, restNum);
//// }
////// if (AppUtil.isEmpty(mUid) && intake > OFFSET_WEIGHT) {
////// Message message = new Message();
////// message.what = 1;
////// handler.sendMessage(message);
////// }
//// }
//// };
//
// @Override
// public void onValueSelected(Entry e, Highlight h) {
//
// }
//
// @Override
// public void onNothingSelected() {
//
// }
//}
@@ -0,0 +1,31 @@
package com.sw.st.ui.setting;
public class FoodListModel {
private String id;
private String foodName;
private String foodImg;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFoodName() {
return foodName;
}
public void setFoodName(String foodName) {
this.foodName = foodName;
}
public String getFoodImg() {
return foodImg;
}
public void setFoodImg(String foodImg) {
this.foodImg = foodImg;
}
}
@@ -0,0 +1,40 @@
package com.sw.st.ui.setting;
import android.content.Context;
import android.widget.TextView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.sw.st.R;
import com.sw.st.model.NewFoodInfoModel;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public class FoodNameAdapter extends BaseQuickAdapter<NewFoodInfoModel, BaseViewHolder> {
Context context;
public FoodNameAdapter(@Nullable List<NewFoodInfoModel> strs, Context context) {
super(R.layout.item_food_name_tv, strs);
this.context = context;
}
@Override
protected void convert(@NotNull BaseViewHolder baseViewHolder, NewFoodInfoModel info) {
TextView textView = baseViewHolder.findView(R.id.tv);
// baseViewHolder.setText(R.id.tv, info.getFoodName());
textView.setText(info.getFoodName());
textView.setSelected(info.isSelect());
if(info.isSelect()){
}else{
}
}
}
@@ -0,0 +1,544 @@
package com.sw.st.ui.setting;
import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Build;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.BarHide;
import com.gyf.immersionbar.ImmersionBar;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.HttpHeaders;
import com.sw.st.R;
import com.sw.st.base.BaseActivity;
import com.sw.st.model.FoodGoodsInfo;
import com.sw.st.model.NewFoodInfoModel;
import com.sw.st.model.UserFaceModel;
import com.sw.st.net.helper.Convert;
import com.sw.st.utils.AppUtil;
import com.sw.st.utils.InputMethod;
import com.sw.st.utils.L;
import com.sw.st.utils.PrefUtils;
import com.wabon.wbintelligenthardwaresdk.api.WeigherTwo;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import pub.devrel.easypermissions.EasyPermissions;
public class FoodSettingActivity extends BaseActivity<FoodSettingView, FoodSettingPresenter>
implements FoodSettingView {
private static final int REQUEST_CODE_QRCODE_PERMISSIONS = 1;
public static final int LEFT_WEIGHT_INDEX = 1;
public static final int RIGHT_WEIGHT_INDEX = 2;
private final String[] Permissions = {Manifest.permission.READ_PHONE_STATE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.VIBRATE};
public static final String REST_NUM = "restId";
public static final String REST_NAME = "restName";
public static final String CURRENT_FOOD_DATA = "current_food_data";
@BindView(R.id.setting_search_edit)
EditText searchEdit;
@BindView(R.id.setting_search_edit_cancel_img)
ImageView cancelImg;
// @BindView(R.id.item_shopping_flowlayout)
// TagFlowLayout flowLayout;
@BindView(R.id.setting_current_food_tv)
TextView currentFoodTv;
@BindView(R.id.currentWeight)
TextView currentWeight;
@BindView(R.id.start)
Button startButton;
@BindView(R.id.foodRecyclerView)
RecyclerView foodRecyclerView;
// private MyFlowAdapters myFlowAdapters;
private FoodNameAdapter foodNameAdapter;
private ArrayList<NewFoodInfoModel> foodTagList = new ArrayList<>();
private NewFoodInfoModel currentFoodInfo;
private String restNo = "99";
private ArrayList<NewFoodInfoModel> allFoodList = new ArrayList<>();
private ArrayList<NewFoodInfoModel> searchResultFoodList = new ArrayList<>();
private int deviceWeight = 0;
private boolean isInitScale = false;
private double leftDeviceWeight = 0;
private double rightDeviceWeight = 0;
private int currentDeviceIndex = LEFT_WEIGHT_INDEX;
@Override
protected int provideContentViewId() {
return R.layout.activity_setting;
}
@Override
public void init() {
super.init();
if (!EasyPermissions.hasPermissions(this, Permissions)) {
EasyPermissions.requestPermissions(this, "扫描二维码需要打开相机和文件权限", REQUEST_CODE_QRCODE_PERMISSIONS, Permissions);
}
WeigherTwo.init("/dev/ttyS7");
}
@Override
public void initView() {
ImmersionBar.with(this)
.hideBar(BarHide.FLAG_HIDE_BAR)
.statusBarAlpha(0f)
.statusBarDarkFont(true)
.statusBarColor(R.color.white)
.init();
}
@Override
public void initData() {
initScale();
mPresenter.getToken(AppUtil.getUDID(mContext));
foodNameAdapter = new FoodNameAdapter(null, mContext);
foodRecyclerView.setAdapter(foodNameAdapter);
}
@Override
public void initListener() {
searchEdit.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (AppUtil.isEmpty(s.toString())) {
cancelImg.setVisibility(View.GONE);
} else {
cancelImg.setVisibility(View.VISIBLE);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
searchEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
// 当按了搜索之后关闭软键盘
InputMethod.closeInputMethod(FoodSettingActivity.this, v);
searchResultFoodList.clear();
mPresenter.getRestInfoFoodsByName(restNo, searchEdit.getText().toString());
return true;
}
return false;
}
});
foodNameAdapter.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
// 当按了搜索之后关闭软键盘
InputMethod.closeInputMethod(FoodSettingActivity.this, startButton);
startButton.setVisibility(View.VISIBLE);
currentFoodInfo = (NewFoodInfoModel) adapter.getItem(position);
currentFoodTv.setText(currentFoodInfo.getFoodName());
List<NewFoodInfoModel> foodInfoModelList = foodNameAdapter.getData();
for (NewFoodInfoModel foodInfoModel : foodInfoModelList) {
foodInfoModel.setSelect(false);
}
foodNameAdapter.getItem(position).setSelect(true);
foodNameAdapter.notifyDataSetChanged();
mPresenter.getGoodsUseList(currentFoodInfo.getId(), 1000);
}
});
}
@OnClick({R.id.setting_search_edit_cancel_img, R.id.back,
R.id.start, R.id.currentWeight, R.id.zeroTv, R.id.zeroTitleTv})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.title_name_tv:
break;
case R.id.title_back_iv:
finish();
break;
case R.id.setting_search_edit_cancel_img:
searchEdit.setText(null);
InputMethod.closeInputMethod(this, view);
if (foodTagList == null || foodTagList.size() == 0) {
// myFlowAdapters = new MyFlowAdapters(this, allFoodList);
foodNameAdapter.setList(allFoodList);
} else {
foodNameAdapter.setList(foodTagList);
}
break;
case R.id.back:
finish();
break;
case R.id.start:
currentDeviceIndex=RIGHT_WEIGHT_INDEX;
break;
case R.id.currentWeight:
currentDeviceIndex=RIGHT_WEIGHT_INDEX;
break;
case R.id.zeroTitleTv:
showProgress("请稍候...");
weightZero(currentDeviceIndex);
break;
case R.id.zeroTv:
weightTare(currentDeviceIndex);
break;
}
}
@Override
protected FoodSettingPresenter createPresenter() {
return new FoodSettingPresenter();
}
@Override
protected void afterRequestPermission(int requestCode, boolean isAllGranted) {
}
@Override
public void getFoodListSuccess(ArrayList<NewFoodInfoModel> list, String type) {
switch (type) {
case "0":
allFoodList = list;
L.e("FoodListSize===" + allFoodList.size());
if (foodTagList == null || foodTagList.size() == 0) {
foodNameAdapter.setList(allFoodList);
}
break;
case "1":
foodTagList = list;
foodNameAdapter.setList(foodTagList);
break;
}
}
@Override
public void getFoodListFail(String info) {
}
@Override
public void getTokenSuccess(String info) {
String token = info;
if (!TextUtils.isEmpty(token)) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.headersMap.put("Authorization", token);
OkGo.getInstance().addCommonHeaders(httpHeaders);
}
mPresenter.getRestInfoFoodsByType(restNo, "1");
// mPresenter.getRestInfoFoodsByType(restNo, "0");
}
@Override
public void getTokenFail(String info) {
}
@Override
public void addFoodWeightSuccess(String info) {
String currentFoodInfoStr = Convert.toJson(currentFoodInfo);
L.e(currentFoodInfoStr);
PrefUtils.setString(FoodSettingActivity.this, CURRENT_FOOD_DATA, currentFoodInfoStr);
finish();
}
@Override
public void addFoodWeightFail(String info) {
hideProgress();
showToast(info);
}
@Override
public void getRestInfoSuccess(String info) {
Log.e("mzf", info);
try {
JSONObject jsonInfo = new JSONObject(info);
String restName = jsonInfo.optString("restName");
// String restNo = jsonInfo.optString("restNo");
String restId = jsonInfo.getString("id");
PrefUtils.setString(this, REST_NAME, restName);
PrefUtils.setString(this, REST_NUM, restId);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void getRestInfoFail(String info) {
showToast(info);
Dialog alertDialog = new AlertDialog.Builder(this)
.setTitle("失败")
.setMessage(info)
.create();
alertDialog.show();
}
@Override
public void getFaceFeatureSuccess(ArrayList<UserFaceModel> list) {
}
@Override
public void getFaceFeatureFail(String info) {
}
@Override
public void searchFoodListSuccess(ArrayList<NewFoodInfoModel> list) {
searchResultFoodList = list;
foodNameAdapter.setList(searchResultFoodList);
}
@Override
public void searchFoodListFail(String info) {
}
ArrayList<FoodGoodsInfo> foodGoodsInfoArrayList;
@Override
public void getGoodsUseListSuccess(String info) {
try {
JSONObject jsonObject = new JSONObject(info);
foodGoodsInfoArrayList = Convert.fromJson(jsonObject.optString("voList"), new TypeToken<ArrayList<FoodGoodsInfo>>() {
}.getType());
L.e("size===" + foodGoodsInfoArrayList.size());
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
@Override
public void getGoodsUseListFail(String info) {
}
@Override
public void saveFoodGoodsUseInfoSuccess(String info) {
}
@Override
public void saveFoodGoodsUseInfoFail(String info) {
}
@Override
public void showProgress(String tipString) {
showWaitingDialog(tipString);
}
@Override
public void hideProgress() {
hideWaitingDialog();
}
@Override
protected void onDestroy() {
super.onDestroy();
try {
WeigherTwo.unInit();
} catch (Exception e) {
e.printStackTrace();
}
System.exit(0);
}
public void weightZero(int index) {
WeigherTwo.zeroTwo(index);
}
public void weightTare(int index) {
WeigherTwo.tareTwo(index);
}
/**
* 初始化称体
*/
private void initScale() {
WeigherTwo.setListener(new WeigherTwo.Listener() {
@Override
public void onInit(boolean connect) {
L.e("onZero onInit===" + connect);
if (connect) {//初始化成功
// Weigher.getWeight();
WeigherTwo.startContinuousRead();
WeigherTwo.zeroTwo(LEFT_WEIGHT_INDEX);
isInitScale = true;
} else {//失败再次尝试
WeigherTwo.init("/dev/ttyS7");
}
}
@Override
public void onZero() {
if (isInitScale) {//初始化后置零需要一个一个操作,两个同时会失败
isInitScale = false;
WeigherTwo.zeroTwo(RIGHT_WEIGHT_INDEX);
}
}
@Override
public void onGetWeight(int address, int state, int weight) {
String stateStr = "";
// switch (state) {
// case SensorScale.STATE_STABLE:
// stateStr = "稳定";
// break;
// case SensorScale.STATE_UNSTABLE:
// stateStr = "不稳定";
// return;
// case SensorScale.STATE_OVER_WEIGHT:
// stateStr = "量程溢出";
// return;
// }
if (address == LEFT_WEIGHT_INDEX) {
leftDeviceWeight = weight;
}
if (address == RIGHT_WEIGHT_INDEX) {
rightDeviceWeight = weight;
}
//======================================================
runOnUiThread(new Runnable() {
@Override
public void run() {
if (currentDeviceIndex == LEFT_WEIGHT_INDEX) {
currentWeight.setText(formatWeight(leftDeviceWeight));
} else if (currentDeviceIndex == RIGHT_WEIGHT_INDEX) {
currentWeight.setText(formatWeight(rightDeviceWeight));
}
}
});
}
@Override
public void onTare() {
}
@Override
public void onSetIdentify() {
}
@Override
public void onReadIdentify(int rate) {
}
@Override
public void onFail(int errCode) {
String str = "";
switch (errCode) {
case WeigherTwo.ERR_001:
str = "电子称未初始化";
break;
case WeigherTwo.ERR_002:
str = "开机零位异常";
break;
case WeigherTwo.ERR_003:
str = "传感器故障";
break;
case WeigherTwo.ERR_004:
str = "鉴别率超出范围";
break;
case WeigherTwo.ERR_PCB_NOT_SUPPORT:
str = "主板不支持, " + Build.MODEL;
break;
}
}
@Override
public void onFastFilter() {
}
@Override
public void onReadParam() {
}
@Override
public void onRangCal() {
}
});
}
private String formatWeight(double weight) {
// weight = weight < 0 ? 0 : weight;
if (weight > 1000) {
return "余量 " + AppUtil.formatDouble(weight / 1000) + " 千克";
} else {
return "余量 " + weight + "";
}
}
}
@@ -0,0 +1,290 @@
package com.sw.st.ui.setting;
import com.sw.st.api.SwService;
import com.sw.st.base.BasePresenter;
import com.sw.st.model.FoodInfoModel;
import com.sw.st.model.NewFoodInfoModel;
import com.sw.st.model.UserFaceModel;
import com.sw.st.net.helper.rxjavahelper.RxObserver;
import com.sw.st.net.helper.rxjavahelper.RxResultHelper;
import com.sw.st.net.helper.rxjavahelper.RxSchedulersHelper;
import com.sw.st.ui.device.BindDeviceModel;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import io.reactivex.disposables.Disposable;
public class FoodSettingPresenter extends BasePresenter<FoodSettingView> {
public void getRestInfoFoodsByType(String restNo, String type) {
SwService.getRestInfoFoodsByType(restNo, type)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleResult())
.subscribe(new RxObserver<ArrayList<NewFoodInfoModel>>() {
@Override
public void _onSubscribe(Disposable d) {
}
@Override
public void _onNext(ArrayList<NewFoodInfoModel> info) {
if (getView() != null)
getView().getFoodListSuccess(info, type);
}
@Override
public void _onError(String errorMessage) {
if (getView() != null)
getView().getFoodListFail(errorMessage);
}
@Override
public void _onComplete() {
if (getView() != null)
getView().hideProgress();
}
});
}
public void getRestInfoFoodsByName(String restNo, String foodName) {
getView().showProgress("搜索中...");
SwService.getRestInfoFoodsByName(restNo, foodName)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleResult())
.subscribe(new RxObserver<ArrayList<NewFoodInfoModel>>() {
@Override
public void _onSubscribe(Disposable d) {
}
@Override
public void _onNext(ArrayList<NewFoodInfoModel> info) {
if (getView() != null) {
getView().searchFoodListSuccess(info);
getView().hideProgress();
}
}
@Override
public void _onError(String errorMessage) {
if (getView() != null) {
getView().searchFoodListFail(errorMessage);
getView().hideProgress();
}
}
@Override
public void _onComplete() {
}
});
}
public void getToken(String devId) {
SwService.getToken(devId)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleJsonResponse())
.subscribe(new RxObserver<String>() {
@Override
public void _onSubscribe(Disposable d) {
}
@Override
public void _onNext(String info) {
try {
JSONObject jsonObject = new JSONObject(info);
if (jsonObject.optInt("code") == 200) {
String data = jsonObject.optString("data");
if (getView() != null)
getView().getTokenSuccess(data);
}
} catch (JSONException e) {
e.printStackTrace();
if (getView() != null)
getView().getTokenFail("数据解析异常");
}
}
@Override
public void _onError(String errorMessage) {
if (getView() != null)
getView().getTokenFail(errorMessage);
}
@Override
public void _onComplete() {
}
});
}
/**
* @param foodId 菜品ID
* @param type 1开餐,2加菜
* @param totalWeight 菜品增重
* @return
*/
public void startMealService(String foodId, int type, double totalWeight, String deviceMac) {
SwService.startMealService(foodId, type, totalWeight, deviceMac)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleJsonResponse())
.subscribe(new RxObserver<String>() {
@Override
public void _onSubscribe(Disposable d) {
}
@Override
public void _onNext(String info) {
try {
JSONObject jsonObject = new JSONObject(info);
if (jsonObject.optInt("code") == 200) {
String data = jsonObject.optString("data");
if (getView() != null)
getView().addFoodWeightSuccess(data);
} else {
getView().addFoodWeightFail(jsonObject.optString("message"));
}
} catch (JSONException e) {
e.printStackTrace();
if (getView() != null)
getView().addFoodWeightFail("数据解析异常");
}
}
@Override
public void _onError(String errorMessage) {
if (getView() != null)
getView().addFoodWeightFail(errorMessage);
}
@Override
public void _onComplete() {
}
});
}
public void getRestInfoByRestNo(String restNo) {
getView().showProgress("查询中...");
SwService.getRestInfoByRestNo(restNo)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleJsonResponse())
.subscribe(new RxObserver<String>() {
@Override
public void _onSubscribe(Disposable d) {
}
@Override
public void _onNext(String info) {
try {
JSONObject jsonObject = new JSONObject(info);
if (jsonObject.optInt("code") == 200) {
String data = jsonObject.optString("result");
if (getView() != null) {
getView().getRestInfoSuccess(data);
getView().hideProgress();
}
} else {
String message = jsonObject.optString("message");
if (getView() != null) {
getView().getRestInfoFail(message);
getView().hideProgress();
}
}
} catch (JSONException e) {
e.printStackTrace();
if (getView() != null) {
getView().getRestInfoFail("数据解析异常");
getView().hideProgress();
}
}
}
@Override
public void _onError(String errorMessage) {
if (getView() != null) {
getView().getRestInfoFail(errorMessage);
getView().hideProgress();
}
}
@Override
public void _onComplete() {
}
});
}
public void getUserFace() {
SwService.getUserFace()
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleResult())
.subscribe(new RxObserver<ArrayList<UserFaceModel>>() {
@Override
public void _onSubscribe(Disposable d) {
getView().showProgress("加载中...");
}
@Override
public void _onNext(ArrayList<UserFaceModel> list) {
getView().getFaceFeatureSuccess(list);
}
@Override
public void _onError(String errorMessage) {
getView().getFaceFeatureFail(errorMessage);
getView().hideProgress();
}
@Override
public void _onComplete() {
getView().hideProgress();
}
});
}
public void getGoodsUseList(String foodId, double foodWeight) {
SwService.getGoodsUseList(foodId, foodWeight)
.compose(RxSchedulersHelper.io_main())
.compose(RxResultHelper.handleJsonResponse())
.subscribe(new RxObserver<String>() {
@Override
public void _onSubscribe(Disposable d) {
}
@Override
public void _onNext(String info) {
try {
JSONObject jsonObject = new JSONObject(info);
if (jsonObject.optInt("code") == 200) {
String data = jsonObject.optString("data");
if (getView() != null)
getView().getGoodsUseListSuccess(data);
}
} catch (JSONException e) {
e.printStackTrace();
if (getView() != null)
getView().getGoodsUseListFail("数据解析异常");
}
}
@Override
public void _onError(String errorMessage) {
if (getView() != null)
getView().getGoodsUseListFail(errorMessage);
}
@Override
public void _onComplete() {
}
});
}
}
@@ -0,0 +1,47 @@
package com.sw.st.ui.setting;
import com.sw.st.base.BaseView;
import com.sw.st.model.FoodInfoModel;
import com.sw.st.model.NewFoodInfoModel;
import com.sw.st.model.UserFaceModel;
import java.util.ArrayList;
public interface FoodSettingView extends BaseView {
void getFoodListSuccess(ArrayList<NewFoodInfoModel> list, String type);
void getFoodListFail(String info);
void getTokenSuccess(String info);
void getTokenFail(String info);
void addFoodWeightSuccess(String info);
void addFoodWeightFail(String info);
void getRestInfoSuccess(String info);
void getRestInfoFail(String info);
void getFaceFeatureSuccess(ArrayList<UserFaceModel> list);
void getFaceFeatureFail(String info);
void searchFoodListSuccess(ArrayList<NewFoodInfoModel> list);
void searchFoodListFail(String info);
void getGoodsUseListSuccess(String info);
void getGoodsUseListFail(String info);
void saveFoodGoodsUseInfoSuccess(String info);
void saveFoodGoodsUseInfoFail(String info);
}
@@ -0,0 +1,37 @@
package com.sw.st.ui.setting;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import com.sw.st.R;
import com.sw.st.model.FoodInfoModel;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import java.util.List;
/**
* Created by Administrator on 2019/4/23 0023.
*/
public class MyFlowAdapters extends TagAdapter<FoodInfoModel> {
private Context context;
public MyFlowAdapters(Context context, List<FoodInfoModel> datas) {
super(datas);
this.context = context;
}
@Override
public View getView(FlowLayout parent, int position, FoodInfoModel foodListModel) {
LayoutInflater inflater = LayoutInflater.from(context);
TextView tv = (TextView) inflater.inflate(R.layout.item_flow_tv, parent, false);
tv.setText(foodListModel.getFoodName());
return tv;
}
}
@@ -0,0 +1,661 @@
package com.sw.st.utils;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.ActivityNotFoundException;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.TextView;
import androidx.core.content.FileProvider;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.Locale;
import java.util.UUID;
import static android.content.Context.TELEPHONY_SERVICE;
public class AppUtil {
public static String getAppPackageName(Context context) {
String packageName = "";
try {
PackageManager pm = context.getPackageManager();
PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
packageName = pi.packageName;
if (AppUtil.isEmpty(packageName)) {
return "";
}
} catch (Exception e) {
e.printStackTrace();
}
return packageName + ".single";
}
public static String getAppVersionName(Context context) {
String versionName = "";
// int versioncode=1;
try {
PackageManager pm = context.getPackageManager();
PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
versionName = pi.versionName;
// versioncode = pi.versionCode;表示更新了多少次
if (versionName == null || versionName.length() <= 0) {
return "";
}
} catch (Exception e) {
e.printStackTrace();
}
return versionName;
}
public static int getAppVersionCode(Context context) {
int versioncode = 1;
try {
PackageManager pm = context.getPackageManager();
PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
versioncode = pi.versionCode;
} catch (Exception e) {
e.printStackTrace();
}
return versioncode;
}
/**
* 打电话
* <p>
* Intent.ACTION_DIAL Intent.ACTION_CALL
*
* @param context
* @param mobile
*/
public static void callUp(Context context, String mobile) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"
+ mobile));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
/**
* 获取设备ID
*
* @param context
* @return
*/
public static String getDevId(Context context) {
TelephonyManager TelephonyMgr = (TelephonyManager) context
.getSystemService(TELEPHONY_SERVICE);
return TelephonyMgr.getDeviceId();
}
public static String formatDateGetFull(String date) {
if (isEmpty(date)) {
return "";
}
Date d = new Date(Long.parseLong(date));
SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
return dateFormat1.format(d);
}
public static String formatDateGetCurrentTime() {
Date d = new Date(System.currentTimeMillis());
SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
return dateFormat1.format(d);
}
public static String formatDateGetDayWeek(long date) {
if (date == 0) {
return "";
}
Date d = new Date(date);
SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd EEEE");
return dateFormat1.format(d);
}
public static String formatDateGetFull(long date) {
if (date == 0) {
return "";
}
Date d = new Date(date);
SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
return dateFormat1.format(d);
}
public static String formatDateGetDay(long date) {
if (date == 0) {
return "";
}
Date d = new Date(date);
SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
return dateFormat1.format(d);
}
public static boolean isEmpty(String s) {
if (TextUtils.isEmpty(s) || s.trim().equals("null")) {
return true;
} else {
return false;
}
}
/**
* 格式化浮点型
*
* @param data
* @return
*/
public static String formatDouble(double data) {
return new DecimalFormat("0.00").format(data);
}
/**
* 格式化分钟
*
* @param minutes
* @return
*/
public static String formatMinutes(int minutes) {
int hour = minutes / 60;
int minute = minutes % 60;
if (hour > 0 && minute > 0) {
return hour + "小时" + minute + "分钟";
} else if (hour > 0) {
return hour + "小时";
} else {
return minute + "分钟";
}
}
//com.fawan.news
public static void goToMarket(Context context, String packageName) {
Uri uri = Uri.parse("market://details?id=" + packageName);
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
try {
context.startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
}
/**
* true为存在,false为不存在
*
* @param context
* @param packageName
* @return
*/
public static boolean isInstallApp(Context context, String packageName) {
try {
context.getPackageManager().getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
return true;
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
/**
* 格式化float 保留两位小数
*
* @param data
* @return
*/
public static float formatFloat2(float data) {
// DecimalFormat decimalFormat = new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
// return decimalFormat.format(data);//返回字符串
int scale = 2;//设置位数
int roundingMode = 4;//表示四舍五入,可以选择其他舍值方式,例如去尾,等等.
BigDecimal bd = new BigDecimal((double) data);
bd = bd.setScale(scale, roundingMode);
data = bd.floatValue();
return data;
}
/**
* 格式化float 保留两位小数
*
* @param data
* @return
*/
public static float formatFloat1(float data) {
// DecimalFormat decimalFormat = new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
// return decimalFormat.format(data);//返回字符串
int scale = 1;//设置位数
int roundingMode = 4;//表示四舍五入,可以选择其他舍值方式,例如去尾,等等.
BigDecimal bd = new BigDecimal((double) data);
bd = bd.setScale(scale, roundingMode);
data = bd.floatValue();
return data;
}
/**
* 格式化浮点型
*
* @param data
* @return
*/
public static String formatDouble1(double data) {
return new DecimalFormat("0.0").format(data);
}
/**
* Android 6.0 之前(不包括6.0)获取mac地址
* 必须的权限 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
*
* @param context * @return
*/
public static String getMacDefault(Context context) {
String mac = "";
if (context == null) {
return mac;
}
WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo info = null;
try {
info = wifi.getConnectionInfo();
} catch (Exception e) {
e.printStackTrace();
}
if (info == null) {
return null;
}
mac = info.getMacAddress();
if (!TextUtils.isEmpty(mac)) {
mac = mac.toUpperCase(Locale.ENGLISH);
}
return mac;
}
/**
* Android 6.0-Android 7.0 获取mac地址
*/
public static String getMacAddress() {
String macSerial = null;
String str = "";
try {
Process pp = Runtime.getRuntime().exec("cat/sys/class/net/wlan0/address");
InputStreamReader ir = new InputStreamReader(pp.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
while (null != str) {
str = input.readLine();
if (str != null) {
macSerial = str.trim();//去空格
break;
}
}
} catch (IOException ex) {
// 赋予默认值
ex.printStackTrace();
}
return macSerial;
}
/**
* Android 7.0之后获取Mac地址
* 遍历循环所有的网络接口,找到接口是 wlan0
* 必须的权限 <uses-permission android:name="android.permission.INTERNET"></uses-permission>
*
* @return
*/
public static String getMacFromHardware() {
try {
ArrayList<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif : all) {
if (!nif.getName().equals("wlan0"))
continue;
byte[] macBytes = nif.getHardwareAddress();
if (macBytes == null) return "";
StringBuilder res1 = new StringBuilder();
for (Byte b : macBytes) {
res1.append(String.format("%02X:", b));
}
if (!TextUtils.isEmpty(res1)) {
res1.deleteCharAt(res1.length() - 1);
}
return res1.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* 获取mac地址(适配所有Android版本)
*
* @return
*/
public static String getMac(Context context) {
String mac = "";
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
mac = getMacDefault(context);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
mac = getMacAddress();
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mac = getMacFromHardware();
}
return mac;
}
//把String转化为float
public static double convertToFloat(String number, double defaultValue) {
if (TextUtils.isEmpty(number)) {
return defaultValue;
}
try {
return Double.parseDouble(number);
} catch (Exception e) {
return defaultValue;
}
}
/**
* 获取设备唯一 UDID
*
* @param context
* @return
*/
@SuppressLint("MissingPermission")
public static String getUDID(Context context) {
// return "SWSN:" + getMac(context);
String mac = getMac(context);
if (isEmpty(mac)) {
String androidID = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
if (!androidID.equals("")) {
try {
if (!"9774d56d682e549c".equals(androidID)) {
androidID = UUID.nameUUIDFromBytes(androidID.getBytes("utf8")).toString();
} else {
@SuppressLint("MissingPermission") final String deviceId = ((TelephonyManager) context.getSystemService(TELEPHONY_SERVICE)).getDeviceId();
androidID = deviceId != null ? UUID.nameUUIDFromBytes(deviceId.getBytes("utf8")).toString() : UUID.randomUUID().toString();
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return androidID;
}
//需要权限 android.permission.READ_PHONE_STATE
TelephonyManager TelephonyMgr = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
String szImei = TelephonyMgr.getDeviceId();
if (!szImei.equals("")) {
return szImei;
}
//需要权限 android.permission.ACCESS_WIFI_STATE
WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
String m_szWLANMAC = wm.getConnectionInfo().getMacAddress();
if (!m_szWLANMAC.equals("")) {
return m_szWLANMAC;
}
//需要权限 android.permission.BLUETOOTH
BluetoothAdapter m_BluetoothAdapter = null;
m_BluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
String m_szBTMAC = m_BluetoothAdapter.getAddress();
if (!m_szBTMAC.equals("")) {
return m_szBTMAC;
}
return getUniquePsuedoID();
} else
return "SWSN:" + getMac(context);
}
//获得 Psuedo ID
public static String getUniquePsuedoID() {
String serial = null;
String m_szDevIDShort = "35" +
Build.BOARD.length() % 10 + Build.BRAND.length() % 10 +
Build.CPU_ABI.length() % 10 + Build.DEVICE.length() % 10 +
Build.DISPLAY.length() % 10 + Build.HOST.length() % 10 +
Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 +
Build.MODEL.length() % 10 + Build.PRODUCT.length() % 10 +
Build.TAGS.length() % 10 + Build.TYPE.length() % 10 +
Build.USER.length() % 10; //13 位
try {
serial = android.os.Build.class.getField("SERIAL").get(null).toString();
//API>=9 使用serial号
return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
} catch (Exception exception) {
//serial需要一个初始化,随意值
serial = "serial";
}
//使用硬件信息拼凑出来的15位号码
return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
}
/**
* 安装apk
*
* @param activity
* @param apkFile
*/
public static void installApk(Context activity, File apkFile) {
//文件有所有者概念,现在是属于当前进程的,需要把这个文件暴露给系统安装程序(其他进程)去安装
//因此,可能会存在权限问题,需要做下面的设置
//如果文件是sdcard上的,就不需要这个操作了
try {
apkFile.setExecutable(true, false);
apkFile.setReadable(true, false);
apkFile.setWritable(true, false);
} catch (Exception e) {
e.printStackTrace();
}
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
Uri uri;
//TODO N FileProvider
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(activity, activity.getPackageName() + ".fileProvider", apkFile);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
} else {
uri = Uri.fromFile(apkFile);
}
intent.setDataAndType(uri, "application/vnd.android.package-archive");
activity.startActivity(intent);
//TODO 0 INSTALL PERMISSION
//在AndroidManifest中加入权限即可
}
/*
  @pararm apkPath 等待安装的app全路径,如:/sdcard/app/app.apk
**/
public static boolean clientInstall(String apkPath) {
PrintWriter PrintWriter = null;
Process process = null;
try {
process = Runtime.getRuntime().exec("su");
PrintWriter = new PrintWriter(process.getOutputStream());
PrintWriter.println("chmod 777 " + apkPath);
PrintWriter
.println("export LD_LIBRARY_PATH=/vendor/lib:/system/lib");
PrintWriter.println("pm install -r " + apkPath);
// PrintWriter.println("exit");
PrintWriter.flush();
PrintWriter.close();
int value = process.waitFor();
L.e("静默安装返回值:" + value);
return true;
// return returnResult(value);
} catch (Exception e) {
e.printStackTrace();
L.e("安装apk出现异常");
} finally {
if (process != null) {
process.destroy();
}
}
return false;
}
private void execLinuxCommand() {
String cmd = "sleep 120; am start -n 包名/包名.第一个Activity的名称";
//Runtime对象
Runtime runtime = Runtime.getRuntime();
try {
Process localProcess = runtime.exec("su");
OutputStream localOutputStream = localProcess.getOutputStream();
DataOutputStream localDataOutputStream = new DataOutputStream(localOutputStream);
localDataOutputStream.writeBytes(cmd);
localDataOutputStream.flush();
L.e("设备准备重启");
} catch (IOException e) {
L.i("strLine:" + e.getMessage());
e.printStackTrace();
}
}
/**
* 判断网络连接状态
*
* @param context
* @return
*/
public static boolean isNetworkConnected(Context context) {
if (context != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
if (mNetworkInfo != null) {
return mNetworkInfo.isAvailable();
}
}
return false;
}
/**
* 判断WiFi连接状态
*
* @param context
* @return
*/
public static boolean isWifiConnected(Context context) {
if (context != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWiFiNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWiFiNetworkInfo != null) {
return mWiFiNetworkInfo.isAvailable();
}
}
return false;
}
/**
* 判断移动网络状态
*
* @param context
* @return
*/
public static boolean isMobileConnected(Context context) {
if (context != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mMobileNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mMobileNetworkInfo != null) {
return mMobileNetworkInfo.isAvailable();
}
}
return false;
}
/**
* 获取网络连接类型
*
* @param context
* @return
*/
public static int getConnectedType(Context context) {
if (context != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {
return mNetworkInfo.getType();
}
}
return -1;
}
public static int getMaxInt(int a, int b, int c) {
// 使用Math.max获取两个中的最大值
int max1 = Math.max(a, b);
int max2 = Math.max(max1, c); // 使用之前计算的最大值来比较第三个
return max2;
}
public static int getMinInt(int a, int b, int c) {
// 使用Math.min获取两个中的最小值
int min1 = Math.min(a, b);
int min2 = Math.min(min1, c); // 使用之前计算的最小值来比较第三个
return min2;
}
}
@@ -0,0 +1,268 @@
package com.sw.st.utils;
public final class Base64 {
private static final int BASELENGTH = 128;
private static final int LOOKUPLENGTH = 64;
private static final int TWENTYFOURBITGROUP = 24;
private static final int EIGHTBIT = 8;
private static final int SIXTEENBIT = 16;
private static final int FOURBYTE = 4;
private static final int SIGN = -128;
private static char PAD = '=';
private static byte[] base64Alphabet = new byte[BASELENGTH];
private static char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH];
static {
for (int i = 0; i < BASELENGTH; ++i) {
base64Alphabet[i] = -1;
}
for (int i = 'Z'; i >= 'A'; i--) {
base64Alphabet[i] = (byte) (i - 'A');
}
for (int i = 'z'; i >= 'a'; i--) {
base64Alphabet[i] = (byte) (i - 'a' + 26);
}
for (int i = '9'; i >= '0'; i--) {
base64Alphabet[i] = (byte) (i - '0' + 52);
}
base64Alphabet['+'] = 62;
base64Alphabet['/'] = 63;
for (int i = 0; i <= 25; i++) {
lookUpBase64Alphabet[i] = (char) ('A' + i);
}
for (int i = 26, j = 0; i <= 51; i++, j++) {
lookUpBase64Alphabet[i] = (char) ('a' + j);
}
for (int i = 52, j = 0; i <= 61; i++, j++) {
lookUpBase64Alphabet[i] = (char) ('0' + j);
}
lookUpBase64Alphabet[62] = (char) '+';
lookUpBase64Alphabet[63] = (char) '/';
}
private static boolean isWhiteSpace(char octect) {
return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
}
private static boolean isPad(char octect) {
return (octect == PAD);
}
private static boolean isData(char octect) {
return (octect < BASELENGTH && base64Alphabet[octect] != -1);
}
/**
* Encodes hex octects into Base64
*
* @param binaryData
* Array containing binaryData
* @return Encoded Base64 array
*/
public static String encode(byte[] binaryData) {
if (binaryData == null) {
return null;
}
int lengthDataBits = binaryData.length * EIGHTBIT;
if (lengthDataBits == 0) {
return "";
}
int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1
: numberTriplets;
char encodedData[] = null;
encodedData = new char[numberQuartet * 4];
byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
int encodedIndex = 0;
int dataIndex = 0;
for (int i = 0; i < numberTriplets; i++) {
b1 = binaryData[dataIndex++];
b2 = binaryData[dataIndex++];
b3 = binaryData[dataIndex++];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
: (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)
: (byte) ((b2) >> 4 ^ 0xf0);
byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6)
: (byte) ((b3) >> 6 ^ 0xfc);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];
encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
}
// form integral number of 6-bit groups
if (fewerThan24bits == EIGHTBIT) {
b1 = binaryData[dataIndex];
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
: (byte) ((b1) >> 2 ^ 0xc0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];
encodedData[encodedIndex++] = PAD;
encodedData[encodedIndex++] = PAD;
} else if (fewerThan24bits == SIXTEENBIT) {
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
: (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)
: (byte) ((b2) >> 4 ^ 0xf0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];
encodedData[encodedIndex++] = PAD;
}
return new String(encodedData);
}
/**
* Decodes Base64 data into octects
*
* @param encoded
* string containing Base64 data
* @return Array containind decoded data.
*/
public static byte[] decode(String encoded) {
if (encoded == null) {
return null;
}
char[] base64Data = encoded.toCharArray();
// remove white spaces
int len = removeWhiteSpace(base64Data);
if (len % FOURBYTE != 0) {
return null;// should be divisible by four
}
int numberQuadruple = (len / FOURBYTE);
if (numberQuadruple == 0) {
return new byte[0];
}
byte decodedData[] = null;
byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
char d1 = 0, d2 = 0, d3 = 0, d4 = 0;
int i = 0;
int encodedIndex = 0;
int dataIndex = 0;
decodedData = new byte[(numberQuadruple) * 3];
for (; i < numberQuadruple - 1; i++) {
if (!isData((d1 = base64Data[dataIndex++]))
|| !isData((d2 = base64Data[dataIndex++]))
|| !isData((d3 = base64Data[dataIndex++]))
|| !isData((d4 = base64Data[dataIndex++]))) {
return null;
}// if found "no data" just return null
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
}
if (!isData((d1 = base64Data[dataIndex++]))
|| !isData((d2 = base64Data[dataIndex++]))) {
return null;// if found "no data" just return null
}
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
d3 = base64Data[dataIndex++];
d4 = base64Data[dataIndex++];
if (!isData((d3)) || !isData((d4))) {// Check if they are PAD characters
if (isPad(d3) && isPad(d4)) {
if ((b2 & 0xf) != 0)// last 4 bits should be zero
{
return null;
}
byte[] tmp = new byte[i * 3 + 1];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
return tmp;
} else if (!isPad(d3) && isPad(d4)) {
b3 = base64Alphabet[d3];
if ((b3 & 0x3) != 0)// last 2 bits should be zero
{
return null;
}
byte[] tmp = new byte[i * 3 + 2];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
return tmp;
} else {
return null;
}
} else { // No PAD e.g 3cQl
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
}
return decodedData;
}
/**
* remove WhiteSpace from MIME containing encoded Base64 data.
*
* @param data
* the byte array of base64 data (with WS)
* @return the new length
*/
private static int removeWhiteSpace(char[] data) {
if (data == null) {
return 0;
}
// count characters that's not whitespace
int newSize = 0;
int len = data.length;
for (int i = 0; i < len; i++) {
if (!isWhiteSpace(data[i])) {
data[newSize++] = data[i];
}
}
return newSize;
}
}
@@ -0,0 +1,44 @@
package com.sw.st.utils;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.BatteryManager;
public class BatteryChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, 0);
int healthy = intent.getIntExtra(BatteryManager.EXTRA_HEALTH, 0);
int voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0);
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 3);
String technology = intent.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY);
int temperature = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0);
boolean present = intent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, false);
String desc = String.format("%s : 收到广播:%s",
AppUtil.formatDateGetCurrentTime(), intent.getAction());
desc = String.format("%s\n电量刻度=%d", desc, scale);
desc = String.format("%s\n当前电量=%d", desc, level);
desc = String.format("%s\n当前状态=%s", desc, mStatus[status]);
desc = String.format("%s\n健康程度=%s", desc, mHealthy[healthy]);
desc = String.format("%s\n当前电压=%d", desc, voltage);
desc = String.format("%s\n当前电源=%s", desc, mPlugged[plugged]);
desc = String.format("%s\n当前技术=%s", desc, technology);
desc = String.format("%s\n当前温度=%d", desc, temperature / 10);
desc = String.format("%s\n是否提供电池=%s", desc, present ? "" : "");
L.e("desc===" + desc);
}
}
private static String[] mStatus = {"不存在", "未知", "正在充电", "正在断电", "不在充电", "充满"};
private static String[] mHealthy = {"不存在", "未知", "良好", "过热", "坏了", "短路", "未知错误", "冷却"};
private static String[] mPlugged = {"电池", "充电器", "USB", "不存在", "无线"};
}
@@ -0,0 +1,97 @@
package com.sw.st.utils;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import com.sw.st.net.helper.Convert;
import com.sw.st.ui.init.InitActivity;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class CrashHandler implements Thread.UncaughtExceptionHandler {
//系统默认UncaughtExceptionHandler
private Thread.UncaughtExceptionHandler mDefaultHandler;
private Context mContext;
private static CrashHandler mInstance;
private String DeviceUrl = "/businesslog/stBusinessLog/add";//上传错误网址
//空的构造方法
private CrashHandler() {
}
//单例,获取CrashHandler实例
public static synchronized CrashHandler getInstance() {
if (null == mInstance) {
mInstance = new CrashHandler();
}
return mInstance;
}
public void init(Context context) {
mContext = context;
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
//设置该CrashHandler为系统默认的
Thread.setDefaultUncaughtExceptionHandler(this);
}
//uncaughtException 回调函数
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && mDefaultHandler != null) {
//如果自己没处理交给系统处理
mDefaultHandler.uncaughtException(thread, ex);
}
}
//收集错误信息.发送到服务器, 处理了该异常返回true, 否则false
private boolean handleException(Throwable ex) {
if (ex == null) {
return false;
}
//获取错误信息
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
ex.printStackTrace(printWriter);
String errorReport = result.toString();
Map<String, String> map = new ConcurrentHashMap<>();
map.put("errorData", errorReport);
map.put("id", AppUtil.getUDID(mContext));
map.put("versionNo", AppUtil.getAppVersionName(mContext));
map.put("versionName", AppUtil.getAppPackageName(mContext));
String logData = Convert.toJson(map);
Map<String, String> requestMap = new ConcurrentHashMap<>();
requestMap.put("logData", logData);
requestMap.put("logType", "1");
L.e(Convert.toJson(requestMap));
PrefUtils.setString(mContext, "crashUrl", InitActivity.BASE_URL + DeviceUrl);
PrefUtils.setString(mContext, "crashData", Convert.toJson(requestMap));
Intent intent = new Intent(mContext, InitActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
android.os.Process.killProcess(android.os.Process.myPid());
return true;
}
}
@@ -0,0 +1,247 @@
package com.sw.st.utils;
import android.content.Context;
import android.os.Environment;
import android.telephony.TelephonyManager;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.util.UUID;
public class DeviceIdUtil {
//保存文件的路径
private static final String CACHE_DEVICES_DIR = "csair-mmp-devices/devices";
//保存的文件 采用隐藏文件的形式进行保存
private static final String DEVICES_FILE_NAME = ".DEVICES";
/**
* 获取设备唯一标识符
*
* @param context
* @return
*/
public static String getDeviceId(Context context) {
// //读取保存的在sd卡中的唯一标识符
String deviceId = readDeviceID(context);
//判断是否已经生成过,
if (deviceId != null && !"".equals(deviceId)) {
return deviceId;
}
//用于生成最终的唯一标识符
StringBuffer s = new StringBuffer();
try {
//获取IMES(也就是常说的DeviceId)
deviceId = getIMIEStatus(context);
s.append(deviceId);
} catch (Exception e) {
e.printStackTrace();
}
try {
//获取设备的MACAddress地址 去掉中间相隔的冒号
deviceId = getLocalMac(context).replace(":", "");
s.append(deviceId);
} catch (Exception e) {
e.printStackTrace();
}
// }
//如果以上搜没有获取相应的则自己生成相应的UUID作为相应设备唯一标识符
if (s == null || s.length() <= 0) {
UUID uuid = UUID.randomUUID();
deviceId = uuid.toString().replace("-", "");
s.append(deviceId);
}
//为了统一格式对设备的唯一标识进行md5加密 最终生成32位字符串
String md5 = getMD5(s.toString(), false);
if (s.length() > 0) {
//持久化操作, 进行保存到SD卡中
saveDeviceID(md5, context);
}
return md5;
}
/**
* 读取固定的文件中的内容,这里就是读取sd卡中保存的设备唯一标识符
*
* @param context
* @return
*/
private static String readDeviceID(Context context) {
File file = getDevicesDir(context);
StringBuffer buffer = new StringBuffer();
try {
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
Reader in = new BufferedReader(isr);
int i;
while ((i = in.read()) > -1) {
buffer.append((char) i);
}
in.close();
return buffer.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 获取设备的DeviceId(IMES) 这里需要相应的权限<br/>
* 需要 READ_PHONE_STATE 权限
*
* @param context
* @return
*/
private static String getIMIEStatus(Context context) {
TelephonyManager tm = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
String deviceId = tm.getDeviceId();
return deviceId;
}
/**
* 获取设备MAC 地址 由于 6.0 以后 WifiManager 得到的 MacAddress得到都是 相同的没有意义的内容
* 所以采用以下方法获取Mac地址
*
* @param context
* @return
*/
private static String getLocalMac(Context context) {
// WifiManager wifi = (WifiManager) context
// .getSystemService(Context.WIFI_SERVICE);
// WifiInfo info = wifi.getConnectionInfo();
// return info.getMacAddress();
String macAddress = null;
StringBuffer buf = new StringBuffer();
NetworkInterface networkInterface = null;
try {
networkInterface = NetworkInterface.getByName("eth1");
if (networkInterface == null) {
networkInterface = NetworkInterface.getByName("wlan0");
}
if (networkInterface == null) {
return "";
}
byte[] addr = networkInterface.getHardwareAddress();
for (byte b : addr) {
buf.append(String.format("%02X:", b));
}
if (buf.length() > 0) {
buf.deleteCharAt(buf.length() - 1);
}
macAddress = buf.toString();
} catch (SocketException e) {
e.printStackTrace();
return "";
}
return macAddress;
}
/**
* 保存 内容到 SD卡中, 这里保存的就是 设备唯一标识符
*
* @param str
* @param context
*/
private static void saveDeviceID(String str, Context context) {
File file = getDevicesDir(context);
try {
FileOutputStream fos = new FileOutputStream(file);
Writer out = new OutputStreamWriter(fos, "UTF-8");
out.write(str);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 对挺特定的 内容进行 md5 加密
*
* @param message 加密明文
* @param upperCase 加密以后的字符串是是大写还是小写 true 大写 false 小写
* @return
*/
private static String getMD5(String message, boolean upperCase) {
String md5str = "";
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] input = message.getBytes();
byte[] buff = md.digest(input);
md5str = bytesToHex(buff, upperCase);
} catch (Exception e) {
e.printStackTrace();
}
return md5str;
}
private static String bytesToHex(byte[] bytes, boolean upperCase) {
StringBuffer md5str = new StringBuffer();
int digital;
for (int i = 0; i < bytes.length; i++) {
digital = bytes[i];
if (digital < 0) {
digital += 256;
}
if (digital < 16) {
md5str.append("0");
}
md5str.append(Integer.toHexString(digital));
}
if (upperCase) {
return md5str.toString().toUpperCase();
}
return md5str.toString().toLowerCase();
}
/**
* 统一处理设备唯一标识 保存的文件的地址
*
* @param context
* @return
*/
private static File getDevicesDir(Context context) {
File mCropFile = null;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File cropdir = new File(Environment.getExternalStorageDirectory(), CACHE_DEVICES_DIR);
if (!cropdir.exists()) {
cropdir.mkdirs();
}
mCropFile = new File(cropdir, DEVICES_FILE_NAME);
} else {
File cropdir = new File(context.getFilesDir(), CACHE_DEVICES_DIR);
if (!cropdir.exists()) {
cropdir.mkdirs();
}
mCropFile = new File(cropdir, DEVICES_FILE_NAME);
}
return mCropFile;
}
}
@@ -0,0 +1,692 @@
package com.sw.st.utils;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import com.sw.st.application.App;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
public class FileUtil {
private static boolean isSaveLog = false;
public static final String FILE_STR_PATH = App.getmContext().getExternalCacheDir().getAbsolutePath();
public static final int SIZETYPE_B = 1;//获取文件大小单位为B的double值
public static final int SIZETYPE_KB = 2;//获取文件大小单位为KB的double值
public static final int SIZETYPE_MB = 3;//获取文件大小单位为MB的double值
public static final int SIZETYPE_GB = 4;//获取文件大小单位为GB的double值
private static String urlNull = "原文件路径不存在";
private static String isFile = "原文件不是文件";
private static String canRead = "原文件不能读";
private static String copyFalse = "备份失败!";
private static String cFromFile = "创建原文件出错:";
private static String ctoFile = "创建备份文件出错:";
/**
* 写入文件
* FileUtil.byteWriteFile(getExternalFilesDir("123"),"test.jpg",nv21);
*
* @param filePath
* @param fileName
* @param bytes
*/
public static void byteWriteFile(File filePath, String fileName, byte[] bytes) {
BufferedOutputStream bout = null;
try {
File file = new File(filePath, fileName);
if (file.exists() == false) {
if (file.getParentFile().exists() == false) {
file.getParentFile().mkdirs();
}
file.createNewFile();
}
bout = new BufferedOutputStream(new FileOutputStream(file, false));
bout.write(bytes);
bout.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bout != null) {
try {
bout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 获取文件名
*
* @param path 路径
* @return 文件名
*/
public static String getFileName(String path) {
int index = path.lastIndexOf("/");
return path.substring(index + 1);
}
/**
* 根据文件路径获取文件
*
* @param path 路径
* @return
*/
public static File getFileByPath(String path) {
File file = new File(path);
if (file.exists()) {
return new File(path);
} else {
return null;
}
}
/**
* 重命名文件
*
* @param filePath 文件路径
* @param newName 新名称
* @return {@code true}: 重命名成功<br>{@code false}: 重命名失败
*/
public static boolean rename(String filePath, String newName) {
return rename(getFileByPath(filePath), newName);
}
/**
* 重命名文件
*
* @param file 文件
* @param newName 新名称
* @return {@code true}: 重命名成功<br>{@code false}: 重命名失败
*/
public static boolean rename(File file, String newName) {
// 文件为空返回false
if (file == null) return false;
// 文件不存在返回false
if (!file.exists()) return false;
// 新的文件名为空返回false
if (AppUtil.isEmpty(newName)) return false;
// 如果文件名没有改变返回true
if (newName.equals(file.getName())) return true;
File newFile = new File(file.getParent() + File.separator + newName);
// 如果重命名的文件已存在返回false
return !newFile.exists()
&& file.renameTo(newFile);
}
/**
* 判断文件是否存在
*
* @param path 文件的路径,含文件后缀和文件名
* @return 是否存在
*/
public static boolean isFileExists(String path) {
File file = new File(path);
if (file.exists()) {
return true;
} else {
return false;
}
}
/**
* 判断文件是否存在
*
* @return 是否存在
*/
public static boolean isFileExists(File file) {
if (file.exists()) {
return true;
} else {
return false;
}
}
/**
* 删除文件夹及文件夹下所有内容
*
* @param path 文件夹路径
* @return 返回是否删除成功
*/
public static boolean deleteFiles(String path) {
if (getFileByPath(path) != null) {
return deleteFiles(getFileByPath(path));
} else {
return false;
}
}
/**
* 删除文件夹及文件夹下所有内容
*
* @param file 文件
* @return 返回是否删除成功
*/
public static boolean deleteFiles(File file) {
try {
if (file.exists()) { // 判断文件是否存在
if (file.isFile()) { // 判断是否是文件
file.delete(); // delete()方法
} else if (file.isDirectory()) { // 否则如果它是一个目录
File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
deleteFiles(files[i].getPath()); // 把每个文件 用这个方法进行迭代
}
file.delete();//删除目录
}
//file.delete();
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 获取文件的Uri
*
* @param path 文件的路径
* @return 文件的Uri
*/
public static Uri getUriFromFile(String path) {
File file = new File(path);
return Uri.fromFile(file);
}
/**
* 获取文件指定文件的指定单位的大小
*
* @param filePath 文件路径
* @param sizeType 获取大小的类型1为B、2为KB、3为MB、4为GB
* @return double值的大小
*/
public static double getFileOrFilesSize(String filePath, int sizeType) {
File file = new File(filePath);
long blockSize = 0;
try {
if (file.isDirectory()) {
blockSize = getFileSizes(file);
} else {
blockSize = getFileSize(file);
}
} catch (Exception e) {
e.printStackTrace();
L.i("获取文件大小", "获取失败!");
}
return FormetFileSize(blockSize, sizeType);
}
/**
* 调用此方法自动计算指定文件或指定文件夹的大小
*
* @param filePath 文件路径
* @return 计算好的带B、KB、MB、GB的字符串
*/
public static String getAutoFileOrFilesSize(String filePath) {
File file = new File(filePath);
long blockSize = 0;
try {
if (file.isDirectory()) {
blockSize = getFileSizes(file);
} else {
blockSize = getFileSize(file);
}
} catch (Exception e) {
e.printStackTrace();
L.i("获取文件大小", "获取失败!");
}
return FormetFileSize(blockSize);
}
/**
* 获取指定文件大小
*
* @param file
* @return
* @throws Exception
*/
private static long getFileSize(File file) throws Exception {
long size = 0;
if (file.exists()) {
FileInputStream fis = null;
fis = new FileInputStream(file);
size = fis.available();
} else {
// file.createNewFile();
L.i("获取文件大小", "文件不存在!");
}
return size;
}
/**
* 获取目录下指定文件名的文件包括子目录
* <p>大小写忽略</p>
*
* @param dirPath 目录路径
* @param fileName 文件名
* @return 文件链表
*/
public static List<File> searchFileInDir(String dirPath, String fileName) {
return searchFileInDir(getFileByPath(dirPath), fileName);
}
/**
* 获取目录下指定文件名的文件包括子目录
* <p>大小写忽略</p>
*
* @param dir 目录
* @param fileName 文件名
* @return 文件链表
*/
public static List<File> searchFileInDir(File dir, String fileName) {
if (dir == null || !dir.isDirectory()) return null;
List<File> list = new ArrayList<>();
File[] files = dir.listFiles();
if (files != null && files.length != 0) {
for (File file : files) {
if (file.getName().toUpperCase().equals(fileName.toUpperCase())) {
list.add(file);
}
if (file.isDirectory()) {
list.addAll(searchFileInDir(file, fileName));
}
}
}
return list;
}
/**
* 获取指定文件夹
*
* @param f
* @return
* @throws Exception
*/
private static long getFileSizes(File f) throws Exception {
long size = 0;
File flist[] = f.listFiles();
for (int i = 0; i < flist.length; i++) {
if (flist[i].isDirectory()) {
size = size + getFileSizes(flist[i]);
} else {
size = size + getFileSize(flist[i]);
}
}
return size;
}
/**
* 转换文件大小
*
* @param fileS
* @return
*/
private static String FormetFileSize(long fileS) {
DecimalFormat df = new DecimalFormat("#.00");
String fileSizeString = "";
String wrongSize = "0B";
if (fileS == 0) {
return wrongSize;
}
if (fileS < 1024) {
fileSizeString = df.format((double) fileS) + "B";
} else if (fileS < 1048576) {
fileSizeString = df.format((double) fileS / 1024) + "KB";
} else if (fileS < 1073741824) {
fileSizeString = df.format((double) fileS / 1048576) + "MB";
} else {
fileSizeString = df.format((double) fileS / 1073741824) + "GB";
}
return fileSizeString;
}
/**
* 转换文件大小,指定转换的类型
*
* @param fileS
* @param sizeType
* @return
*/
private static double FormetFileSize(long fileS, int sizeType) {
DecimalFormat df = new DecimalFormat("#.00");
double fileSizeLong = 0;
switch (sizeType) {
case SIZETYPE_B:
fileSizeLong = Double.valueOf(df.format((double) fileS));
break;
case SIZETYPE_KB:
fileSizeLong = Double.valueOf(df.format((double) fileS / 1024));
break;
case SIZETYPE_MB:
fileSizeLong = Double.valueOf(df.format((double) fileS / 1048576));
break;
case SIZETYPE_GB:
fileSizeLong = Double.valueOf(df.format((double) fileS / 1073741824));
break;
default:
break;
}
return fileSizeLong;
}
/**
* 复制文件
*
* @param fromFilePath 旧文件地址和名称
* @param toFilePath 新文件地址和名称
* @return 返回备份文件的信息,ok是成功,其它就是错误
*/
public static File copyFile(String fromFilePath, String toFilePath) {
File fromFile = null;
File toFile = null;
try {
fromFile = new File(fromFilePath);
} catch (Exception e) {
L.i(cFromFile + e.getMessage());
return null;
}
try {
toFile = new File(toFilePath);
if (toFile.isDirectory()) {
toFile = new File(toFilePath.endsWith("/") ? toFilePath + fromFile.getName() : toFilePath + "/" + fromFile.getName());
}
} catch (Exception e) {
L.i(ctoFile + e.getMessage());
return null;
}
if (!fromFile.exists()) {
L.i(urlNull);
return null;
}
if (!fromFile.isFile()) {
L.i(isFile);
return null;
}
if (!fromFile.canRead()) {
L.i(canRead);
return null;
}
// 复制到的路径如果不存在就创建
if (!toFile.getParentFile().exists()) {
toFile.getParentFile().mkdirs();
}
if (toFile.exists()) {
toFile.delete();
}
if (!toFile.canWrite()) {
//return notWrite;
}
try {
FileInputStream fosfrom = new FileInputStream(
fromFile);
FileOutputStream fosto = new FileOutputStream(toFile);
byte bt[] = new byte[1024];
int c;
while ((c = fosfrom.read(bt)) > 0) {
fosto.write(bt, 0, c); // 将内容写到新文件当中
}
//关闭数据流
fosfrom.close();
fosto.close();
} catch (Exception e) {
e.printStackTrace();
L.i(copyFalse + e.getMessage());
return null;
}
return toFile;
}
/**
* 创建文件
*
* @param path 文件路径
* @return 创建的文件
*/
public static synchronized File createNewFile(String path) {
File file = new File(path);
String parentPath = path.substring(0, path.lastIndexOf("/") + 1);
File parentFile = new File(parentPath);
if (!parentFile.exists()) {
parentFile.mkdirs();
}
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return file;
}
/***
* 根据文件后缀回去MIME类型
****/
private static String getMIMEType(File file) {
String type = "*/*";
String fName = file.getName();
//获取后缀名前的分隔符"."在fName中的位置。
int dotIndex = fName.lastIndexOf(".");
if (dotIndex < 0) {
return type;
}
/* 获取文件的后缀名*/
String end = fName.substring(dotIndex, fName.length()).toLowerCase();
if (end == "") return type;
//在MIME和文件类型的匹配表中找到对应的MIME类型。
for (int i = 0; i < MIME_MapTable.length; i++) { //MIME_MapTable??在这里你一定有疑问,这个MIME_MapTable是什么?
if (end.equals(MIME_MapTable[i][0]))
type = MIME_MapTable[i][1];
}
return type;
}
/**
* 获取全路径中的文件拓展名
*
* @param file 文件
* @return 文件拓展名
*/
public static String getFileExtension(File file) {
if (file == null) return null;
return getFileExtension(file.getPath());
}
/**
* 获取全路径中的文件拓展名
*
* @param filePath 文件路径
* @return 文件拓展名
*/
public static String getFileExtension(String filePath) {
if (AppUtil.isEmpty(filePath)) return filePath;
int lastPoi = filePath.lastIndexOf('.');
int lastSep = filePath.lastIndexOf(File.separator);
if (lastPoi == -1 || lastSep >= lastPoi) return "";
return filePath.substring(lastPoi + 1);
}
/**
* 调用系统应用打开文件
*
* @param context 上下文
* @param file 文件
*/
public static void openFile(Context context, File file) {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//设置intent的Action属性
intent.setAction(Intent.ACTION_VIEW);
//获取文件file的MIME类型
String type = getMIMEType(file);
//设置intent的data和Type属性。
intent.setDataAndType(Uri.fromFile(file), type);
//跳转
try {
context.startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
L.i("找不到打开此文件的应用!");
}
}
/**
* 保存文本文件
* FileUtil.saveStrFile("测试", "log.txt", FILE_STR_PATH, true);
*
* @param res 写入内容
* @param fileName 文件名
* @param filePath 路径
* @param append true新增 false替换
* @return
*/
public static boolean saveStrFile(String res, String fileName, String filePath, boolean append) {
boolean flag = true;
BufferedReader bufferedReader = null;
BufferedWriter bufferedWriter = null;
try {
File file = new File(filePath, fileName);
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
bufferedReader = new BufferedReader(new StringReader(res));
bufferedWriter = new BufferedWriter(new FileWriter(file, append));
char buf[] = new char[1024]; //字符缓冲区
int len;
while ((len = bufferedReader.read(buf)) != -1) {
bufferedWriter.write(buf, 0, len);
}
bufferedWriter.flush();
bufferedReader.close();
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
flag = false;
return flag;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return flag;
}
public static void saveLog(String... info) {
if (!isSaveLog) {
return;
}
new Thread() {
@Override
public void run() {
super.run();
StringBuffer stringBuffer = new StringBuffer();
for (String s : info) {
stringBuffer.append(s).append("===");
}
stringBuffer.append((AppUtil.formatDateGetCurrentTime())).append("\n");
FileUtil.saveStrFile(stringBuffer.toString(),
"log" + AppUtil.formatDateGetDay(java.lang.System.currentTimeMillis()) + ".txt", FILE_STR_PATH, true);
}
}.start();
}
private static final String[][] MIME_MapTable = {
// {后缀名,MIME类型}
{".3gp", "video/3gpp"},
{".apk", "application/vnd.android.package-archive"},
{".asf", "video/x-ms-asf"},
{".avi", "video/x-msvideo"},
{".bin", "application/octet-stream"},
{".bmp", "image/bmp"},
{".c", "text/plain"},
{".class", "application/octet-stream"},
{".conf", "text/plain"},
{".cpp", "text/plain"},
{".doc", "application/msword"},
{".docx",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
{".xls", "application/vnd.ms-excel"},
{".xlsx",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{".exe", "application/octet-stream"},
{".gif", "image/gif"},
{".gtar", "application/x-gtar"},
{".gz", "application/x-gzip"},
{".h", "text/plain"},
{".htm", "text/html"},
{".html", "text/html"},
{".jar", "application/java-archive"},
{".java", "text/plain"},
{".jpeg", "image/jpeg"},
{".jpg", "image/jpeg"},
{".js", "application/x-javascript"},
{".log", "text/plain"},
{".m3u", "audio/x-mpegurl"},
{".m4a", "audio/mp4a-latm"},
{".m4b", "audio/mp4a-latm"},
{".m4p", "audio/mp4a-latm"},
{".m4u", "video/vnd.mpegurl"},
{".m4v", "video/x-m4v"},
{".mov", "video/quicktime"},
{".mp2", "audio/x-mpeg"},
{".mp3", "audio/x-mpeg"},
{".mp4", "video/mp4"},
{".mpc", "application/vnd.mpohun.certificate"},
{".mpe", "video/mpeg"},
{".mpeg", "video/mpeg"},
{".mpg", "video/mpeg"},
{".mpg4", "video/mp4"},
{".mpga", "audio/mpeg"},
{".msg", "application/vnd.ms-outlook"},
{".ogg", "audio/ogg"},
{".pdf", "application/pdf"},
{".png", "image/png"},
{".pps", "application/vnd.ms-powerpoint"},
{".ppt", "application/vnd.ms-powerpoint"},
{".pptx",
"application/vnd.openxmlformats-officedocument.presentationml.presentation"},
{".prop", "text/plain"}, {".rc", "text/plain"},
{".rmvb", "audio/x-pn-realaudio"}, {".rtf", "application/rtf"},
{".sh", "text/plain"}, {".tar", "application/x-tar"},
{".tgz", "application/x-compressed"}, {".txt", "text/plain"},
{".wav", "audio/x-wav"}, {".wma", "audio/x-ms-wma"},
{".wmv", "audio/x-ms-wmv"},
{".wps", "application/vnd.ms-works"}, {".xml", "text/plain"},
{".z", "application/x-compress"},
{".zip", "application/x-zip-compressed"}, {"", "*/*"}};
}
@@ -0,0 +1,175 @@
package com.sw.st.utils;
import android.os.SystemClock;
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/**
* Created by Administrator on 2018/11/9.
*/
public class GpioUtils {
private static final String TAG = "GpioUtils";
/*
给export申请权限
*/
public static void upgradeRootPermissionForExport(){
upgradeRootPermission("/sys/class/gpio/export");
}
/*
配置一个gpio路径
*/
public static boolean exportGpio(int gpio) {
return writeNode("/sys/class/gpio/export", ""+gpio);
}
/*
给获取io口的状态的路径申请权限,该方法需要在exportGpio后调用
*/
public static void upgradeRootPermissionForGpio(int gpio){
upgradeRootPermission("/sys/class/gpio/gpio" + gpio + "/direction");
upgradeRootPermission("/sys/class/gpio/gpio" + gpio + "/value");
}
/*
设置io口为输入或输出
*/
public static boolean setGpioDirection(int gpio, int arg){
String gpioDirection = "";
if(arg == 0) gpioDirection = "out";
else if(arg == 1) gpioDirection = "in";
else return false;
return writeNode("/sys/class/gpio/gpio" + gpio + "/direction", gpioDirection);
}
/*
获取io口的状态为输出还是输入
*/
public static String getGpioDirection(int gpio){
String gpioDirection ="";
gpioDirection = readNode("/sys/class/gpio/gpio" + gpio + "/direction");
return gpioDirection;
}
/*
给输出io口写值,高电平或低电平
*/
public static boolean writeGpioValue(int gpio, String arg){
return writeNode("/sys/class/gpio/gpio" + gpio + "/value", arg);
}
//获取当前gpio是高还是低
public static String getGpioValue(int gpio) {
return readNode("/sys/class/gpio/gpio" + gpio + "/value");
}
private static boolean upgradeRootPermission(String path) {
Process process = null;
DataOutputStream os = null;
try {
String cmd="chmod 777 " + path;
process = Runtime.getRuntime().exec("su"); //切换到root帐号
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(cmd + "\n");
os.writeBytes("exit\n");
os.flush();
process.waitFor();
} catch (Exception e) {
} finally {
try {
if (os != null) {
os.close();
}
process.destroy();
} catch (Exception e) {
}
}
try {
return process.waitFor()==0;
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
}
private static boolean writeNode(String path, String arg) {
Log.d(TAG, "Gpio_test set node path: " + path + " arg: " + arg);
if (path == null || arg == null) {
Log.e(TAG, "set node error");
return false;
}
FileWriter fileWriter = null;
BufferedWriter bufferedWriter = null;
try {
fileWriter = new FileWriter(path);
fileWriter.write(arg);
} catch (Exception e) {
Log.e(TAG, "Gpio_test write node error!! path" + path + " arg: " + arg);
e.printStackTrace();
return false;
} finally {
try {
if (fileWriter != null) {
fileWriter.close();
}
if (bufferedWriter != null) {
bufferedWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
private static long mTime = 0;
private static int mFailTimes = 0;
private static String readNode(String path) {
String result = "";
FileReader fread = null;
BufferedReader buffer = null;
try {
fread = new FileReader(path);
buffer = new BufferedReader(fread);
String str = null;
while ((str = buffer.readLine()) != null) {
result = str;
break;
}
mFailTimes = 0;
} catch (IOException e) {
Log.e(TAG, "IO Exception");
e.printStackTrace();
if (mTime == 0 || SystemClock.uptimeMillis() - mTime < 1000) {
mFailTimes++;
}
if (mFailTimes >= 3) {
Log.d(TAG, "read format node continuous failed three times, exist thread");
}
} finally {
try {
if (buffer != null) {
buffer.close();
}
if (fread != null) {
fread.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
}

Some files were not shown because too many files have changed in this diff Show More