jniLibs下面放的就是so库。
注意:因为用的谷歌原生so库,所以SerialPort类的包名一定要是android_serialport_api,如果想修改这个包名,就需要重新生成对应的so库
public class SerialPortUtil {
public static String TAG = “SerialPortUtil”;
/**
- 标记当前串口状态(true:打开,false:关闭)
**/
public static boolean isFlagSerial = false;
public static SerialPort serialPort = null;
public static InputStream inputStream = null;
public static OutputStream outputStream = null;
public static Thread receiveThread = null;
public static String strData = “”;
public static Handler mHandler;
/**
- 打开串口
*/
public static boolean open() {
boolean isopen = false;
if(isFlagSerial){
LogUtils.e(TAG,“串口已经打开,打开失败”);
return false;
}
try {
serialPort = new SerialPort(new File(“/dev/ttyS3”), 115200, 0);
inputStream = serialPort.getInputStream();
outputStream = serialPort.getOutputStream();
receive();
isopen = true;
isFlagSerial = true;
} catch (IOException e) {
e.printStackTrace();
isopen = false;
}
return isopen;
}
/**
- 关闭串口
*/
public static boolean close() {
if(isFlagSerial){
LogUtils.e(TAG,“串口关闭失败”);
return false;
}
boolean isClose = false;
LogUtils.e(TAG, “关闭串口”);
try {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
isClose = true;
isFlagSerial = false;//关闭串口时,连接状态标记为false
} catch (IOException e) {
e.printStackTrace();
isClose = false;
}
return isClose;
}
/**
- 发送串口指令
*/
public static void sendString(String data, Handler handler) {
mHandler = handler;
if (!isFlagSerial) {
LogUtils.e(TAG, “串口未打开,发送失败” + data);
return;
}
try {
outputStream.write(ByteUtil.hex2byte(data));
outputStream.flush();
LogUtils.e(TAG, “sendSerialData:” + data);
} catch (IOException e)