LogUtil.e(TAG, “串口关闭失败”);
return false;
}
boolean isClose = false;
LogUtil.e(TAG, “关闭串口”);
try {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
if (serialPort != null) {
serialPort.close();
}
isClose = true;
isFlagSerial = false;//关闭串口时,连接状态标记为false
} catch (IOException e) {
e.printStackTrace();
isClose = false;
}
return isClose;
}
/**
- 发送16进制,串口指令
*/
public void sendHexString(String data) {
if (!isFlagSerial) {
LogUtil.e(TAG, “串口未打开,发送失败” + data);
return;
}
try {
outputStream.write(ByteUtil.hex2byte(data));
outputStream.flush();
LogUtil.e(TAG, “sendSerialData:” + data);
} catch (IOException e) {
e.printStackTrace();
LogUtil.e(TAG, “发送指令出现异常”);
}
}
/**
- 发送ASCII,串口指令
*/
public void sendAsciiString(String data) {
if (!isFlagSerial) {
LogUtil.e(TAG, “串口未打开,发送失败” + data);
return;
}
try {
outputStream.write(data.getBytes(“gbk”));
outputStream.flush();
LogUtil.e(TAG, “sendSerialData:” + data);
} catch (IOException e) {
e.printStackTrace();
LogUtil.e(TAG, “发送指令出现异常”);
}
}
/**
- 接收串口数据的方法
*/
public void receive() {
if (receiveThread != null && !isFlagSerial) {
return;
}
receiveThread = new Thread() {
@Override
public void run() {
while (isFlagSerial) {
try {
byte[] readData = new byte[256];
if (inputStream == null) {
return;
}
int size = inputStream.read(readData);
if (size > 0 && isFlagSerial) {
// strData = ByteUtil.byteToStr(readData, size);
if (onDataReceiveListener != null) {
onDataReceiveListener.onSerialPortData(readData, size);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
receiveThread.start();
}
private SerialCallBack onDataReceiveListener;
publi