日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

安卓串口中InputStream数据接收不完整

發布時間:2023/11/27 生活经验 51 豆豆
生活随笔 收集整理的這篇文章主要介紹了 安卓串口中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数据接收不完整的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。