安卓串口中InputStream数据接收不完整
16lz
2021-01-26
串口读数组本身就很可能需要读几次才能读完,建议是写一个拼接数据的方法,每次记录读取的数据和数据的长度
一开始的写法如下 会出现串口读取断开情况
protected class LReadThread extends Thread { @Override public void run() { super.run(); while (!interrupted()) { int size; try { //处理读取 byte[] buffer = new byte[64]; if (lInputStream == null) return; size = lInputStream.read(buffer); if (size > 0) { onDataReceived(buffer, size, 0); } } catch (IOException e) { e.printStackTrace(); } } } }
然后百度之后写法如下 不过这个写法要求你的卡号是\n结尾的
protected class LReadThread extends Thread { @Override public void run() { super.run(); while (!interrupted()) { int bytes; int ch;//读取字符串变量 try { if (lInputStream == null) return; //处理读取 byte[] buffer = new byte[64]; bytes=0; while ((ch = lInputStream.read()) != '\n'){ if (ch != -1) { buffer[bytes] = (byte) ch; bytes++; } } buffer[bytes] = '\n'; bytes++; if (bytes > 0) { onDataReceived(buffer, bytes, 0); } } catch (IOException e) { e.printStackTrace(); } } } }
上面的有限制,所以呢大部分的可以是使用下面的代码处理 ,flag 是自己添加的区分那一个线程,
还有就是byte 大于8的问题,这个看自己要读取卡号的大小自己添加判断就行
private class MReadThread extends Thread { @Override public void run() { super.run(); while (!isInterrupted()) { try { if (mInputStream == null) return; byte[] buffer = new byte[64]; int mcount; if (mInputStream.available() <= 0) { continue; } else { Thread.sleep(300); } mcount = mInputStream.read(buffer); if (mcount > 8) { onDataReceived(buffer, mcount, 1); } } catch (IOException e) { e.printStackTrace(); return; } catch (InterruptedException e) { e.printStackTrace(); return; } } } }
参考链接 非常感谢
https://blog.csdn.net/clliu_hust/article/details/80874272
https://blog.csdn.net/lilidejing/article/details/37913627
更多相关文章
- Android开发 华为手机读取相册闪退问题
- AndroidManifest.xml:117: error: ERROR getting 'android:name'
- android中判断sim卡状态和读取联系人资料的方法
- Bundle的说明和用法
- Android(安卓)中自定义控件和属性
- android MakeFile写法
- android输入设备相关文件
- 从assets文件夹中读取txt文件
- 从assets文件夹中读取文件