Commit f7c16ce3 by liulei

初始化

parent 2d0cc45d
apply plugin: 'com.android.application'
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
useLibrary 'org.apache.http.legacy'
compileSdkVersion 28
defaultConfig {
applicationId "com.stm.asset"
minSdkVersion 21
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
repositories {
flatDir {
dirs 'libs'
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.multidex:multidex:2.0.1'
implementation "androidx.room:room-runtime:2.2.3"
annotationProcessor "androidx.room:room-compiler:2.2.3"
implementation 'com.github.bumptech.glide:glide:3.7.0'
implementation 'com.google.code.gson:gson:2.8.9'
implementation 'com.squareup.okhttp3:okhttp:3.14.2'
implementation 'com.squareup.okio:okio:1.17.4'
implementation 'com.tencent.bugly:crashreport:3.4.4'
implementation 'me.jessyan:autosize:1.1.2'
implementation (name: 'BaseLib', ext: 'aar')
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
// compile project(path: ':u8')
}
# 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
-dontwarn com.tencent.bugly.**
-keep public class com.tencent.bugly.**{*;}
\ No newline at end of file
package com.stm.asset;
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.stm.asset", appContext.getPackageName());
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.stm.asset">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_LOGS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:name=".base.StmApplication"
android:allowBackup="true"
android:icon="@drawable/logo"
android:label="@string/app_name"
android:roundIcon="@drawable/logo"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:networkSecurityConfig="@xml/network_security_config">
<!-- 480 * 640 -->
<meta-data android:name="design_width_in_dp" android:value="337"/>
<meta-data android:name="design_height_in_dp" android:value="449"/>
<activity android:name=".page.WelcomeActivity" android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
</intent-filter>
</activity>
<activity android:name=".page.MainActivity" android:screenOrientation="portrait" />
<activity android:name=".page.CheckTaskActivity" android:screenOrientation="portrait" />
<activity android:name=".page.TaskInfoActivity" android:screenOrientation="portrait" />
<activity android:name=".page.SetAndSaveActivity" android:screenOrientation="portrait" />
<activity android:name=".page.InventoryActivity" android:screenOrientation="portrait" />
<activity android:name=".page.LoginActivity" android:screenOrientation="portrait" />
<activity android:name=".page.DeviceSetActivity" android:screenOrientation="portrait" />
<activity android:name=".page.SelectIPActivity" android:screenOrientation="portrait" />
</application>
</manifest>
\ No newline at end of file
package com.fn.useries.model;
public interface IResponseHandler {
/**
* 成功
* msg 成功时返回的消息
* data 成功时返回的数据,已转换为字符串
* parameters 成功时返回的响应帧中的Parameters域的数据
*/
public void onSuccess(String msg, Object data, byte[] parameters);
/**
* 失败
* msg 失败的消息
*/
public void onFailure(String msg);
}
package com.fn.useries.model;
public class Message {
private int code; // 0 Successful, 1 Failure
private String message; //额外信息
private String result; // 结果
public Message(){
}
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
public void setCode(int code) {
this.code = code;
}
public void setMessage(String message) {
this.message = message;
}
public void setResult(String result) {
this.result = result;
}
public String getResult() {
return result;
}
}
package com.fn.useries.model;
public class ReceiveDataHandler {
private static final ReceiveDataHandler mReceiverHolder = new ReceiveDataHandler();
private int code; // 0 Successful, 1 Failure
private String message; //额外信息
private String result; // 返回结果
private ReceiveDataHandler(){}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public static ReceiveDataHandler getInstance(){
return mReceiverHolder;
}
}
package com.fn.useries.model;
public abstract class ResponseHandler implements IResponseHandler {
private static final String TAG = "ResponseHandler";
/*
* (non-Javadoc)
* @see com.fn.useries.model.IResponseHandler#onSuccess(java.lang.String, java.lang.Object, byte[])
*/
@Override
public void onSuccess(String msg, Object data, byte[] parameters) {
}
/*
* (non-Javadoc)
* @see com.fn.useries.model.IResponseHandler#onFailure(java.lang.String)
*/
@Override
public void onFailure(String msg) {
System.out.println("onFailure---msg:" + msg);
}
}
package com.fn.useries.model;
/**
* 保存读到的设置参数,各个模块不同可加参数
*
* @author 07
*
*/
public class SettingParams {
private int TXPower;
private int detectionTemperature;// 模块温度
private byte btMode;// 蜂鸣器状态
public int getTXPower() {
return TXPower;
}
public void setTXPower(int tXPower) {
TXPower = tXPower;
}
public int getDetectionTemperature() {
return detectionTemperature;
}
public void setDetectionTemperature(int detectionTemperature) {
this.detectionTemperature = detectionTemperature;
}
public byte getBtMode() {
return btMode;
}
public void setBtMode(byte btMode) {
this.btMode = btMode;
}
}
package com.fn.useries.operation;
import com.fn.useries.model.IResponseHandler;
import com.fn.useries.model.Message;
public interface IUSeries {
/**
* 打开串口
* @param moduleName 模块名
* @return true_ 打开串口成功,false_ 打开串口失败
*/
Message openSerialPort(String moduleName);
/**
* 关闭串口
*
* @return true_ 关闭串口成功,false_ 关闭串口失败
*/
Message closeSerialPort();
/**
* 模块上电
* @param moduleName 模块名
* @return true_ 上电成功,false_ 上电失败
*/
Message modulePowerOn(String moduleName);
/**
* 模块下电
* @param moduleName 模块名
* @return true_ 下电成功,false_ 下电失败
*/
Message modulePowerOff(String moduleName);
/**
* 开始盘询
* @param responseHandler 盘询结果回调
* @return true_ 开始盘询成功成功,false_ 开始盘询失败
*/
boolean startInventory(IResponseHandler responseHandler);
/**
* 停止盘询
* @return true_ 停止盘询成功,false_ 停止盘询失败
*/
boolean stopInventory();
/**
* 单次盘询
* @return 盘询结果
*/
Message Inventory();
/**
* 读标签
*
* @param block 读取区域
* @param w_count 读取长度
* @param w_offset 偏移
* @param acs_pwd 访问密码
* @return 读取标签数据
*/
Message readTagMemory(byte[] EPC, byte block, byte w_count, byte w_offset, byte[] acs_pwd);
/**
* 写标签
*
* @param block 写入区域
* @param w_count 写入长度
* @param w_offset 偏移
* @param data 写入数据
* @param acs_pwd 访问密码
* @return 是否写入成功
*/
Message writeTagMemory(byte[] EPC, byte block, byte w_count, byte w_offset, byte[] data, byte[] acs_pwd);
/**
* 锁标签
*
* @param block 锁定区域
* @param operation 操作类型
* @param acs_pwd 访问密码
* @return 返回错误代码
*/
Message lockTagMemory(byte[] EPC, byte block, Enum operation, byte[] acs_pwd);
/**
* 销毁标签
*
* @param kill_pwd 销毁密码
* @return 返回错误代码
*/
Message killTag(byte[] EPC, byte[] kill_pwd);
/**
* 设置参数
*
* @param paraName 参数名(详见SDK)
* @return
*/
String getParams(String paraName);
/**
* 设置参数
*
* @param paraName 参数名(详见SDK)
* @param paraValue 参数值(详见SDK)
* @return
*/
boolean setParams(String paraName, String paraValue);
}
package com.fn.useries.reader;
public class CMD {
public final static byte RESET = 0x70;
public final static byte SET_UART_BAUDRATE = 0x71;
public final static byte GET_FIRMWARE_VERSION = 0x72;
public final static byte SET_READER_ADDRESS = 0x73;
public final static byte SET_WORK_ANTENNA = 0x74;
public final static byte GET_WORK_ANTENNA = 0x75;
public final static byte SET_OUTPUT_POWER = 0x76;
public final static byte GET_OUTPUT_POWER = 0x77;
public final static byte SET_FREQUENCY_REGION = 0x78;
public final static byte GET_FREQUENCY_REGION = 0x79;
public final static byte SET_BEEPER_MODE = 0x7A;
public final static byte GET_READER_TEMPERATURE = 0x7B;
public final static byte READ_GPIO_VALUE = 0x60;
public final static byte WRITE_GPIO_VALUE = 0x61;
public final static byte SET_ANT_CONNECTION_DETECTOR = 0x62;
public final static byte GET_ANT_CONNECTION_DETECTOR = 0x63;
public final static byte SET_TEMPORARY_OUTPUT_POWER = 0x66;
public final static byte SET_READER_IDENTIFIER = 0x67;
public final static byte GET_READER_IDENTIFIER = 0x68;
public final static byte SET_RF_LINK_PROFILE = 0x69;
public final static byte GET_RF_LINK_PROFILE = 0x6A;
public final static byte GET_RF_PORT_RETURN_LOSS = 0x7E;
public final static byte INVENTORY = (byte) 0x80;
public final static byte READ_TAG = (byte) 0x81;
public final static byte WRITE_TAG = (byte) 0x82;
public final static byte LOCK_TAG = (byte) 0x83;
public final static byte KILL_TAG = (byte) 0x84;
public final static byte SET_ACCESS_EPC_MATCH = (byte) 0x85;
public final static byte GET_ACCESS_EPC_MATCH = (byte) 0x86;
public final static byte REAL_TIME_INVENTORY = (byte) 0x89;
public final static byte FAST_SWITCH_ANT_INVENTORY = (byte) 0x8A;
public final static byte CUSTOMIZED_SESSION_TARGET_INVENTORY = (byte) 0x8B;
public final static byte SET_IMPINJ_FAST_TID = (byte) 0x8C;
public final static byte SET_AND_SAVE_IMPINJ_FAST_TID = (byte) 0x8D;
public final static byte GET_IMPINJ_FAST_TID = (byte) 0x8E;
public final static byte ISO18000_6B_INVENTORY = (byte) 0xB0;
public final static byte ISO18000_6B_READ_TAG = (byte) 0xB1;
public final static byte ISO18000_6B_WRITE_TAG = (byte) 0xB2;
public final static byte ISO18000_6B_LOCK_TAG = (byte) 0xB3;
public final static byte ISO18000_6B_QUERY_LOCK_TAG = (byte) 0xB4;
public final static byte GET_INVENTORY_BUFFER = (byte) 0x90;
public final static byte GET_AND_RESET_INVENTORY_BUFFER = (byte) 0x91;
public final static byte GET_INVENTORY_BUFFER_TAG_COUNT = (byte) 0x92;
public final static byte RESET_INVENTORY_BUFFER = (byte) 0x93;
public static String format(byte btCmd)
{
String strCmd = "";
switch (btCmd)
{
case RESET:
strCmd = "复位读写器";
break;
case SET_UART_BAUDRATE:
strCmd = "设置串口通讯波特率";
break;
case GET_FIRMWARE_VERSION:
strCmd = "读取读写器固件版本";
break;
case SET_READER_ADDRESS:
strCmd = "设置读写器地址";
break;
case SET_WORK_ANTENNA:
strCmd = "设置读写器工作天线";
break;
case GET_WORK_ANTENNA:
strCmd = "查询当前天线工作天线";
break;
case SET_OUTPUT_POWER:
strCmd = "设置读写器射频输出功率";
break;
case GET_OUTPUT_POWER:
strCmd = "查询读写器当前输出功率";
break;
case SET_FREQUENCY_REGION:
strCmd = "设置读写器工作频率范围";
break;
case GET_FREQUENCY_REGION:
strCmd = "查询读写器工作频率范围";
break;
case SET_BEEPER_MODE:
strCmd = "设置蜂鸣器状态";
break;
case GET_READER_TEMPERATURE:
strCmd = "查询当前设备的工作温度";
break;
case READ_GPIO_VALUE:
strCmd = "读取GPIO电平";
break;
case WRITE_GPIO_VALUE:
strCmd = "设置GPIO电平";
break;
case SET_ANT_CONNECTION_DETECTOR:
strCmd = "设置天线连接检测器状态";
break;
case GET_ANT_CONNECTION_DETECTOR:
strCmd = "读取天线连接检测器状态";
break;
case SET_TEMPORARY_OUTPUT_POWER:
strCmd = "设置读写器临时射频输出功率";
break;
case SET_READER_IDENTIFIER:
strCmd = "设置读写器识别码";
break;
case GET_READER_IDENTIFIER:
strCmd = "读取读写器识别码";
break;
case SET_RF_LINK_PROFILE:
strCmd = "设置射频链路的通讯速率";
break;
case GET_RF_LINK_PROFILE:
strCmd = "读取射频链路的通讯速率";
break;
case GET_RF_PORT_RETURN_LOSS:
strCmd = "测量天线端口的回波损耗";
break;
case INVENTORY:
strCmd = "盘存标签";
break;
case READ_TAG:
strCmd = "读标签";
break;
case WRITE_TAG:
strCmd = "写标签";
break;
case LOCK_TAG:
strCmd = "锁定标签";
break;
case KILL_TAG:
strCmd = "灭活标签";
break;
case SET_ACCESS_EPC_MATCH:
strCmd = "匹配ACCESS操作的EPC号";
break;
case GET_ACCESS_EPC_MATCH:
strCmd = "查询匹配的EPC状态";
break;
case REAL_TIME_INVENTORY:
strCmd = "盘存标签(实时上传标签数据)";
break;
case FAST_SWITCH_ANT_INVENTORY:
strCmd = "快速轮询多个天线盘存标签";
break;
case CUSTOMIZED_SESSION_TARGET_INVENTORY:
strCmd = "自定义session和target盘存";
break;
case SET_IMPINJ_FAST_TID:
strCmd = "设置Monza标签快速读TID(不保存)";
break;
case SET_AND_SAVE_IMPINJ_FAST_TID:
strCmd = "设置Monza标签快速读TID(保存)";
break;
case GET_IMPINJ_FAST_TID:
strCmd = "查询当前的快速TID设置";
break;
case ISO18000_6B_INVENTORY:
strCmd = "盘询18000-6B标签";
break;
case ISO18000_6B_READ_TAG:
strCmd = "读18000-6B标签";
break;
case ISO18000_6B_WRITE_TAG:
strCmd = "写18000-6B标签";
break;
case ISO18000_6B_LOCK_TAG:
strCmd = "锁18000-6B标签";
break;
case ISO18000_6B_QUERY_LOCK_TAG:
strCmd = "匹配18000-6B标签";
break;
case GET_INVENTORY_BUFFER:
strCmd = "提取标签数据保留缓存备份";
break;
case GET_AND_RESET_INVENTORY_BUFFER:
strCmd = "提取标签数据并删除缓存";
break;
case GET_INVENTORY_BUFFER_TAG_COUNT:
strCmd = "查询缓存中已读标签个数";
break;
case RESET_INVENTORY_BUFFER:
strCmd = "清空标签数据缓存";
break;
default:
strCmd = "未知操作";
break;
}
return strCmd;
}
}
package com.fn.useries.reader;
public class Converter {
public static final int LITTLE_ENDIAN = 0;
public static final int BIG_ENDIAN = 1;
public static byte[] getBytes(int number, int order) {
int temp = number;
byte[] b = new byte[4];
if (order == LITTLE_ENDIAN) {
for (int i = b.length - 1; i >= 0; i--) {
b[i] = new Long(temp & 0xff).byteValue();
temp = temp >> 8;
}
} else {
for (int i = 0; i < b.length; i++) {
b[i] = new Long(temp & 0xff).byteValue();
temp = temp >> 8;
}
}
return b;
}
public static byte[] getBytes(long number, int order) {
long temp = number;
byte[] b = new byte[8];
if (order == LITTLE_ENDIAN) {
for (int i = b.length - 1; i >= 0; i--) {
b[i] = new Long(temp & 0xff).byteValue();
temp = temp >> 8;
}
} else {
for (int i = 0; i < b.length; i++) {
b[i] = new Long(temp & 0xff).byteValue();
temp = temp >> 8;
}
}
return b;
}
public static byte[] getBytes(short number, int order) {
int temp = number;
byte[] b = new byte[8];
if (order == LITTLE_ENDIAN) {
for (int i = b.length - 1; i >= 0; i--) {
b[i] = new Long(temp & 0xff).byteValue();
temp = temp >> 8;
}
} else {
for (int i = 0; i < b.length; i++) {
b[i] = new Long(temp & 0xff).byteValue();
temp = temp >> 8;
}
}
return b;
}
public static long byteToLong(byte[] b, int order) {
long s = 0;
long s0 = b[0] & 0xff;// 最低位
long s1 = b[1] & 0xff;
long s2 = b[2] & 0xff;
long s3 = b[3] & 0xff;
long s4 = b[4] & 0xff;// 最低位
long s5 = b[5] & 0xff;
long s6 = b[6] & 0xff;
long s7 = b[7] & 0xff;
if (order == LITTLE_ENDIAN) {
s1 <<= 8 * 1;
s2 <<= 8 * 2;
s3 <<= 8 * 3;
s4 <<= 8 * 4;
s5 <<= 8 * 5;
s6 <<= 8 * 6;
s7 <<= 8 * 7;
} else {
s0 <<= 8 * 7;
s1 <<= 8 * 6;
s2 <<= 8 * 5;
s3 <<= 8 * 4;
s4 <<= 8 * 3;
s5 <<= 8 * 2;
s6 <<= 8 * 1;
}
s = s0 | s1 | s2 | s3 | s4 | s5 | s6 | s7;
return s;
}
public static int byteToInt(byte[] b, int order) {
int s = 0;
int s0 = b[0] & 0xff;// 最低位
int s1 = b[1] & 0xff;
int s2 = b[2] & 0xff;
int s3 = b[3] & 0xff;
if (order == LITTLE_ENDIAN) {
s2 <<= 8;
s1 <<= 16;
s0 <<= 24;
} else {
s3 <<= 24;
s2 <<= 16;
s1 <<= 8;
}
s = s0 | s1 | s2 | s3;
return s;
}
public static short byteToShort(byte[] b, int order) {
short s = 0;
short s0 = (short) (b[0] & 0xff);// 最低位
short s1 = (short) (b[1] & 0xff);
if (order == LITTLE_ENDIAN) {
s0 <<= 8;
s = (short) (s0 | s1);
} else {
s1 <<= 8;
s = (short) (s0 | s1);
}
return s;
}
}
package com.fn.useries.reader;
public class ERROR {
public final static byte SUCCESS = 0x10;
public final static byte FAIL = 0x11;
public final static byte MCU_RESET_ERROR = 0x20;
public final static byte CW_ON_ERROR = 0x21;
public final static byte ANTENNA_MISSING_ERROR = 0x22;
public final static byte WRITE_FLASH_ERROR = 0x23;
public final static byte READ_FLASH_ERROR = 0x24;
public final static byte SET_OUTPUT_POWER_ERROR = 0x25;
public final static byte TAG_INVENTORY_ERROR = 0x31;
public final static byte TAG_READ_ERROR = 0x32;
public final static byte TAG_WRITE_ERROR = 0x33;
public final static byte TAG_LOCK_ERROR = 0x34;
public final static byte TAG_KILL_ERROR = 0x35;
public final static byte NO_TAG_ERROR = 0x36;
public final static byte INVENTORY_OK_BUT_ACCESS_FAIL = 0x37;
public final static byte BUFFER_IS_EMPTY_ERROR = 0x38;
public final static byte ACCESS_OR_PASSWORD_ERROR = 0x40;
public final static byte PARAMETER_INVALID = 0x41;
public final static byte PARAMETER_INVALID_WORDCNT_TOO_LONG = 0x42;
public final static byte PARAMETER_INVALID_MEMBANK_OUT_OF_RANGE = 0x43;
public final static byte PARAMETER_INVALID_LOCK_REGION_OUT_OF_RANGE = 0x44;
public final static byte PARAMETER_INVALID_LOCK_ACTION_OUT_OF_RANGE = 0x45;
public final static byte PARAMETER_READER_ADDRESS_INVALID = 0x46;
public final static byte PARAMETER_INVALID_ANTENNA_ID_OUT_OF_RANGE = 0x47;
public final static byte PARAMETER_INVALID_OUTPUT_POWER_OUT_OF_RANGE = 0x48;
public final static byte PARAMETER_INVALID_FREQUENCY_REGION_OUT_OF_RANGE = 0x49;
public final static byte PARAMETER_INVALID_BAUDRATE_OUT_OF_RANGE = 0x4A;
public final static byte PARAMETER_BEEPER_MODE_OUT_OF_RANGE = 0x4B;
public final static byte PARAMETER_EPC_MATCH_LEN_TOO_LONG = 0x4C;
public final static byte PARAMETER_EPC_MATCH_LEN_ERROR = 0x4D;
public final static byte PARAMETER_INVALID_EPC_MATCH_MODE = 0x4E;
public final static byte PARAMETER_INVALID_FREQUENCY_RANGE = 0x4F;
public final static byte FAIL_TO_GET_RN16_FROM_TAG = 0x50;
public final static byte PARAMETER_INVALID_DRM_MODE = 0x51;
public final static byte PLL_LOCK_FAIL = 0x52;
public final static byte RF_CHIP_FAIL_TO_RESPONSE = 0x53;
public final static byte FAIL_TO_ACHIEVE_DESIRED_OUTPUT_POWER = 0x54;
public final static byte COPYRIGHT_AUTHENTICATION_FAIL = 0x55;
public final static byte SPECTRUM_REGULATION_ERROR = 0x56;
public final static byte OUTPUT_POWER_TOO_LOW = 0x57;
/**
* 自定义错误: 未接受完整错误
*/
public final static String RECEVICE_INCOMPLETE = "接收数据异常";
/**
* 自定义错误: EPC绑定/解绑失败
*/
public final static String EPC_MATCH_ERROR = "EPC绑定/解绑失败";
/**
* 根据错误代码获取错误类型
* @param btErrorCode 错误代码(1 byte)
* @return 错误类型说明
*/
public static String format(byte btErrorCode)
{
String strErrorCode = "";
switch (btErrorCode)
{
case SUCCESS:
strErrorCode = "命令成功完成";
break;
case FAIL:
strErrorCode = "命令执行失败";//
break;
case MCU_RESET_ERROR:
strErrorCode = "CPU 复位错误";//
break;
case CW_ON_ERROR:
strErrorCode = "打开CW 错误";//
break;
case ANTENNA_MISSING_ERROR:
strErrorCode = "天线未连接";//
break;
case WRITE_FLASH_ERROR:
strErrorCode = "写Flash 错误";//
break;
case READ_FLASH_ERROR:
strErrorCode = "读Flash 错误";//
break;
case SET_OUTPUT_POWER_ERROR:
strErrorCode = "设置发射功率错误";//
break;
case TAG_INVENTORY_ERROR:
strErrorCode = "盘存标签错误";//
break;
case TAG_READ_ERROR:
strErrorCode = "读标签错误";//
break;
case TAG_WRITE_ERROR:
strErrorCode = "写标签错误";//
break;
case TAG_LOCK_ERROR:
strErrorCode = "锁定标签错误";//
break;
case TAG_KILL_ERROR:
strErrorCode = "灭活标签错误";//
break;
case NO_TAG_ERROR:
strErrorCode = "无可操作标签错误";//
break;
case INVENTORY_OK_BUT_ACCESS_FAIL:
strErrorCode = "成功盘存但访问失败";//
break;
case BUFFER_IS_EMPTY_ERROR:
strErrorCode = "缓存为空";//
break;
case ACCESS_OR_PASSWORD_ERROR:
strErrorCode = "访问标签错误或访问密码错误";//
break;
case PARAMETER_INVALID:
strErrorCode = "无效的参数";//
break;
case PARAMETER_INVALID_WORDCNT_TOO_LONG:
strErrorCode = "wordCnt 参数超过规定长度";//
break;
case PARAMETER_INVALID_MEMBANK_OUT_OF_RANGE:
strErrorCode = "MemBank 参数超出范围";//
break;
case PARAMETER_INVALID_LOCK_REGION_OUT_OF_RANGE:
strErrorCode = "Lock 数据区参数超出范围";//
break;
case PARAMETER_INVALID_LOCK_ACTION_OUT_OF_RANGE:
strErrorCode = "LockType 参数超出范围";//
break;
case PARAMETER_READER_ADDRESS_INVALID:
strErrorCode = "读写器地址无效";//
break;
case PARAMETER_INVALID_ANTENNA_ID_OUT_OF_RANGE:
strErrorCode = "Antenna_id 超出范围";//
break;
case PARAMETER_INVALID_OUTPUT_POWER_OUT_OF_RANGE:
strErrorCode = "输出功率参数超出范围";//
break;
case PARAMETER_INVALID_FREQUENCY_REGION_OUT_OF_RANGE:
strErrorCode = "射频规范区域参数超出范围";//
break;
case PARAMETER_INVALID_BAUDRATE_OUT_OF_RANGE:
strErrorCode = "波特率参数超出范围";//
break;
case PARAMETER_BEEPER_MODE_OUT_OF_RANGE:
strErrorCode = "蜂鸣器设置参数超出范围";//
break;
case PARAMETER_EPC_MATCH_LEN_TOO_LONG:
strErrorCode = "EPC 匹配长度越界";//
break;
case PARAMETER_EPC_MATCH_LEN_ERROR:
strErrorCode = "EPC 匹配长度错误";//
break;
case PARAMETER_INVALID_EPC_MATCH_MODE:
strErrorCode = "EPC 匹配参数超出范围";//
break;
case PARAMETER_INVALID_FREQUENCY_RANGE:
strErrorCode = "频率范围设置参数错误";//
break;
case FAIL_TO_GET_RN16_FROM_TAG:
strErrorCode = "无法接收标签的RN16";//
break;
case PARAMETER_INVALID_DRM_MODE:
strErrorCode = "DRM 设置参数错误";//
break;
case PLL_LOCK_FAIL:
strErrorCode = "PLL 不能锁定";//
break;
case RF_CHIP_FAIL_TO_RESPONSE:
strErrorCode = "射频芯片无响应";//
break;
case FAIL_TO_ACHIEVE_DESIRED_OUTPUT_POWER:
strErrorCode = "输出达不到指定的输出功率";//
break;
case COPYRIGHT_AUTHENTICATION_FAIL:
strErrorCode = "版权认证未通过";//
break;
case SPECTRUM_REGULATION_ERROR:
strErrorCode = "频谱规范设置错误";//
break;
case OUTPUT_POWER_TOO_LOW:
strErrorCode = "输出功率过低";//
break;
default:
strErrorCode = "未知错误";//
break;
}
return strErrorCode;
}
}
package com.fn.useries.reader;
public class HEAD {
public final static byte HEAD = (byte) 0xA0;
}
package com.fn.useries.reader;
public class MessageTran {
private byte btPacketType; //数据包头,默认为0xA0
private byte btDataLen; //数据包长度,数据包从‘长度’字节后面开始的字节数,不包含‘长度’字节本身
private byte btReadId; //读写器地址
private byte btCmd; //数据包命令代码
private byte[] btAryData; //数据包命令参数,部分命令无参数
private byte btCheck; //校验和,除校验和本身外所有字节的校验和
private byte[] btAryTranData; //完整数据包
public MessageTran() {
}
public MessageTran(byte btReadId, byte btCmd, byte[] btAryData) {
int nLen = btAryData.length;
this.btPacketType = HEAD.HEAD;
this.btDataLen = (byte)(nLen + 3);
this.btReadId = btReadId;
this.btCmd = btCmd;
this.btAryData = new byte[nLen];
System.arraycopy(btAryData, 0, this.btAryData, 0, btAryData.length);
//btAryData.CopyTo(this.btAryData, 0);
this.btAryTranData = new byte[nLen + 5];
this.btAryTranData[0] = this.btPacketType;
this.btAryTranData[1] = this.btDataLen;
this.btAryTranData[2] = this.btReadId;
this.btAryTranData[3] = this.btCmd;
System.arraycopy(this.btAryData, 0, this.btAryTranData, 4, this.btAryData.length);
//this.btAryData.CopyTo(this.btAryTranData, 4);
this.btCheck = checkSum(this.btAryTranData, 0, nLen + 4);
this.btAryTranData[nLen + 4] = this.btCheck;
}
public MessageTran(byte btReadId, byte btCmd) {
this.btPacketType = HEAD.HEAD;
this.btDataLen = 0x03;
this.btReadId = btReadId;
this.btCmd = btCmd;
this.btAryTranData = new byte[5];
this.btAryTranData[0] = this.btPacketType;
this.btAryTranData[1] = this.btDataLen;
this.btAryTranData[2] = this.btReadId;
this.btAryTranData[3] = this.btCmd;
this.btCheck = checkSum(this.btAryTranData, 0, 4);
this.btAryTranData[4] = this.btCheck;
}
public MessageTran(byte[] btAryTranData) {
int nLen = btAryTranData.length;
this.btAryTranData = new byte[nLen];
System.arraycopy(btAryTranData, 0, this.btAryTranData, 0, btAryTranData.length);
//btAryTranData.CopyTo(this.btAryTranData, 0);
byte btCK = checkSum(this.btAryTranData, 0, this.btAryTranData.length - 1);
if (btCK != btAryTranData[nLen - 1]) {
return;
}
this.btPacketType = btAryTranData[0];
this.btDataLen = btAryTranData[1];
this.btReadId = btAryTranData[2];
this.btCmd = btAryTranData[3];
this.btCheck = btAryTranData[nLen - 1];
if (nLen > 5) {
this.btAryData = new byte[nLen - 5];
for (int nloop = 0; nloop < nLen - 5; nloop++ ) {
this.btAryData[nloop] = btAryTranData[4 + nloop];
}
}
}
//设置属性
/**
* 获取完整数据包。
* @return 数据包
*/
public byte[] getAryTranData() {
return this.btAryTranData;
}
/**
* 获取数据包命令参数,部分命令无参数。
* @return 命令参数
*/
public byte[] getAryData() {
return this.btAryData;
}
/**
* 获取读写器地址。
* @return 读写器地址
*/
public byte getReadId() {
return this.btReadId;
}
/**
* 获取数据包命令字。
* @return 命令字
*/
public byte getCmd() {
return this.btCmd;
}
/**
* 获取数据包头,默认为0xA0。
* @return 数据包头
*/
public byte getPacketType() {
return this.btPacketType;
}
/**
* 校验包头。
* @return 校验结果
*/
public boolean checkPacketType() {
return this.btPacketType == HEAD.HEAD;
}
/**
* 计算校验和
* @param btAryBuffer 数据
* @param nStartPos 起始位置
* @param nLen 校验长度
* @return 校验和
*/
public byte checkSum(byte[] btAryBuffer, int nStartPos, int nLen) {
byte btSum = 0x00;
for (int nloop = nStartPos; nloop < nStartPos + nLen; nloop++ ) {
btSum += btAryBuffer[nloop];
}
return (byte)(((~btSum) + 1) & 0xFF);
}
}
package com.fn.useries.reader.model;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class ISO180006BOperateTagBuffer {
public static class ISO180006BOperateTagMap {
public byte btAntId;
public String strUID;
public int nTotal;
public byte btStartAdd;
public int nLength;
public String strData;
public byte btStatus;
public ISO180006BOperateTagMap() {
btAntId = 0;
strUID = "";
nTotal = 0;
btStartAdd = 0;
nLength = 0;
strData = "";
btStatus = 0;
}
}
public Map<String, Integer> dtIndexMap;
public List<ISO180006BOperateTagMap> lsTagList;
public byte btAntId;
public int nTagCount;
public String strReadData;
public byte btWriteLength;
public byte btStatus;
public ISO180006BOperateTagBuffer() {
btAntId = (byte) 0xFF;
nTagCount = 0;
strReadData = "";
btWriteLength = 0x00;
btStatus = 0x00;
dtIndexMap = new LinkedHashMap<String, Integer>();
lsTagList = new ArrayList<ISO180006BOperateTagMap>();
}
public void clearBuffer() {
btAntId = (byte) 0xFF;
nTagCount = 0;
strReadData = "";
btWriteLength = 0x00;
btStatus = 0x00;
clearTagMap();
}
public final void clearTagMap() {
dtIndexMap.clear();
lsTagList.clear();
}
}
package com.fn.useries.reader.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class InventoryBuffer implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public static class InventoryTagMap {
public String strPC;
public String strCRC;
public String strEPC;
public byte btAntId;
public String strRSSI;
public int nReadCount;
public String strFreq;
public int nAnt1;
public int nAnt2;
public int nAnt3;
public int nAnt4;
public InventoryTagMap() {
strPC = "";
strCRC = "";
strEPC = "";
btAntId = 0;
strRSSI = "";
nReadCount = 0;
strFreq = "";
nAnt1 = 0;
nAnt2 = 0;
nAnt3 = 0;
nAnt4 = 0;
}
}
public byte btRepeat;
public byte btSession;
public byte btTarget;
public byte btA, btB, btC, btD;
public byte btStayA, btStayB, btStayC, btStayD;
public byte btInterval;
public byte btFastRepeat;
public ArrayList<Byte> lAntenna;
public boolean bLoopInventory;
public int nIndexAntenna;
public int nCommond;
public boolean bLoopInventoryReal;
public boolean bLoopCustomizedSession;
public int nTagCount;
public int nDataCount; //执行一次命令所返回的标签记录条数
public int nCommandDuration;
public int nReadRate;
public int nCurrentAnt;
public int nTotalRead;
public Date dtStartInventory;
public Date dtEndInventory;
public int nMaxRSSI;
public int nMinRSSI;
public Map<String, Integer> dtIndexMap;
public List<InventoryTagMap> lsTagList;
public InventoryBuffer() {
btRepeat = 0x00;
btFastRepeat = 0x00;
/** 大于3表示不轮询*/
btA = btB = btC = btD = (byte) 0xFF;
btStayA = btStayB = btStayC = btStayD = 0x01;
lAntenna = new ArrayList<Byte>();
bLoopInventory = false;
nIndexAntenna = 0;
nCommond = 0;
bLoopInventoryReal = false;
nTagCount = 0;
nReadRate = 0;
nTotalRead = 0;
dtStartInventory = new Date();
dtEndInventory = dtStartInventory;
nMaxRSSI = 0;
nMinRSSI = 0;
dtIndexMap = new LinkedHashMap<String, Integer>();
lsTagList = new ArrayList<InventoryTagMap>();
}
public final void clearInventoryPar() {
btRepeat = 0x00;
lAntenna.clear();
//bLoopInventory = false;
nIndexAntenna = 0;
nCommond = 0;
bLoopInventoryReal = false;
}
public final void clearInventoryResult() {
nTagCount = 0;
nReadRate = 0;
nTotalRead = 0;
dtStartInventory = new Date();
dtEndInventory = dtStartInventory;
nMaxRSSI = 0;
nMinRSSI = 0;
clearTagMap();
}
public final void clearInventoryRealResult() {
nTagCount = 0;
nReadRate = 0;
nTotalRead = 0;
dtStartInventory = new Date();
dtEndInventory = dtStartInventory;
nMaxRSSI = 0;
nMinRSSI = 0;
clearTagMap();
}
public final void clearTagMap() {
dtIndexMap.clear();
lsTagList.clear();
}
}
package com.fn.useries.reader.model;
import java.util.ArrayList;
import java.util.List;
public class OperateTagBuffer {
public static class OperateTagMap {
public String strPC;
public String strCRC;
public String strEPC;
public String strData;
public int nDataLen;
public byte btAntId;
public int nReadCount;
public OperateTagMap() {
strPC = "";
strCRC = "";
strEPC = "";
strData = "";
nDataLen = 0;
btAntId = 0;
nReadCount = 0;
}
}
public String strAccessEpcMatch;
public List<OperateTagMap> lsTagList;
public OperateTagBuffer() {
strAccessEpcMatch = "";
lsTagList = new ArrayList<OperateTagMap>();
}
public final void clearBuffer() {
lsTagList.clear();
}
}
package com.fn.useries.reader.model;
public class ReaderSetting {
public byte btReadId;
public byte btMajor;
public byte btMinor;
public byte btIndexBaudrate;
public byte btPlusMinus;
public byte btTemperature;
/**1-4字节*/
public byte []btAryOutputPower;
public byte btWorkAntenna;
public byte btDrmMode;
public byte btRegion;
public byte btFrequencyStart;
public byte btFrequencyEnd;
public byte btBeeperMode;
public byte btGpio1Value;
public byte btGpio2Value;
public byte btGpio3Value;
public byte btGpio4Value;
public byte btAntDetector;
public byte btMonzaStatus;
public boolean blnMonzaStore;
/**固定12字节*/
public byte []btAryReaderIdentifier;
public byte btReturnLoss;
public byte btImpedanceFrequency;
public int nUserDefineStartFrequency;
public byte btUserDefineFrequencyInterval;
public byte btUserDefineChannelQuantity;
public byte btRfLinkProfile;
public boolean blnSetResult;
public String strErrorCode;
public ReaderSetting() {
btReadId = (byte) 0xFF;
btMajor = 0x00;
btMinor = 0x00;
btIndexBaudrate = 0x00;
btPlusMinus = 0x00;
btTemperature = 0x00;
btAryOutputPower = null;
btWorkAntenna = 0x00;
btDrmMode = 0x00;
btRegion = 0x00;
btFrequencyStart = 0x00;
btFrequencyEnd = 0x00;
btBeeperMode = 0x00;
blnMonzaStore = false;
btGpio1Value = 0x00;
btGpio2Value = 0x00;
btGpio3Value = 0x00;
btGpio4Value = 0x00;
btAntDetector = 0x00;
btMonzaStatus = 0x00;
btAryReaderIdentifier = new byte[12];
btReturnLoss = 0x00;
btImpedanceFrequency = 0x00;
nUserDefineStartFrequency = 0x00;
btUserDefineFrequencyInterval = 0x00;
btUserDefineChannelQuantity = 0x00;
btRfLinkProfile = 0x00;
}
}
package com.fn.useries.utils;
import android.os.Environment;
import com.fn.useries.reader.model.InventoryBuffer.InventoryTagMap;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class FileUtil {
public static boolean saveInventoryData(List<InventoryTagMap> data) {
FileOutputStream fos = null;
try {
Date time = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HHmmss", Locale.CHINA);
String dateString = formatter.format(time);
File path = Environment.getExternalStorageDirectory();
File file = new File(path + "/fn_log/U8/" + dateString + System.currentTimeMillis() + ".csv");
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
fos = new FileOutputStream(file);
String header="ID,EPC,PC,Count,RSSI,RISS\r\n";
fos.write(header.getBytes());
for(int i=0;i<data.size();i++){
String ID= String.valueOf(i+1);
String epc=data.get(i).strEPC;
String PC=data.get(i).strPC;
int Count=data.get(i).nReadCount;
String RSSI=(Integer.parseInt(data.get(i).strRSSI) - 129) +"";
String RISS=data.get(i).strFreq;
String datas=ID+","+epc+","+PC+","+Count+","+RSSI+","+RISS+"\r\n";
fos.write(datas.getBytes());
fos.flush();
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
return true;
}
}
package com.fn.useries.utils;
import android.util.Log;
import java.io.FileOutputStream;
public class M10_GPIO {
public static void _14443A_PowerOn() {
writeFile("/sys/bus/platform/devices/odroid-sysfs/ic14443a_enable", "1");
writeFile(
"/sys/bus/platform/devices/odroid-sysfs/ic14443a_serial_switch",
"0");
}
public static void _14443A_PowerOFF() {
writeFile("/sys/bus/platform/devices/odroid-sysfs/ic14443a_enable", "0");
writeFile(
"/sys/bus/platform/devices/odroid-sysfs/ic14443a_serial_switch",
"0");
}
public static void Infrared_PowerOn() {
writeFile("/syss/platform/devices/odroid-sysfs/infrared_enable_switch",
"0");
}
public static void Infrared_PowerOFF() {
writeFile("/syss/platform/devices/odroid-sysfs/rfid_serial_switch", "0");
}
public static void R1000_PowerOn() {
writeFile("/sys/bus/platform/devices/odroid-sysfs/r1000_enable", "1");
writeFile("/sys/bus/platform/devices/odroid-sysfs/r1000_serial_switch",
"1");
}
public static void R1000_PowerOFF() {
writeFile("/sys/bus/platform/devices/odroid-sysfs/r1000_enable", "0");
writeFile("/sys/bus/platform/devices/odroid-sysfs/r1000_serial_switch",
"0");
}
public static void W433_PowerOn() {
writeFile("/sys/bus/platform/devices/odroid-sysfs/rfid_enable", "1");
writeFile("/sys/ bus/platform/devices/odroid-sysfs/rfid_serial_switch",
"0");
}
public static void W433_PowerOff() {
writeFile("/sys/bus/platform/devices/odroid-sysfs/rfid_enable", "0");
writeFile("/sys/ bus/platform/devices/odroid-sysfs/rfid_serial_switch",
"0");
}
private static void writeF() {
/*
* String cmd = "chmod 666 " + device.getAbsolutePath() + "\n" +
* "exit\n"; su.getOutputStream().write(cmd.getBytes());
*/
}
// 写数据
private static boolean writeFile(String fileName, String writestr) {
try {
// Process su = Runtime.getRuntime().exec("su"); // /system/bin/
FileOutputStream fout = new FileOutputStream(fileName);
byte[] bytes = writestr.getBytes();
fout.write(bytes);
fout.close();
} catch (Exception e) {
e.printStackTrace();
Log.e("M10_GPIO", e.getMessage());
return false;
}
return true;
}
}
package com.fn.useries.utils;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import com.stm.asset.R;
import com.stm.asset.base.StmApplication;
import java.util.Map;
import java.util.TreeMap;
public class MusicPlayer {
private Context mContext;
private static MusicPlayer sInstance;
public static class Type {
public final static int OK = 1;
public final static int MUSIC_ERROR = 2;
}
private SoundPool mSp;
private Map<Integer, Integer> sSpMap;
private MusicPlayer(Context context) {
mContext = context;
sSpMap = new TreeMap<Integer, Integer>();
mSp = new SoundPool(2, AudioManager.STREAM_MUSIC, 100);
sSpMap.put(Type.OK, mSp.load(mContext, R.raw.ok, 1));
sSpMap.put(Type.MUSIC_ERROR, mSp.load(mContext, R.raw.error, 1));
// sSpMap.put(Type.MUSIC_FOCUSED, mSp.load(mContext, R.raw.focused, 1))
// ;
}
static {
sInstance = new MusicPlayer(StmApplication.getInstance().getApplicationContext());
}
public static MusicPlayer getInstance() {
return sInstance;
}
public void play(int type) {
if (U8Property.getSoftSound() == 0) {
return;
}
if (sSpMap.get(type) == null)
return;
mSp.play(sSpMap.get(type), 1, 1, 0, 0, 1);
}
}
\ No newline at end of file
package com.fn.useries.utils;
import java.util.ArrayList;
import java.util.regex.Pattern;
public class StringTool {
/**
* 字符串转16进制数组,字符串以空格分割。
* @param strHexValue 16进制字符串
* @return 数组
*/
public static byte[] stringToByteArray(String strHexValue) {
String[] strAryHex = strHexValue.split(" ");
byte[] btAryHex = new byte[strAryHex.length];
try {
int nIndex = 0;
for (String strTemp : strAryHex) {
btAryHex[nIndex] = (byte) Integer.parseInt(strTemp, 16);
nIndex++;
}
} catch (NumberFormatException e) {
}
return btAryHex;
}
/**
* 字符数组转为16进制数组。
* @param strAryHex 要转换的字符串数组
* @param nLen 长度
* @return 数组
*/
public static byte[] stringArrayToByteArray(String[] strAryHex, int nLen) {
if (strAryHex == null) return null;
if (strAryHex.length < nLen) {
nLen = strAryHex.length;
}
byte[] btAryHex = new byte[nLen];
try {
for (int i = 0; i < nLen; i++) {
btAryHex[i] = (byte) Integer.parseInt(strAryHex[i], 16);
}
} catch (NumberFormatException e) {
}
return btAryHex;
}
/**
* 16进制字符数组转成字符串。
* @param btAryHex 要转换的字符串数组
* @param nIndex 起始位置
* @param nLen 长度
* @return 字符串
*/
public static String byteArrayToString(byte[] btAryHex, int nIndex, int nLen) {
if (nIndex + nLen > btAryHex.length) {
nLen = btAryHex.length - nIndex;
}
String strResult = String.format("%02X", btAryHex[nIndex]);
for (int nloop = nIndex + 1; nloop < nIndex + nLen; nloop++ ) {
String strTemp = String.format(" %02X", btAryHex[nloop]);
strResult += strTemp;
}
return strResult;
}
/**
* 将字符串按照指定长度截取并转存为字符数组,空格忽略。
* @param strValue 输入字符串
* @return 数组
*/
public static String[] stringToStringArray(String strValue, int nLen) {
String[] strAryResult = null;
if (strValue != null && !strValue.equals("")) {
ArrayList<String> strListResult = new ArrayList<String>();
String strTemp = "";
int nTemp = 0;
for (int nloop = 0; nloop < strValue.length(); nloop++) {
if (strValue.charAt(nloop) == ' ') {
continue;
} else {
nTemp++;
if (!Pattern.compile("^(([A-F])*([a-f])*(\\d)*)$")
.matcher(strValue.substring(nloop, nloop + 1))
.matches()) {
return strAryResult;
}
strTemp += strValue.substring(nloop, nloop + 1);
//判断是否到达截取长度
if ((nTemp == nLen) || (nloop == strValue.length() - 1
&& (strTemp != null && !strTemp.equals("")))) {
strListResult.add(strTemp);
nTemp = 0;
strTemp = "";
}
}
}
if (strListResult.size() > 0) {
strAryResult = new String[strListResult.size()];
for (int i = 0; i < strAryResult.length; i++) {
strAryResult[i] = strListResult.get(i);
}
}
}
return strAryResult;
}
}
package com.fn.useries.utils;
import android.util.Log;
import com.fn.useries.reader.model.InventoryBuffer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
public class Tools {
// byte 转十六进制
public static String Bytes2HexString(byte[] b, int size) {
String ret = "";
for (int i = 0; i < size; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = "0" + hex;
}
ret += hex.toUpperCase();
}
return ret;
}
public static byte uniteBytes(byte src0, byte src1) {
byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 })).byteValue();
_b0 = (byte) (_b0 << 4);
byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 })).byteValue();
byte ret = (byte) (_b0 ^ _b1);
return ret;
}
// 十六进制转byte
public static byte[] HexString2Bytes(String src) {
int len = src.length() / 2;
byte[] ret = new byte[len];
byte[] tmp = src.getBytes();
for (int i = 0; i < len; i++) {
ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
}
return ret;
}
/* byte[]转Int */
public static int bytesToInt(byte[] bytes) {
int addr = bytes[0] & 0xFF;
addr |= ((bytes[1] << 8) & 0xFF00);
addr |= ((bytes[2] << 16) & 0xFF0000);
addr |= ((bytes[3] << 25) & 0xFF000000);
return addr;
}
/* Int转byte[] */
public static byte[] intToByte(int i) {
byte[] abyte0 = new byte[4];
abyte0[0] = (byte) (0xff & i);
abyte0[1] = (byte) ((0xff00 & i) >> 8);
abyte0[2] = (byte) ((0xff0000 & i) >> 16);
abyte0[3] = (byte) ((0xff000000 & i) >> 24);
return abyte0;
}
/**
* 获取系统时间,时间格式为: 年-月-日 时:分 秒
*
* @return
*/
public static String getTime() {
String model = "yyyy-MM-dd HH:mm:ss";
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat(model);
String dateTime = format.format(date);
return dateTime;
}
public static byte getCRC(byte[] cmd, int pos, int len) {
byte crc = (byte) 0x00;
for (int i = pos; i < len - 1; i++) {
crc += cmd[i];
}
return crc;
}
/**
* 字符串转16进制数组,字符串以空格分割。
*
* @param strHexValue
* 16进制字符串
* @return 数组
*/
public static byte[] stringToByteArray(String strHexValue) {
String[] strAryHex = strHexValue.split(" ");
byte[] btAryHex = new byte[strAryHex.length];
try {
int nIndex = 0;
for (String strTemp : strAryHex) {
btAryHex[nIndex] = (byte) Integer.parseInt(strTemp, 16);
nIndex++;
}
} catch (NumberFormatException e) {
}
return btAryHex;
}
/**
* 字符数组转为16进制数组。
*
* @param strAryHex
* 要转换的字符串数组
* @param nLen
* 长度
* @return 数组
*/
public static byte[] stringArrayToByteArray(String[] strAryHex, int nLen) {
if (strAryHex == null)
return null;
if (strAryHex.length < nLen) {
nLen = strAryHex.length;
}
byte[] btAryHex = new byte[nLen];
try {
for (int i = 0; i < nLen; i++) {
btAryHex[i] = (byte) Integer.parseInt(strAryHex[i], 16);
}
} catch (NumberFormatException e) {
}
return btAryHex;
}
/**
* 16进制字符数组转成字符串。
*
* @param btAryHex
* 要转换的字符串数组
* @param nIndex
* 起始位置
* @param nLen
* 长度
* @return 字符串
*/
public static String byteArrayToString(byte[] btAryHex, int nIndex, int nLen) {
if (nIndex + nLen > btAryHex.length) {
nLen = btAryHex.length - nIndex;
}
String strResult = String.format("%02X", btAryHex[nIndex]);
for (int nloop = nIndex + 1; nloop < nIndex + nLen; nloop++) {
String strTemp = String.format(" %02X", btAryHex[nloop]);
strResult += strTemp;
}
return strResult;
}
/**
* 将字符串按照指定长度截取并转存为字符数组,空格忽略。
*
* @param strValue
* 输入字符串
* @return 数组
*/
public static String[] stringToStringArray(String strValue, int nLen) {
String[] strAryResult = null;
if (strValue != null && !strValue.equals("")) {
ArrayList<String> strListResult = new ArrayList<String>();
String strTemp = "";
int nTemp = 0;
for (int nloop = 0; nloop < strValue.length(); nloop++) {
if (strValue.charAt(nloop) == ' ') {
continue;
} else {
nTemp++;
if (!Pattern.compile("^(([A-F])*([a-f])*(\\d)*)$").matcher(strValue.substring(nloop, nloop + 1)).matches()) {
return strAryResult;
}
strTemp += strValue.substring(nloop, nloop + 1);
// 判断是否到达截取长度
if ((nTemp == nLen) || (nloop == strValue.length() - 1 && (strTemp != null && !strTemp.equals("")))) {
strListResult.add(strTemp);
nTemp = 0;
strTemp = "";
}
}
}
if (strListResult.size() > 0) {
strAryResult = new String[strListResult.size()];
for (int i = 0; i < strAryResult.length; i++) {
strAryResult[i] = strListResult.get(i);
}
}
}
return strAryResult;
}
/**
* 16进制转ASCII
*
* @param hex
* @return
*/
public static String covertAscii(String hex) {
StringBuilder sb = new StringBuilder();
StringBuilder temp = new StringBuilder();
//49204c6f7665204a617661 split into two characters 49, 20, 4c...
for (int i = 0; i < hex.length() - 1; i += 2) {
//grab the hex in pairs
String output = hex.substring(i, (i + 2));
//convert hex to decimal
int decimal = Integer.parseInt(output, 16);
//convert the decimal to character
sb.append((char) decimal);
temp.append(decimal);
}
return sb.toString();
}
/**
* 冒泡排序
* 比较相邻的元素。如果第一个比第二个大,就交换他们两个。
* 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。
* 针对所有的元素重复以上的步骤,除了最后一个。
* 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
*/
public static List<InventoryBuffer.InventoryTagMap> bubbleSort(List<InventoryBuffer.InventoryTagMap> list)
{
String temp = "";
int size = list.size();
for(int i = 0 ; i < size-1; i ++)
{
for(int j = 0 ;j < size-1-i ; j++)
{
if (list.get(j).strEPC.length()>3){
try {
if(Integer.parseInt(list.get(j).strEPC.substring(list.get(j).strEPC.length()-5)) > Integer.parseInt(list.get(j+1).strEPC.substring(list.get(j+1).strEPC.length()-5))) //交换两数位置
{
temp = list.get(j).strEPC;
list.get(j).strEPC = list.get(j+1).strEPC;
list.get(j+1).strEPC = temp;
}
}catch (Exception e){
Log.i("Tools", "bubbleSort: error");
}
}
}
}
return list;
}
}
package com.fn.useries.utils;
import android.content.Context;
import android.content.SharedPreferences;
import com.stm.asset.base.StmApplication;
/**
* 类名称:U8Property
* 类描述:U8本地存储信息
* 创建人:story
* 创建时间:2021-12-17 14:02
*/
public class U8Property {
private static final String PREFERENCES_SYSTEM = "preferences_u8";
private static final String KEY_SESSION = "_session";
private static final String KEY_FLAG = "_flag";
private static final String KEY_STATE = "_state";
private static final String KEY_SOFTWARE_SOUND = "_software_sound";
static public int getSessionState(){
Context context = StmApplication.getInstance().getApplicationContext();
SharedPreferences spf = context.getSharedPreferences(PREFERENCES_SYSTEM, Context.MODE_PRIVATE);
return spf.getInt(KEY_SESSION, 0);
}
static public void saveSessionState(int state){
Context context = StmApplication.getInstance().getApplicationContext();
SharedPreferences spf = context.getSharedPreferences(PREFERENCES_SYSTEM, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = spf.edit();
editor.putInt(KEY_SESSION, state);
editor.apply();
}
static public int getFlagState(){
Context context = StmApplication.getInstance().getApplicationContext();
SharedPreferences spf = context.getSharedPreferences(PREFERENCES_SYSTEM, Context.MODE_PRIVATE);
//SharedPreferences.Editor editor = spf.edit();
int state = spf.getInt(KEY_FLAG, 0);
return state;
}
static public void saveFlagState(int state){
Context context = StmApplication.getInstance().getApplicationContext();
SharedPreferences spf = context.getSharedPreferences(PREFERENCES_SYSTEM, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = spf.edit();
editor.putInt(KEY_FLAG, state);
editor.apply();
}
static public int getVeeperState(){
Context context = StmApplication.getInstance().getApplicationContext();
SharedPreferences spf = context.getSharedPreferences(PREFERENCES_SYSTEM, Context.MODE_PRIVATE);
return spf.getInt(KEY_STATE, 0);
}
static public void saveBeeperState(int state){
Context context = StmApplication.getInstance().getApplicationContext();
SharedPreferences spf = context.getSharedPreferences(PREFERENCES_SYSTEM, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = spf.edit();
editor.putInt(KEY_STATE, state);
editor.apply();
}
static public int getSoftSound(){
Context context = StmApplication.getInstance().getApplicationContext();
SharedPreferences spf =context.getSharedPreferences(PREFERENCES_SYSTEM, Context.MODE_PRIVATE);
//SharedPreferences.Editor editor = spf.edit();
return spf.getInt(KEY_SOFTWARE_SOUND, 1);
}
static public void saveSoftSound(int state){
Context context = StmApplication.getInstance().getApplicationContext();
SharedPreferences spf = context.getSharedPreferences(PREFERENCES_SYSTEM, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = spf.edit();
editor.putInt(KEY_SOFTWARE_SOUND, state);
editor.apply();
}
}
package com.stm.asset.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.stm.asset.R;
import com.stm.asset.model.AddressInfo;
import com.stm.asset.utils.StringUtils;
import java.util.List;
/**
* 类名称:AddressAdapter
* 类描述:地址适配器
* 创建人:story
* 创建时间:2022-01-06 09:52
*/
public class AddressAdapter extends BaseAdapter {
private List<AddressInfo> dataList;
private Context context;
public AddressAdapter(Context context, List<AddressInfo> dataList) {
this.context = context;
this.dataList = dataList;
}
@Override
public int getCount() {
return dataList == null ? 0 : dataList.size();
}
@Override
public Object getItem(int position) {
return dataList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vh;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.view_select_id_item, null);
vh = new ViewHolder();
vh.nameTxt = convertView.findViewById(R.id.select_ip_item_name);
vh.ipTxt = convertView.findViewById(R.id.select_ip_item_ip);
vh.platformTxt = convertView.findViewById(R.id.select_ip_item_platform);
vh.selectImage = convertView.findViewById(R.id.select_ip_item_select_image);
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
AddressInfo addressInfo = dataList.get(position);
vh.nameTxt.setText(addressInfo.getName());
// 处理ip
StringBuffer sbf = new StringBuffer();
if (addressInfo.isHttps()) {
sbf.append("https://");
} else {
sbf.append("http://");
}
sbf.append(addressInfo.getIp());
if (!StringUtils.isEmptyOrNull(addressInfo.getPort())) {
sbf.append(":");
sbf.append(addressInfo.getPort());
}
vh.ipTxt.setText(sbf.toString());
vh.platformTxt.setText(addressInfo.getPlatform());
return convertView;
}
private class ViewHolder {
private TextView nameTxt, ipTxt, platformTxt;
private ImageView selectImage;
}
}
package com.stm.asset.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.fn.useries.reader.model.InventoryBuffer;
import com.fn.useries.utils.Tools;
import com.stm.asset.R;
import com.stm.asset.utils.StringUtils;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
/**
* 类名称:InventoryAdapter
* 类描述:盘询数据展示适配器
* 创建人:story
* 创建时间:2021-12-09 15:34
*/
public class InventoryAdapter extends BaseAdapter {
private LayoutInflater inflater;
private List<InventoryBuffer.InventoryTagMap> dataList;
public InventoryAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return dataList == null ? 0 : dataList.size();
}
@Override
public Object getItem(int position) {
return dataList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView =inflater.inflate(R.layout.view_inventory_item, null);
// viewHolder.idTxt = convertView.findViewById(R.id.item_inventory_id_txt);
viewHolder.epcTxt = convertView.findViewById(R.id.item_inventory_epc_txt);
// viewHolder.pcTxt = convertView.findViewById(R.id.item_inventory_pc_txt);
// viewHolder.timesTxt = convertView.findViewById(R.id.item_inventory_times_txt);
// viewHolder.rssiTxt = convertView.findViewById(R.id.item_inventory_rssi_txt);
// viewHolder.freqTxt = convertView.findViewById(R.id.item_inventory_freq_txt);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
InventoryBuffer.InventoryTagMap inventoryTagMap = dataList.get(position);
// viewHolder.idTxt.setText(String.valueOf(position+1));
try {
String epcStr = inventoryTagMap.strEPC;
byte[] bytes = Tools.stringToByteArray(epcStr);
String str = new String(bytes, StandardCharsets.UTF_8);
viewHolder.epcTxt.setText(str);
} catch (Exception e) {
e.printStackTrace();
}
// viewHolder.pcTxt.setText(inventoryTagMap.strPC);
// viewHolder.timesTxt.setText(String.valueOf(inventoryTagMap.nReadCount));
// try {
// viewHolder.rssiTxt.setText((Integer.parseInt(inventoryTagMap.strRSSI) - 129) + "dBm");
// } catch (Exception e) {
// viewHolder.rssiTxt.setText("");
// }
// viewHolder.freqTxt.setText(inventoryTagMap.strFreq);
return convertView;
}
public void setData(List<InventoryBuffer.InventoryTagMap> data, boolean isReset) {
if (dataList == null) {
dataList = new ArrayList<>();
}
if (isReset) {
dataList.clear();
}
if (data != null && data.size() > 0) {
// 处理标签数据
for (InventoryBuffer.InventoryTagMap item : data) {
String epcStr = item.strEPC;
if (!StringUtils.isEmptyOrNull(epcStr)) {
if (!hasItem(epcStr)) {
try {
byte[] bytes = Tools.stringToByteArray(epcStr);
String str = new String(bytes, StandardCharsets.UTF_8).trim();
if (StringUtils.isNumber(str)) {
dataList.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
notifyDataSetChanged();
}
private boolean hasItem(String epc) {
for (InventoryBuffer.InventoryTagMap item : dataList) {
String epcStr = item.strEPC;
if (epc.equals(epcStr)) {
return true;
}
}
return false;
}
public List<InventoryBuffer.InventoryTagMap> queryData() {
return dataList;
}
private class ViewHolder {
// private TextView idTxt, epcTxt, pcTxt, timesTxt, rssiTxt, freqTxt;
private TextView epcTxt;
}
}
package com.stm.asset.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.stm.asset.R;
import com.stm.asset.model.InventoryInfo;
import java.util.ArrayList;
import java.util.List;
/**
* 类名称:TaskAdapter
* 类描述:盘点任务适配器
* 创建人:story
* 创建时间:2021-12-07 15:27
*/
public class TaskAdapter extends BaseAdapter {
private LayoutInflater inflater;
private List<InventoryInfo> dataList;
public TaskAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return dataList == null ? 0 : dataList.size();
}
@Override
public Object getItem(int position) {
return dataList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView =inflater.inflate(R.layout.view_check_task_item, null);
// viewHolder.nameTxt = convertView.findViewById(R.id.task_item_name_txt);
viewHolder.numberTxt = convertView.findViewById(R.id.task_item_number_txt);
// viewHolder.userTxt = convertView.findViewById(R.id.task_item_user_txt);
// viewHolder.deptTxt = convertView.findViewById(R.id.task_item_dept_txt);
viewHolder.statusTxt = convertView.findViewById(R.id.task_item_status_txt);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
InventoryInfo taskInfo = dataList.get(position);
// viewHolder.nameTxt.setText(taskInfo.getName());
viewHolder.numberTxt.setText(taskInfo.getNumber());
// viewHolder.userTxt.setText(taskInfo.getUserName());
// viewHolder.deptTxt.setText(taskInfo.getUserDept());
String statusName = "";
if ("0".equals(taskInfo.getStatus())) {
statusName = "未上传";
} else if ("1".equals(taskInfo.getStatus())) {
statusName = "上传失败";
} else if ("2".equals(taskInfo.getStatus())) {
statusName = "上传成功";
}
viewHolder.statusTxt.setText(statusName);
return convertView;
}
public void setData(List<InventoryInfo> data) {
if (dataList == null) {
dataList = new ArrayList<>();
}
dataList.clear();
if (data != null && data.size() > 0) {
dataList.addAll(data);
}
notifyDataSetChanged();
}
private class ViewHolder {
// private TextView nameTxt, numberTxt, userTxt, deptTxt, statusTxt;
private TextView numberTxt, statusTxt;
}
}
package com.stm.asset.base;
import android.os.Handler;
import android.os.Looper;
import androidx.annotation.NonNull;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
/**
* 类名称:AppExecutors
* 类描述:线程管理
* 创建人:story
* 创建时间:2021-12-23 14:56
*/
public class AppExecutors {
private final Executor mDiskIO;
private final Executor mNetworkIO;
private final Executor mMainThread;
private AppExecutors(Executor diskIO, Executor networkIO, Executor mainThread) {
this.mDiskIO = diskIO;
this.mNetworkIO = networkIO;
this.mMainThread = mainThread;
}
public AppExecutors() {
this(Executors.newSingleThreadExecutor(), Executors.newFixedThreadPool(3), new MainThreadExecutor());
}
public Executor diskIO() {
return mDiskIO;
}
public Executor networkIO() {
return mNetworkIO;
}
public Executor mainThread() {
return mMainThread;
}
private static class MainThreadExecutor implements Executor {
private Handler mainThreadHandler = new Handler(Looper.getMainLooper());
@Override
public void execute(@NonNull Runnable command) {
mainThreadHandler.post(command);
}
}
}
package com.stm.asset.base;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import com.stm.asset.R;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.util.List;
import me.jessyan.autosize.internal.CustomAdapt;
/**
* 类名称:BaseActivity
* 类描述:Activity基类
* 创建人:story
* 创建时间:2021-08-07 09:47
*/
public abstract class BaseActivity extends Activity implements CustomAdapt {
protected WeakReference<Activity> weakReference;
protected StmApplication sApp;
protected TextView titleTxt, backTxt, rightTxt;
protected ImageView backImg, rightImg;
protected LinearLayout backLayout, rightLayout;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sApp = StmApplication.getInstance();
weakReference = new WeakReference<>((Activity) this);
sApp.enterActivity(weakReference);
}
protected void initTitle(){
try {
titleTxt = findViewById(R.id.common_title_middle_txt);
backImg = findViewById(R.id.common_title_back_img);
backTxt = findViewById(R.id.common_title_back_txt);
backLayout = findViewById(R.id.common_title_back_layout);
rightImg = findViewById(R.id.common_title_right_img);
rightTxt = findViewById(R.id.common_title_right_txt);
rightLayout = findViewById(R.id.common_title_right_layout);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onStop() {
super.onStop();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (!isAppOnForeground()) {
try {
// 弹出Toast提示
StmApplication.getInstance().getCurrentAct().runOnUiThread(new Runnable() {
@Override
public void run() {
if (StmApplication.getInstance().isShowBackground()) {
StmApplication.getInstance().showToastShort(StmApplication.getInstance().getResources().getString(R.string.app_name) + "已经被切到后台运行");
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
}, 500);
}
@Override
protected void onDestroy() {
sApp.removeActivity(weakReference);
super.onDestroy();
}
@Override
public boolean isBaseOnWidth() {
return false;
}
@Override
public float getSizeInDp() {
return 846;
}
private boolean isAppOnForeground() {
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
String runningActivityPackageName;
int sdkVersion;
try {
sdkVersion = Integer.valueOf(android.os.Build.VERSION.SDK);
} catch (NumberFormatException e) {
sdkVersion = 0;
}
if (sdkVersion >= 21) {
runningActivityPackageName = getCurrentPkgName(getApplicationContext());
} else {
runningActivityPackageName = activityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
}
if (getPackageName().equals(runningActivityPackageName)) {
return true;
}
return false;
}
private static String getCurrentPkgName(Context context) {
// 5x系统以后利用反射获取当前栈顶activity的包名.
ActivityManager.RunningAppProcessInfo currentInfo = null;
Field field = null;
int START_TASK_TO_FRONT = 2;
String pkgName = null;
try {
// 通过反射获取进程状态字段.
field = ActivityManager.RunningAppProcessInfo.class.getDeclaredField("processState");
} catch (Exception e) {
e.printStackTrace();
}
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List appList = am.getRunningAppProcesses();
ActivityManager.RunningAppProcessInfo app;
for (int i = 0; i < appList.size(); i++) {
app = (ActivityManager.RunningAppProcessInfo) appList.get(i);
//表示前台运行进程.
if (app.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
Integer state = null;
try {
state = field.getInt(app);// 反射调用字段值的方法,获取该进程的状态.
} catch (Exception e) {
e.printStackTrace();
}
// 根据这个判断条件从前台中获取当前切换的进程对象
if (state != null && state == START_TASK_TO_FRONT) {
currentInfo = app;
break;
}
}
}
if (currentInfo != null) {
pkgName = currentInfo.processName;
}
return pkgName;
}
}
package com.stm.asset.base;
import androidx.fragment.app.Fragment;
/**
* 类名称:BaseFragment
* 类描述:BaseFragment基类
* 创建人:story
* 创建时间:2021-12-07 14:40
*/
public abstract class BaseFragment extends Fragment {
}
package com.stm.asset.base;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import com.stm.asset.R;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.util.List;
import me.jessyan.autosize.internal.CustomAdapt;
/**
* 类名称:BaseFragmentActivity
* 类描述:FragmentActivity基类
* 创建人:story
* 创建时间:2021-12-07 13:48
*/
public abstract class BaseFragmentActivity extends FragmentActivity implements CustomAdapt {
protected WeakReference<Activity> weakReference;
protected StmApplication sApp;
protected TextView titleTxt, backTxt, rightTxt;
protected ImageView backImg, rightImg;
protected LinearLayout backLayout, rightLayout;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sApp = StmApplication.getInstance();
weakReference = new WeakReference<>((Activity) this);
sApp.enterActivity(weakReference);
}
protected void initTitle(){
try {
titleTxt = findViewById(R.id.common_title_middle_txt);
backImg = findViewById(R.id.common_title_back_img);
backTxt = findViewById(R.id.common_title_back_txt);
backLayout = findViewById(R.id.common_title_back_layout);
rightImg = findViewById(R.id.common_title_right_img);
rightTxt = findViewById(R.id.common_title_right_txt);
rightLayout = findViewById(R.id.common_title_right_layout);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onStop() {
super.onStop();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (!isAppOnForeground()) {
try {
// 弹出Toast提示
StmApplication.getInstance().getCurrentAct().runOnUiThread(new Runnable() {
@Override
public void run() {
if (StmApplication.getInstance().isShowBackground()) {
StmApplication.getInstance().showToastShort(StmApplication.getInstance().getResources().getString(R.string.app_name) + "已经被切到后台运行");
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
}, 500);
}
@Override
protected void onDestroy() {
sApp.removeActivity(weakReference);
super.onDestroy();
}
@Override
public boolean isBaseOnWidth() {
return false;
}
@Override
public float getSizeInDp() {
return 846;
}
private boolean isAppOnForeground() {
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
String runningActivityPackageName;
int sdkVersion;
try {
sdkVersion = Integer.valueOf(android.os.Build.VERSION.SDK);
} catch (NumberFormatException e) {
sdkVersion = 0;
}
if (sdkVersion >= 21) {
runningActivityPackageName = getCurrentPkgName(getApplicationContext());
} else {
runningActivityPackageName = activityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
}
if (getPackageName().equals(runningActivityPackageName)) {
return true;
}
return false;
}
private static String getCurrentPkgName(Context context) {
// 5x系统以后利用反射获取当前栈顶activity的包名.
ActivityManager.RunningAppProcessInfo currentInfo = null;
Field field = null;
int START_TASK_TO_FRONT = 2;
String pkgName = null;
try {
// 通过反射获取进程状态字段.
field = ActivityManager.RunningAppProcessInfo.class.getDeclaredField("processState");
} catch (Exception e) {
e.printStackTrace();
}
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List appList = am.getRunningAppProcesses();
ActivityManager.RunningAppProcessInfo app;
for (int i = 0; i < appList.size(); i++) {
app = (ActivityManager.RunningAppProcessInfo) appList.get(i);
//表示前台运行进程.
if (app.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
Integer state = null;
try {
state = field.getInt(app);// 反射调用字段值的方法,获取该进程的状态.
} catch (Exception e) {
e.printStackTrace();
}
// 根据这个判断条件从前台中获取当前切换的进程对象
if (state != null && state == START_TASK_TO_FRONT) {
currentInfo = app;
break;
}
}
}
if (currentInfo != null) {
pkgName = currentInfo.processName;
}
return pkgName;
}
}
package com.stm.asset.base;
public class ConfigKey {
public final static String GATEWAYIP = "mfms.citictrust.com.cn";
public final static String GATWAYPORT = "";
// http://10.50.251.101 18081 测试地址
// https://fms.citictrust.com.cn 生产地址
public final static String PLAYFORM = "FMPAPP";
// CJFKAPP 长江养老
public final static String SIGNATURENAME = "stream"; // 测试环境请配置成stream(生产环境具体再通知)
public final static String SIGNATUREPASSWORD = "stream123"; // 测试环境请配置成stream123(生产环境具体再通知)
public final static String HTTPS_CERTIFICATION_NAME = "feiyongmofang.cer";
public final static boolean DEBUG = true; // 是否打印测试数据
public final static boolean ISOPENHTTPS = true; // 是否开启https请求方式
}
package com.stm.asset.base;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import java.util.List;
/**
* 类名称:FragPageAdapter
* 类描述:Fragment页面适配器
* 创建人:story
* 创建时间:2021-12-07 16:41
*/
public class FragPageAdapter extends FragmentPagerAdapter {
private List<Fragment> fragmentsList;
public FragPageAdapter(FragmentManager fm) {
super(fm);
}
public FragPageAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragmentsList = fragments;
}
@Override
public int getCount() {
return fragmentsList.size();
}
@NonNull
@Override
public Fragment getItem(int arg0) {
return fragmentsList.get(arg0);
}
@Override
public int getItemPosition(@NonNull Object object) {
return super.getItemPosition(object);
}
}
package com.stm.asset.base;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.widget.Toast;
import androidx.multidex.MultiDex;
import com.fn.useries.reader.server.ReaderHelper;
import com.stm.asset.model.UserInfo;
import com.tencent.bugly.crashreport.CrashReport;
import java.lang.ref.WeakReference;
import java.util.Stack;
/**
* 类名称:StmApplication
* 类描述:自定义Application
* 创建人:story
* 创建时间:2021-08-07 09:49
*/
public class StmApplication extends Application {
private static StmApplication instance;
private Stack<WeakReference<Activity>> mActivityStack;
private boolean isShowBackground = true; // 是否提示切换到后台,防止某些地方不需要提示
private static Toast toastLong;
private static Toast toastShort;
private UserInfo userInfo;
private AppExecutors appExecutors;
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
@Override
public void onCreate() {
super.onCreate();
instance = this;
try {
//实例化ReaderHelper并setContext
ReaderHelper.setContext(getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
appExecutors = new AppExecutors();
// 开启bugly异常捕获
CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(getApplicationContext());
strategy.setAppChannel("BASE"); //设置渠道
CrashReport.initCrashReport(getApplicationContext(), "24e17bedee", true, strategy);
}
public static StmApplication getInstance() {
return instance;
}
public void enterActivity(WeakReference<Activity> weakReference) {
if (mActivityStack == null) {
mActivityStack = new Stack<>();
}
mActivityStack.add(weakReference);
}
public void removeActivity(WeakReference<Activity> weakReference) {
if (mActivityStack != null) {
mActivityStack.remove(weakReference);
}
}
public Activity getCurrentAct() {
Activity activity = null;
if (mActivityStack != null) {
activity = mActivityStack.lastElement().get();
}
return activity;
}
public boolean isShowBackground() {
return isShowBackground;
}
public void setShowBackground(boolean showBackground) {
isShowBackground = showBackground;
}
public void showToastLong(String msg) {
if (toastLong == null) {
toastLong = Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG);
} else {
toastLong.setText(msg);
}
toastLong.show();
}
public void showToastShort(String msg) {
if (toastShort == null) {
toastShort = Toast.makeText(getBaseContext(), msg, Toast.LENGTH_SHORT);
} else {
toastShort.setText(msg);
}
toastShort.show();
}
public UserInfo getUserInfo() {
return userInfo;
}
public void setUserInfo(UserInfo userInfo) {
this.userInfo = userInfo;
}
// public String getHttpStr() {
// String httpSb;
// if (PropertyUtil.isUseHttps(this)) {
// httpSb = "https";
// } else {
// httpSb = "http";
// }
// return httpSb;
// }
public AppExecutors getAppExecutors() {
return appExecutors;
}
}
package com.stm.asset.dao;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Update;
import com.stm.asset.model.InventoryInfo;
import java.util.List;
/**
* 类名称:InventoryInfoDao
* 类描述:InventoryInfoDao
* 创建人:story
* 创建时间:2021-12-09 16:36
*/
@Dao
public interface InventoryInfoDao {
/**
* 查询所有数据
*/
@Query("select * from inventoryInfo")
List<InventoryInfo> getAllInventoryInfoList();
@Query("select * from inventoryInfo where (status = '0' or status = '1') and userName = :userName")
List<InventoryInfo> getUndoInventoryList(String userName);
@Query("select * from inventoryInfo where status = '2' and userName = :userName")
List<InventoryInfo> getDoneInventoryList(String userName);
/**
* 插入数据
*/
@Insert(onConflict = OnConflictStrategy.REPLACE)
long[] insertInventoryList(List<InventoryInfo> inventoryInfoList);
/**
* 修改数据
*/
@Update
int updateInventory(InventoryInfo inventoryInfo);
/**
* 删除数据
*/
@Delete
int deleteInventoryList(List<InventoryInfo> inventoryInfoList);
}
package com.stm.asset.database;
import androidx.room.Database;
import androidx.room.RoomDatabase;
import com.stm.asset.dao.InventoryInfoDao;
import com.stm.asset.model.InventoryInfo;
/**
* 类名称:InventoryInfoDatabase
* 类描述:InventoryInfoDatabase
* 创建人:story
* 创建时间:2021-12-09 16:52
*/
@Database(entities = {InventoryInfo.class}, version = 1, exportSchema = false)
public abstract class InventoryInfoDatabase extends RoomDatabase {
public abstract InventoryInfoDao inventoryInfoDao();
}
package com.stm.asset.http;
import org.apache.http.conn.ConnectTimeoutException;
import java.net.SocketTimeoutException;
/**
* 类名称:HttpException
* 类描述:请求异常封装
* 创建人:story
* 创建时间:2021-12-14 14:56
*/
public class HttpException extends Exception {
private static final long serialVersionUID = -4699234082428363296L;
private int exceptionCode;
private Throwable throwable;
public HttpException() {}
public HttpException(String detailMessage) {
super(detailMessage);
}
public HttpException(String detailMessage, Throwable throwable) {
super(detailMessage, throwable);
this.throwable =throwable;
}
public HttpException(Throwable throwable) {
super(throwable);
this.throwable =throwable;
}
public HttpException(int exceptionCode) {
this.exceptionCode = exceptionCode;
}
public HttpException(int exceptionCode, String detailMessage) {
super(detailMessage);
this.exceptionCode = exceptionCode;
}
public HttpException(int exceptionCode, String detailMessage, Throwable throwable) {
super(detailMessage, throwable);
this.exceptionCode = exceptionCode;
this.throwable =throwable;
}
public HttpException(int exceptionCode, Throwable throwable) {
super(throwable);
this.exceptionCode = exceptionCode;
this.throwable =throwable;
}
public int getExceptionCode() {
return exceptionCode;
}
public boolean isConnectTimeout(){
if (this.throwable instanceof ConnectTimeoutException || this.throwable instanceof SocketTimeoutException) {
return true;
}
return false;
}
public Throwable getThrowable() {
return throwable;
}
}
package com.stm.asset.http;
import com.stm.asset.base.InterfaceKey;
import com.stm.asset.json.CommonMapJson;
import com.stm.asset.json.CommonStringJson;
import com.stm.asset.json.ListUserInfo;
/**
* 类名称:HttpService
* 类描述:封装请求服务
* 创建人:story
* 创建时间:2021-12-11 16:00
*/
public class HttpService {
private static HttpService instance;
private HttpService() {}
public static HttpService getInstance() {
if (instance == null) {
instance = new HttpService();
}
return instance;
}
public void unionLoginApp(String accout, String password, RequestCallback<CommonStringJson> requestCallback) {
RequestParams params = new RequestParams();
params.addBodyParameter("username", accout);
params.addBodyParameter("password", password);
HttpUtil.getInstance().sendJson(InterfaceKey.UNIONLOGINAPP, params, requestCallback);
}
public void quryPageHomeUserInfo(String accessToken, RequestCallback<ListUserInfo> requestCallback) {
RequestParams params = new RequestParams();
params.addBodyParameter("accessToken", accessToken);
HttpUtil.getInstance().sendJson(InterfaceKey.QURYPAGEHOMEUSERINFO, params, requestCallback);
}
public void queryAppVersionApp(RequestCallback<CommonMapJson> requestCallback) {
RequestParams params = new RequestParams();
HttpUtil.getInstance().sendJson(InterfaceKey.QUERYVERSIONAPP, params, requestCallback);
}
public void scanInventory(String numberList, RequestCallback<CommonStringJson> requestCallback) {
RequestParams params = new RequestParams();
params.addBodyParameter("numList", numberList);
HttpUtil.getInstance().sendJson(InterfaceKey.SCANINVENTORY, params, requestCallback);
}
}
package com.stm.asset.http;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.stm.asset.base.StmApplication;
import com.stm.asset.utils.PropertyUtil;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.annotations.EverythingIsNonNull;
/**
* 类名称:HttpUtil
* 类描述:网络请求工具类
* 创建人:story
* 创建时间:2021-12-10 17:15
*/
public class HttpUtil {
private static HttpUtil httpUtil;
private OkHttpClient okHttpClient;
private HttpUtil() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addInterceptor(new LoggingInterceptor());
if (PropertyUtil.isUseHttps(StmApplication.getInstance().getApplicationContext())) {
try {
builder.hostnameVerifier(TrustAllSSLSocketFactory.getHostnameVerifier());
builder.sslSocketFactory(TrustAllSSLSocketFactory.createSSLSocketFactory(), new TrustAllSSLSocketFactory.TrustAllManager());
} catch (Exception e) {
e.printStackTrace();
}
}
builder.callTimeout(6000, TimeUnit.MILLISECONDS);
builder.connectTimeout(6000, TimeUnit.MILLISECONDS);
builder.readTimeout(30000, TimeUnit.MILLISECONDS);
builder.writeTimeout(30000, TimeUnit.MILLISECONDS);
okHttpClient = builder.build();
}
public static HttpUtil getInstance() {
if (httpUtil == null) {
httpUtil = new HttpUtil();
}
return httpUtil;
}
public void sendJson1(String interfaceName, RequestParams requestParams, RequestCallback callback) {
// StmApplication.getInstance().getAppExecutors().networkIO().execute(new Runnable() {
// @Override
// public void run() {
//
// }
// });
Request.Builder builder = new Request.Builder();
String url = buildUrl(interfaceName);
Log.i("HttpUtil", String.format("请求方法: %s", url));
builder.url(url);
if (requestParams.getHeaders() != null && requestParams.getHeaders().size() > 0) {
for (Map.Entry<String, String> headerEntry : requestParams.getHeaders().entrySet()) {
builder.header(headerEntry.getKey(), headerEntry.getValue());
}
}
if (requestParams.getBodyParams() != null && requestParams.getBodyParams().size() > 0) {
Log.i("HttpUtil", String.format("请求参数:%s", new Gson().toJson(requestParams.getBodyParams())));
// RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(requestParams.getBodyParams()));
// builder.post(requestBody);
FormBody.Builder bodyBuilder = new FormBody.Builder();
for (Map.Entry<String, String> entry : requestParams.getBodyParams().entrySet()) {
bodyBuilder.add(entry.getKey(), entry.getValue());
}
builder.post(bodyBuilder.build());
}
Request request = builder.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
@EverythingIsNonNull
public void onFailure(Call call, IOException e) {
callback.onFailure(new HttpException(e.getCause()), e.getMessage());
}
@Override
@EverythingIsNonNull
public void onResponse(Call call, Response response) {
boolean flag = false;
if (response.isSuccessful()) {
try {
ResponseBody body = response.body();
if (body != null) {
String result = body.string();
Log.i("HttpUtil", result);
callback.onSuccess(new Gson().fromJson(result, TypeToken.get(callback.getType()).getType()));
flag = true;
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (!flag) {
callback.onFailure(new HttpException("返回数据异常"), "返回数据异常");
}
}
});
}
public void sendJson(String interfaceName, RequestParams requestParams, RequestCallback callback) {
Request.Builder builder = new Request.Builder();
String url = buildUrl(interfaceName);
Log.i("HttpUtil", String.format("请求方法: %s", url));
builder.url(url);
if (requestParams.getHeaders() != null && requestParams.getHeaders().size() > 0) {
for (Map.Entry<String, String> headerEntry : requestParams.getHeaders().entrySet()) {
builder.header(headerEntry.getKey(), headerEntry.getValue());
}
}
if (requestParams.getBodyParams() != null && requestParams.getBodyParams().size() > 0) {
Log.i("HttpUtil", String.format("请求参数:%s", new Gson().toJson(requestParams.getBodyParams())));
// RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(requestParams.getBodyParams()));
// builder.post(requestBody);
FormBody.Builder bodyBuilder = new FormBody.Builder();
for (Map.Entry<String, String> entry : requestParams.getBodyParams().entrySet()) {
bodyBuilder.add(entry.getKey(), entry.getValue());
}
builder.post(bodyBuilder.build());
}
Request request = builder.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
@EverythingIsNonNull
public void onFailure(Call call, IOException e) {
StmApplication.getInstance().getAppExecutors().mainThread().execute(new Runnable() {
@Override
public void run() {
callback.onFailure(new HttpException(e.getCause()), e.getMessage());
}
});
}
@Override
@EverythingIsNonNull
public void onResponse(Call call, Response response) {
StmApplication.getInstance().getAppExecutors().mainThread().execute(new Runnable() {
@Override
public void run() {
boolean flag = false;
if (response.isSuccessful()) {
try {
ResponseBody body = response.body();
if (body != null) {
String result = body.string();
Log.i("HttpUtil", result);
callback.onSuccess(new Gson().fromJson(result, TypeToken.get(callback.getType()).getType()));
flag = true;
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (!flag) {
callback.onFailure(new HttpException("返回数据异常"), "返回数据异常");
}
}
});
}
});
}
private String buildUrl(String interfaceName) {
StmApplication sap = StmApplication.getInstance();
StringBuilder sbd = new StringBuilder();
boolean isHttps = PropertyUtil.isUseHttps(sap.getApplicationContext());
if (isHttps) {
sbd.append("https://");
} else {
sbd.append("http://");
}
String address = PropertyUtil.getHttpAddress(sap.getApplicationContext());
sbd.append(address);
String port = PropertyUtil.getHttpPort(sap.getApplicationContext());
if (port != null && !port.equals("")) {
sbd.append(":");
sbd.append(port);
}
sbd.append("/");
sbd.append(interfaceName);
sbd.append(".app");
return sbd.toString();
}
}
package com.stm.asset.http;
import android.util.Log;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
/**
* 类名称:LoggingInterceptor
* 类描述:请求日志拦截
* 创建人:story
* 创建时间:2021-12-10 17:35
*/
public class LoggingInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
Log.i("LoggingInterceptor", String.format("请求地址: %s", response.request().url()));
ResponseBody responseBody = response.body();
if (responseBody != null) {
try {
MediaType mediaType = responseBody.contentType();
byte[] responseBytes = responseBody.bytes();
Log.i("LoggingInterceptor", String.format("请求返回:%s", new String(responseBytes)));
response = response.newBuilder()
.body(ResponseBody.create(mediaType, responseBytes))
.build();
} catch (Exception e) {
e.printStackTrace();
}
}
// if (responseBody != null && responseBody.contentLength() > 0) {
// BufferedSource bufferedSource = responseBody.source();
// bufferedSource.request(Long.MAX_VALUE);
// Buffer buffer = bufferedSource.getBuffer();
// Charset charset = Charset.forName("utf-8");
// MediaType contentType = responseBody.contentType();
// if (contentType != null) {
// try {
// charset = contentType.charset(Charset.forName("utf-8"));
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// if (charset != null) {
// String result = buffer.clone().readString(charset);
// Log.i("LoggingInterceptor", String.format("请求返回:%s", result));
// }
// }
return response;
}
}
package com.stm.asset.http;
import com.stm.asset.base.ConfigKey;
import java.security.MessageDigest;
public class MD5Util implements java.io.Serializable {
/**
* 加密算法
*/
public static String encodeByMd5(String plainText) {
StringBuffer buf = new StringBuffer("");
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(plainText.getBytes());
byte b[] = md.digest();
int i = 0;
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
} catch (Exception e) {
e.printStackTrace();
}
//return buf.toString(); //32位的加密
return buf.toString().substring(8,24); // 16位的加密
}
/**
* 加密算法
*/
public static String encodeByMd5_32(String plainText) {
StringBuffer buf = new StringBuffer("");
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(plainText.getBytes());
byte b[] = md.digest();
int i = 0;
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
} catch (Exception e) {
e.printStackTrace();
}
return buf.toString(); //32位的加密
}
//获取MD5串
public static String getAuthenticator(Long currentTime){
StringBuffer sPwd = new StringBuffer();
sPwd.append(ConfigKey.SIGNATURENAME).append(ConfigKey.SIGNATUREPASSWORD).append(currentTime);
String authenticator = MD5Util.encodeByMd5_32(sPwd.toString()).toUpperCase();
return authenticator;
}
}
package com.stm.asset.http;
import com.stm.asset.json.BaseInfo;
/**
* 类名称:RequestCallback
* 类描述:请求返回封装
* 创建人:story
* 创建时间:2021-12-11 15:55
*/
public abstract class RequestCallback<T extends BaseInfo> {
private Class<T> type;
public abstract void onSuccess(T responseInfo);
public abstract void onFailure(HttpException error, String msg);
public RequestCallback(Class<T> clazz) {
this.type = clazz;
}
public Class<T> getType() {
return type;
}
}
package com.stm.asset.http;
import com.stm.asset.base.StmApplication;
import com.stm.asset.utils.PropertyUtil;
import com.stm.asset.utils.SystemUtil;
import java.util.HashMap;
import java.util.Map;
/**
* 类名称:RequestParams
* 类描述:网络请求参数封装
* 创建人:story
* 创建时间:2021-12-10 17:15
*/
public class RequestParams {
private Map<String, String> headers;
private Map<String, String> bodyParams;
public RequestParams() {
addCommonParams();
}
public Map<String, String> getHeaders() {
return headers;
}
public Map<String, String> getBodyParams() {
return bodyParams;
}
/**
* 添加header
*/
public void addHeader(String name, String value) {
if (this.headers == null) {
this.headers = new HashMap<>();
}
this.headers.put(name, value);
}
/**
* 添加body参数
*/
public void addBodyParameter(String name, String value) {
if (bodyParams == null) {
bodyParams = new HashMap<>();
}
bodyParams.put(name, value);
}
private void addCommonParams(){
if (bodyParams == null) {
bodyParams = new HashMap<>();
}
bodyParams.put("machinecode", "h5");
bodyParams.put("machinetype", "h5");
bodyParams.put("channelcode", "APP");
bodyParams.put("terminalcode", "fee");
bodyParams.put("platform", PropertyUtil.getHttpPlatform(StmApplication.getInstance().getApplicationContext()));
long currentTime = System.currentTimeMillis();
bodyParams.put("currenttime", String.valueOf(currentTime));
bodyParams.put("authenticator", MD5Util.getAuthenticator(currentTime));
if (StmApplication.getInstance().getUserInfo() != null) {
bodyParams.put("accessToken", PropertyUtil.getAccessToken(StmApplication.getInstance().getApplicationContext()));
}
}
}
\ No newline at end of file
package com.stm.asset.http;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class TrustAllSSLSocketFactory {
public static SSLSocketFactory createSSLSocketFactory() {
SSLSocketFactory sslFactory = null;
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[] { new TrustAllManager() }, new SecureRandom());
sslFactory = sslContext.getSocketFactory();
} catch (Exception e) {
e.printStackTrace();
}
return sslFactory;
}
public static HostnameVerifier getHostnameVerifier() {
return new TrustAllHostname();
}
private static class TrustAllHostname implements HostnameVerifier {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
public static class TrustAllManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
}
}
package com.stm.asset.json;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
* 类名称:BaseInfo
* 类描述:请求返回基础类
* 创建人:story
* 创建时间:2021-12-14 14:46
*/
public class BaseInfo implements Serializable {
private static final long serialVersionUID = -5800150937418965637L;
private String msgType; // 响应消息类型 N:正常 E:错误
private String rspCode; // 响应码 000000:正常 其他为错误码
private String rspMsg;
private String rspTime; // 系统时间
// private T rspData; // 响应数据 msgType为N时返回用户信息
private List<Map<String, String>> head;// 处理分页时的数据
private List<Map<String, String>> headList;// 处理分页时的数据
private List<Map<String, String>> warnList;// 警告信息的处理(警告用户风险,若用户继续确认,仍可提交)
public String getMsgType() {
return msgType;
}
public void setMsgType(String msgType) {
this.msgType = msgType;
}
public String getRspCode() {
return rspCode;
}
public void setRspCode(String rspCode) {
this.rspCode = rspCode;
}
public String getRspMsg() {
return rspMsg;
}
public void setRspMsg(String rspMsg) {
this.rspMsg = rspMsg;
}
public String getRspTime() {
return rspTime;
}
public void setRspTime(String rspTime) {
this.rspTime = rspTime;
}
// public T getRspData() {
// return rspData;
// }
//
// public void setRspData(T rspData) {
// this.rspData = rspData;
// }
public List<Map<String, String>> getHead() {
return head;
}
public void setHead(List<Map<String, String>> head) {
this.head = head;
}
public List<Map<String, String>> getHeadList() {
return headList;
}
public void setHeadList(List<Map<String, String>> headList) {
this.headList = headList;
}
public List<Map<String, String>> getWarnList() {
return warnList;
}
public void setWarnList(List<Map<String, String>> warnList) {
this.warnList = warnList;
}
public boolean isSucess() {
if ("000000".equals(this.rspCode)) {
return true;
}
return false;
}
}
package com.stm.asset.json;
import java.util.List;
import java.util.Map;
/**
* 类名称:CommonListMapJson
* 类描述:常用ListMap返回类
* 创建人:story
* 创建时间:2021-12-14 14:51
*/
public class CommonListMapJson extends BaseInfo {
private static final long serialVersionUID = 2677831404656997579L;
private List<Map<String, String>> rspData;
public List<Map<String, String>> getRspData() {
return rspData;
}
public void setRspData(List<Map<String, String>> rspData) {
this.rspData = rspData;
}
}
package com.stm.asset.json;
import java.util.Map;
/**
* 类名称:CommonMapJson
* 类描述:常用Map返回类
* 创建人:story
* 创建时间:2021-12-14 14:50
*/
public class CommonMapJson extends BaseInfo {
private static final long serialVersionUID = 2410670796256546600L;
private Map<String, String> rspData;
public Map<String, String> getRspData() {
return rspData;
}
public void setRspData(Map<String, String> rspData) {
this.rspData = rspData;
}
}
package com.stm.asset.json;
/**
* 类名称:CommonStringJson
* 类描述:常用字符串返回类
* 创建人:story
* 创建时间:2021-12-14 14:50
*/
public class CommonStringJson extends BaseInfo {
private static final long serialVersionUID = 6711484331694503504L;
private String rspData;
public String getRspData() {
return rspData;
}
public void setRspData(String rspData) {
this.rspData = rspData;
}
}
package com.stm.asset.json;
import com.stm.asset.model.LoginInfo;
/**
* 类名称:ListUserInfo
* 类描述:登录返回实体类
* 创建人:story
* 创建时间:2021-12-14 17:28
*/
public class ListUserInfo extends BaseInfo {
private static final long serialVersionUID = -4992321996771893423L;
private LoginInfo rspData;
public void setRspData(LoginInfo rspData) {
this.rspData = rspData;
}
public LoginInfo getRspData() {
return rspData==null?new LoginInfo():rspData;
}
}
package com.stm.asset.keyboard;
public class KeyBoardUtil {
/**
* 判断是否全由数字组成
* @param str
* @return
*/
public static boolean isNumeric(String str) {
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
}
package com.stm.asset.keyboard;
public class KeyModel {
public KeyModel(int code,String lable){
this.code = code;
this.lable = lable;
}
private String lable;
private int code;
public String getLable() {
return lable;
}
public int getCode() {
return code;
}
}
package com.stm.asset.keyboard;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import com.stm.asset.R;
public class SafeKeyboardManager {
private static String preKeyBoardName = "";
public static void initKeyBoard(String preKeyBoardName){
SafeKeyboardManager.preKeyBoardName = preKeyBoardName;
}
public static void registKeyboard(Activity activity, EditText safeEdit){
LinearLayout linearLayout = new LinearLayout(activity);
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.BOTTOM;
activity.addContentView(linearLayout,layoutParams);
@SuppressLint("InflateParams") View view = LayoutInflater.from(activity).inflate(R.layout.layout_keyboard_containor, null);
SafeKeyboard safeKeyboard = new SafeKeyboard(activity, linearLayout, safeEdit,
R.layout.layout_keyboard_containor, view.findViewById(R.id.safeKeyboardLetter).getId(),
SafeKeyboardManager.preKeyBoardName);
safeKeyboard.setDelDrawable(activity.getResources().getDrawable(R.drawable.icon_del2));
safeKeyboard.setLowDrawable(activity.getResources().getDrawable(R.drawable.icon_capital_default3));
safeKeyboard.setUpDrawable(activity.getResources().getDrawable(R.drawable.icon_capital_default2));
}
}
package com.stm.asset.keyboard;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
import android.util.AttributeSet;
import androidx.annotation.Nullable;
import com.stm.asset.R;
import java.lang.reflect.Field;
import java.util.List;
/**
* Created by Administrator on 2018/3/7 0007.
*/
public class SafeKeyboardView extends KeyboardView {
private static final String TAG = "SafeKeyboardView";
private Context mContext;
private boolean isCap;
private Drawable delDrawable;
private Drawable lowDrawable;
private Drawable upDrawable;
/**
* 按键的宽高至少是图标宽高的倍数
*/
private static final int ICON2KEY = 2;
public SafeKeyboardView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
this.mContext = context;
}
public SafeKeyboardView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
this.mContext = context;
}
private void init() {
this.isCap = false;
this.delDrawable = null;
this.lowDrawable = null;
this.upDrawable = null;
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
try {
List<Keyboard.Key> keys = getKeyboard().getKeys();
for (Keyboard.Key key : keys) {
if (key.codes[0] == -5 || key.codes[0] == -2 || key.codes[0] == 100860 || key.codes[0] == -1
|| key.codes[0] == -3)
drawSpecialKey(canvas, key);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void drawSpecialKey(Canvas canvas, Keyboard.Key key) {
if (key.codes[0] == -5) {
drawKeyBackground(R.drawable.keyboard_change, canvas, key);
drawTextAndIcon(canvas, key, delDrawable);
} else if (key.codes[0] == -2 || key.codes[0] == 100860) {
drawKeyBackground(R.drawable.keyboard_change, canvas, key);
drawTextAndIcon(canvas, key, null);
} else if (key.codes[0] == -1) {
if (isCap) {
drawKeyBackground(R.drawable.keyboard_change, canvas, key);
drawTextAndIcon(canvas, key, upDrawable);
} else {
drawKeyBackground(R.drawable.keyboard_change, canvas, key);
drawTextAndIcon(canvas, key, lowDrawable);
}
}else if (key.codes[0] == -3){
drawKeyBackground(R.drawable.keyboard_confirm,canvas,key);
drawTextAndIcon(canvas,key,null);
}
}
private void drawKeyBackground(int id, Canvas canvas, Keyboard.Key key) {
Drawable drawable = mContext.getResources().getDrawable(id);
int[] state = key.getCurrentDrawableState();
if (key.codes[0] != 0) {
drawable.setState(state);
}
drawable.setBounds(key.x, key.y, key.x + key.width, key.y + key.height);
drawable.draw(canvas);
}
private void drawTextAndIcon(Canvas canvas, Keyboard.Key key, @Nullable Drawable drawable) {
try {
Rect bounds = new Rect();
Paint paint = new Paint();
paint.setTextAlign(Paint.Align.CENTER);
paint.setAntiAlias(true);
paint.setColor(Color.BLACK);
if (key.label != null) {
String label = key.label.toString();
Field field;
if (label.length() > 1 && key.codes.length < 2) {
int labelTextSize = 0;
try {
field = KeyboardView.class.getDeclaredField(getContext().getString(R.string.mLabelTextSize));
field.setAccessible(true);
labelTextSize = (Integer) field.get(this);
} catch (NoSuchFieldException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e2) {
e2.printStackTrace();
}
paint.setTextSize(labelTextSize);
paint.setTypeface(Typeface.DEFAULT_BOLD);
if (key.label.equals("确认")){
paint.setColor(Color.WHITE);
}
} else {
int keyTextSize = 0;
try {
field = KeyboardView.class.getDeclaredField(getContext().getString(R.string.mLabelTextSize));
field.setAccessible(true);
keyTextSize = (Integer) field.get(this);
} catch (NoSuchFieldException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e2) {
e2.printStackTrace();
}
paint.setTextSize(keyTextSize);
paint.setTypeface(Typeface.DEFAULT);
}
paint.getTextBounds(key.label.toString(), 0, key.label.toString().length(), bounds);
canvas.drawText(key.label.toString(), key.x + (key.width / 2),
(key.y + key.height / 2) + bounds.height() / 2, paint);
}
if (drawable == null) return;
// 约定: 最终图标的宽度和高度都需要在按键的宽度和高度的二分之一以内
// 如果: 图标的实际宽度和高度都在按键的宽度和高度的二分之一以内, 那就不需要变换, 否则就需要等比例缩小
int iconSizeWidth, iconSizeHeight;
key.icon = drawable;
int iconH = px2dip(mContext, key.icon.getIntrinsicHeight());
int iconW = px2dip(mContext, key.icon.getIntrinsicWidth());
if (key.width >= (ICON2KEY * iconW) && key.height >= (ICON2KEY * iconH)) {
//图标的实际宽度和高度都在按键的宽度和高度的二分之一以内, 不需要缩放, 因为图片已经够小或者按键够大
setIconSize(canvas, key, iconW, iconH);
} else {
//图标的实际宽度和高度至少有一个不在按键的宽度或高度的二分之一以内, 需要等比例缩放, 因为此时图标的宽或者高已经超过按键的二分之一
//需要把超过的那个值设置为按键的二分之一, 另一个等比例缩放
//不管图标大小是多少, 都以宽度width为标准, 把图标的宽度缩放到和按键一样大, 并同比例缩放高度
double multi = 1.0 * iconW / key.width;
int tempIconH = (int) (iconH / multi);
if (tempIconH <= key.height) {
//宽度相等时, 图标的高度小于等于按键的高度, 按照现在的宽度和高度设置图标的最终宽度和高度
iconSizeHeight = tempIconH / ICON2KEY;
iconSizeWidth = key.width / ICON2KEY;
} else {
//宽度相等时, 图标的高度大于按键的高度, 这时按键放不下图标, 需要重新按照高度缩放
double mul = 1.0 * iconH / key.height;
int tempIconW = (int) (iconW / mul);
iconSizeHeight = key.height / ICON2KEY;
iconSizeWidth = tempIconW / ICON2KEY;
}
setIconSize(canvas, key, iconSizeWidth, iconSizeHeight);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void setIconSize(Canvas canvas, Keyboard.Key key, int iconSizeWidth, int iconSizeHeight) {
int left = key.x + (key.width - iconSizeWidth) / 2;
int top = key.y + (key.height - iconSizeHeight) / 2;
int right = key.x + (key.width + iconSizeWidth) / 2;
int bottom = key.y + (key.height + iconSizeHeight) / 2;
key.icon.setBounds(left, top, right, bottom);
key.icon.draw(canvas);
key.icon = null;
}
public void setCap(boolean cap) {
isCap = cap;
}
public void setDelDrawable(Drawable delDrawable) {
this.delDrawable = delDrawable;
}
public void setLowDrawable(Drawable lowDrawable) {
this.lowDrawable = lowDrawable;
}
public void setUpDrawable(Drawable upDrawable) {
this.upDrawable = upDrawable;
}
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
}
package com.stm.asset.model;
import java.io.Serializable;
/**
* 类名称:AddressInfo
* 类描述:请求地址详情
* 创建人:story
* 创建时间:2022-01-06 10:04
*/
public class AddressInfo implements Serializable {
private static final long serialVersionUID = 1801015901518969341L;
private String name;
private String ip;
private String port;
private boolean isHttps;
private String platform;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public boolean isHttps() {
return isHttps;
}
public void setHttps(boolean https) {
isHttps = https;
}
public String getPlatform() {
return platform;
}
public void setPlatform(String platform) {
this.platform = platform;
}
}
package com.stm.asset.model;
import java.io.Serializable;
/**
* 类名称:CheckTaskInfo
* 类描述:盘点任务实体类
* 创建人:story
* 创建时间:2021-12-07 15:11
*/
public class CheckTaskInfo implements Serializable {
private static final long serialVersionUID = 1644638878669069343L;
private String taskId;
private String taskName; // 任务名称
private String creater; // 创建人
private String createTime; // 创建时间
private String taskNum; // 盘点总数
private String taskArea; // 盘点区域
private String taskStatus; // 盘点状态
private String taskStatusName; // 状态说明
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public String getCreater() {
return creater;
}
public void setCreater(String creater) {
this.creater = creater;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getTaskNum() {
return taskNum;
}
public void setTaskNum(String taskNum) {
this.taskNum = taskNum;
}
public String getTaskArea() {
return taskArea;
}
public void setTaskArea(String taskArea) {
this.taskArea = taskArea;
}
public String getTaskStatus() {
return taskStatus;
}
public void setTaskStatus(String taskStatus) {
this.taskStatus = taskStatus;
}
public String getTaskStatusName() {
return taskStatusName;
}
public void setTaskStatusName(String taskStatusName) {
this.taskStatusName = taskStatusName;
}
}
package com.stm.asset.model;
import java.io.Serializable;
/**
* 类名称:CorpInfo
* 类描述:企业实体类
* 创建人:story
* 创建时间:2021-12-14 17:24
*/
public class CorpInfo implements Serializable {
private static final long serialVersionUID = -119966012740920874L;
private String id; //公司ID
private String name; //公司名字
private boolean isSelect; //是否选择 true选择
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSelect() {
return isSelect;
}
public void setSelect(boolean select) {
isSelect = select;
}
}
package com.stm.asset.model;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.PrimaryKey;
import java.io.Serializable;
/**
* 类名称:InventoryInfo
* 类描述:盘询数据实体类
* 创建人:story
* 创建时间:2021-12-09 16:24
*/
@Entity(tableName = "inventoryInfo")
public class InventoryInfo implements Serializable {
private static final long serialVersionUID = 1060118962039231156L;
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
private long id;
@ColumnInfo(name = "name")
private String name; // 资产名称
@ColumnInfo(name = "number")
private String number; // 资产编码
@ColumnInfo(name = "userName")
private String userName; // 使用人
@ColumnInfo(name = "userDept")
private String userDept; // 使用部门
@ColumnInfo(name = "status")
private String status; // 状态:0,未提交;1,提交失败;2,提交成功
@ColumnInfo(name = "item01")
private String item01;
@ColumnInfo(name = "item02")
private String item02;
@ColumnInfo(name = "item03")
private String item03;
@ColumnInfo(name = "item04")
private String item04;
@ColumnInfo(name = "item05")
private String item05;
@ColumnInfo(name = "item06")
private String item06;
@ColumnInfo(name = "item07")
private String item07;
@ColumnInfo(name = "item08")
private String item08;
@ColumnInfo(name = "item09")
private String item09;
@ColumnInfo(name = "item10")
private String item10;
public InventoryInfo(){}
@Ignore
public InventoryInfo(String name, String number, String userName, String userDept, String item01, String item02){
this.name = name;
this.number = number;
this.userName = userName;
this.userDept = userDept;
this.item01 = item01;
this.item02 = item02;
this.status = "0";
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserDept() {
return userDept;
}
public void setUserDept(String userDept) {
this.userDept = userDept;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getItem01() {
return item01;
}
public void setItem01(String item01) {
this.item01 = item01;
}
public String getItem02() {
return item02;
}
public void setItem02(String item02) {
this.item02 = item02;
}
public String getItem03() {
return item03;
}
public void setItem03(String item03) {
this.item03 = item03;
}
public String getItem04() {
return item04;
}
public void setItem04(String item04) {
this.item04 = item04;
}
public String getItem05() {
return item05;
}
public void setItem05(String item05) {
this.item05 = item05;
}
public String getItem06() {
return item06;
}
public void setItem06(String item06) {
this.item06 = item06;
}
public String getItem07() {
return item07;
}
public void setItem07(String item07) {
this.item07 = item07;
}
public String getItem08() {
return item08;
}
public void setItem08(String item08) {
this.item08 = item08;
}
public String getItem09() {
return item09;
}
public void setItem09(String item09) {
this.item09 = item09;
}
public String getItem10() {
return item10;
}
public void setItem10(String item10) {
this.item10 = item10;
}
}
package com.stm.asset.model;
import java.io.Serializable;
import java.util.List;
/**
* 类名称:LoginInfo
* 类描述:登录返回数据
* 创建人:story
* 创建时间:2021-12-14 17:26
*/
public class LoginInfo implements Serializable {
private static final long serialVersionUID = -5421078409061430086L;
private UserInfo userInfo; //单公司登录返回的信息
private List<CorpInfo> corpInfo; //多公司第一次登录返回的信息
public UserInfo getUserInfo() {
return userInfo;
}
public void setUserInfo(UserInfo userInfo) {
this.userInfo = userInfo;
}
public List<CorpInfo> getCorpInfo() {
return corpInfo;
}
public void setCorpInfo(List<CorpInfo> corpInfo) {
this.corpInfo = corpInfo;
}
}
package com.stm.asset.page;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import com.stm.asset.R;
import com.stm.asset.base.BaseFragmentActivity;
import com.stm.asset.base.FragPageAdapter;
import com.stm.asset.view.LoadingDialog;
import java.util.ArrayList;
import java.util.List;
/**
* 类名称:CheckTaskActivity
* 类描述:盘点任务页面
* 创建人:story
* 创建时间:2021-12-07 13:54
*/
public class CheckTaskActivity extends BaseFragmentActivity implements View.OnClickListener {
private TextView unfinishedTxt, finishedTxt;
private ViewPager selectVPager;
private FragPageAdapter fragPageAdapter;
private List<Fragment> fragmentList;
private TaskFragment unfinishedTaskFgm;
private TaskFragment finishedTaskFgm;
private LoadingDialog loadingDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_task);
initView();
}
private void initView() {
initTitle();
titleTxt.setText("盘点任务");
findViewById(R.id.common_title_back_layout).setOnClickListener(this);
unfinishedTxt = findViewById(R.id.task_unfinished_txt);
finishedTxt = findViewById(R.id.task_finished_txt);
unfinishedTxt.setText("未盘点任务(0)");
finishedTxt.setText("已完成任务");
unfinishedTxt.setSelected(true);
finishedTxt.setSelected(false);
unfinishedTxt.setOnClickListener(this);
finishedTxt.setOnClickListener(this);
selectVPager = findViewById(R.id.task_content);
fragmentList = new ArrayList<>();
unfinishedTaskFgm = TaskFragment.instance(this,"A");
fragmentList.add(unfinishedTaskFgm);
fragPageAdapter = new FragPageAdapter(getSupportFragmentManager(), fragmentList);
selectVPager.setAdapter(fragPageAdapter);
loadingDialog = new LoadingDialog(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.common_title_back_layout:
finish();
break;
case R.id.task_unfinished_txt:
if (!unfinishedTxt.isSelected()) {
unfinishedTxt.setSelected(true);
finishedTxt.setSelected(false);
selectVPager.setCurrentItem(0);
}
break;
case R.id.task_finished_txt:
if (!finishedTxt.isSelected()) {
if (finishedTaskFgm == null) {
finishedTaskFgm = TaskFragment.instance(this,"B");
fragmentList.add(finishedTaskFgm);
fragPageAdapter.notifyDataSetChanged();
}
unfinishedTxt.setSelected(false);
finishedTxt.setSelected(true);
selectVPager.setCurrentItem(1);
}
break;
}
}
public void setUnfinishedNum(int num) {
String str = "未盘点任务(" + num + ")";
unfinishedTxt.setText(str);
}
public void setFinishedNum(int num) {
String str = "已完成任务";
finishedTxt.setText(str);
}
public LoadingDialog getLoadingDialog() {
return loadingDialog;
}
public void refreshData() {
if (unfinishedTaskFgm != null) {
unfinishedTaskFgm.loadData();
}
if (finishedTaskFgm != null) {
finishedTaskFgm.loadData();
}
}
}
package com.stm.asset.page;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import androidx.annotation.Nullable;
import com.fn.useries.operation.U8Series;
import com.fn.useries.reader.ERROR;
import com.fn.useries.utils.MusicPlayer;
import com.stm.asset.R;
import com.stm.asset.base.BaseActivity;
import com.stm.asset.base.StmApplication;
import com.stm.asset.utils.ViewUtil;
import com.stm.asset.view.TextMoveLayout;
/**
* 类名称:DeviceSetActivity
* 类描述:设备参数设置
* 创建人:story
* 创建时间:2021-12-15 11:10
*/
public class DeviceSetActivity extends BaseActivity implements View.OnClickListener {
private static final String MODEL = "U8";
private TextMoveLayout powerLayout;
private SeekBar powerSb;
private TextView moveTextDBM;
private ViewGroup.LayoutParams layoutParams;
private EditText temperatureEt;
private Spinner sessionSpinner;
private Spinner flagSpinner;
private U8Series mUSeries;
private int screenWidth;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_set);
initView();
}
private void initView() {
initTitle();
screenWidth = ViewUtil.getScreenWidth(this);
moveTextDBM = new TextView(this);
moveTextDBM.setBackgroundColor(Color.rgb(245, 245, 245));
moveTextDBM.setTextColor(Color.rgb(0, 161, 229));
moveTextDBM.setTextSize(26);
moveTextDBM.layout(0, 5, screenWidth, 80);
titleTxt.setText("设备参数");
findViewById(R.id.common_title_back_layout).setOnClickListener(this);
powerLayout = findViewById(R.id.set_power_layout);
powerSb = findViewById(R.id.set_power_sb);
powerSb.setOnSeekBarChangeListener(new OnSeekBarChangeListenerImp());
powerSb.setMax(33);
layoutParams = new ViewGroup.LayoutParams(screenWidth, 40);
temperatureEt = findViewById(R.id.set_temperature_et);
findViewById(R.id.set_temperature_read_btn).setOnClickListener(this);
sessionSpinner = findViewById(R.id.set_inventory_session_spinner);
flagSpinner = findViewById(R.id.set_inventory_flag_spinner);
findViewById(R.id.inventory_save_btn).setOnClickListener(this);
mUSeries = U8Series.getInstance();
}
@Override
protected void onResume() {
super.onResume();
mUSeries.modulePowerOn(MODEL);
powerLayout.removeAllViews();
powerLayout.addView(moveTextDBM, layoutParams);
if (mUSeries != null) {
getPower();
getInventoryParams();
}
}
@Override
protected void onPause() {
super.onPause();
mUSeries.modulePowerOff(MODEL);
}
private void getPower() {
try {
Thread.sleep(800);
String outPowerSetParams = mUSeries.getParams(U8Series.PARA_POWER);
Log.i("DeviceSetActivity", "M10_U8:getPower " + outPowerSetParams);
if (outPowerSetParams.trim().equalsIgnoreCase(ERROR.RECEVICE_INCOMPLETE)) {
MusicPlayer.getInstance().play(MusicPlayer.Type.MUSIC_ERROR);
StmApplication.getInstance().showToastShort(getResources().getString(R.string.device_set_get_power_fail) + " " + outPowerSetParams);
return;
}
refreshPowerView(outPowerSetParams);
// 显示软件提示音
} catch (Exception e) {
Log.i("DeviceSetActivity", "M10_U8:getPowerParamsException " + e.toString());
}
}
private void getInventoryParams() {
String[] mItems = { "s0", "s1", "s2", "s3" };
String[] mItemsFlag = { "A", "B" };
ArrayAdapter<String> simpleAdapter = new ArrayAdapter<>(this, R.layout.view_simple_spinner_item, mItems);
sessionSpinner.setAdapter(simpleAdapter);
String sessionParams = mUSeries.getParams(U8Series.SESSIONSTATE);
if (sessionParams != null && !"".equals(sessionParams)) {
sessionSpinner.setSelection(Integer.parseInt(sessionParams));
}
simpleAdapter = new ArrayAdapter<>(this, R.layout.view_simple_spinner_item, mItemsFlag);
flagSpinner.setAdapter(simpleAdapter);
String flagParams = mUSeries.getParams(U8Series.FLAGSTATE);
if (flagParams != null && !"".equals(flagParams)) {
flagSpinner.setSelection(Integer.parseInt(flagParams));
}
}
private void refreshPowerView(String powerValue) {
String str = powerValue + "dBm";
moveTextDBM.setText(str);
powerSb.setProgress(Integer.parseInt(powerValue));
}
private void getTemperature() {
temperatureEt.setText("");
try {
String strTemperature = mUSeries.getParams(U8Series.TEMPERATURE);
if (strTemperature.trim().equalsIgnoreCase(ERROR.RECEVICE_INCOMPLETE)) {// 接收异常
MusicPlayer.getInstance().play(MusicPlayer.Type.MUSIC_ERROR);
StmApplication.getInstance().showToastShort(ERROR.RECEVICE_INCOMPLETE);
return;
}
MusicPlayer.getInstance().play(MusicPlayer.Type.OK);
temperatureEt.setText(strTemperature);
} catch (Exception e) {
MusicPlayer.getInstance().play(MusicPlayer.Type.MUSIC_ERROR);
Log.i("DeviceSetActivity", "M10_U8:getTemperatureParamsException" + e.toString());
e.printStackTrace();
}
}
private boolean setSessionAndFlag() {
int sessionIndex = sessionSpinner.getSelectedItemPosition();
int flagIndex = flagSpinner.getSelectedItemPosition();
boolean setSessionStateResult = mUSeries.setParams(U8Series.SESSIONSTATE, Byte.toString((byte) sessionIndex));
boolean setFlagStateResult = mUSeries.setParams(U8Series.FLAGSTATE, Byte.toString((byte) flagIndex));
return (setSessionStateResult && setFlagStateResult);
}
private boolean setPower() {
byte btOutputPower;
try {
String powerStr = moveTextDBM.getText().toString();
btOutputPower = (byte) Integer.parseInt(powerStr.subSequence(0, powerStr.indexOf("dBm")).toString());
} catch (Exception e) {
return false;
}
try {
return mUSeries.setParams(U8Series.PARA_POWER, Byte.toString(btOutputPower));
} catch (Exception e) {
Log.i("DeviceSetActivity", "M10_U8:setPowerParamsException" + e.toString());
return false;
}
}
private void saveSet() {
if (setSessionAndFlag() && setPower()) {
MusicPlayer.getInstance().play(MusicPlayer.Type.OK);
StmApplication.getInstance().showToastShort("设置成功");
return;
}
StmApplication.getInstance().showToastShort("设置失败");
MusicPlayer.getInstance().play(MusicPlayer.Type.MUSIC_ERROR);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.common_title_back_layout:
finish();
break;
case R.id.set_temperature_read_btn:
getTemperature();
break;
case R.id.inventory_save_btn:
saveSet();
break;
}
}
private class OnSeekBarChangeListenerImp implements SeekBar.OnSeekBarChangeListener {
// 触发操作,拖动
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
float value = ((float) screenWidth / (float) 35) * (float) 0.8;
int moveStep = Math.round(value);
moveTextDBM.setWidth(80);
moveTextDBM.layout((progress * moveStep), 5, screenWidth, 80);
String str = progress + "dBm";
moveTextDBM.setText(str);
}
// 表示进度条刚开始拖动,开始拖动时候触发的操作
public void onStartTrackingTouch(SeekBar seekBar) {
}
// 停止拖动时候
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
}
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment