安卓串口中InputStream数据接收不完整
生活随笔
收集整理的這篇文章主要介紹了
安卓串口中InputStream数据接收不完整
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
串口讀數組本身就很可能需要讀幾次才能讀完,建議是寫一個拼接數據的方法,每次記錄讀取的數據和數據的長度
?
一開始的寫法如下 會出現串口讀取斷開情況
protected class LReadThread extends Thread {@Overridepublic 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 {@Overridepublic 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 {@Overridepublic 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
總結
以上是生活随笔為你收集整理的安卓串口中InputStream数据接收不完整的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 炒股多少钱啊?
- 下一篇: 锅开头的成语有哪些?