Android 串口开发(一) 串口读写操作

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)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值