![](/img/trans.png)
[英]Issue with Bluetooth through transferring data between Android and Arduino
[英]Bluetooth data loss between Android and Arduino
直截了當-我的應用程序由於某種神秘的原因而在接收InputStream時失去了部分數據(字符串)。 我在這里談論藍牙連接。 大多數時候,我會收到正確的字符串,但有時會縮短它。 這里最奇怪的是,我正在將每個InputStream打印到ScrollView中,並且可以說出整個字符串都在里面...不過,這里是代碼:
@Override
public void run() {
InputStream inputStream;
try {
inputStream = mBTSocket.getInputStream();
while (!bStop) {
byte[] buffer = new byte[256];
int bytes;
if (inputStream.available() > 0) {
bytes = inputStream.read(buffer);
final String strInput = new String(buffer, 0, bytes);;
mTxtReceive.post(new Runnable() {
@Override
public void run() {
mTxtReceive.append(strInput);
int txtLength = mTxtReceive.getEditableText().length();
if (txtLength > mMaxChars) {
mTxtReceive.getEditableText().delete(0, txtLength - mMaxChars);
}
scrollView.post(new Runnable() {
@Override
public void run() {
scrollView.fullScroll(View.FOCUS_DOWN);
}
});
}
});
runOnUiThread(new Runnable() {
@Override
public void run() {
weather = strInput.split(",");
mTxtHumidity.setText(weather[0]);
mTxtTemperatureDHT.setText(weather[1]);
mTxtPressure.setText(weather[2]);
mTxtLux.setText(weather[3]);
mTxtRainMM.setText(weather[4]);
mTxtRainDaily.setText(weather[5]);
mTxtWSKPH.setText(weather[6]);
mTxtWGKPH.setText(weather[7]);
mTxtWSAVG2.setText(weather[8]);
mTxtWGAVG10.setText(weather[9]);
}
});
}
Thread.sleep(500);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
這里的問題是數組weather
為空異常,因為根據我的應用程序,我有時會越界訪問項目(一旦出錯,大多數時候weather
長度為6/7/8)。 應用程序在10%的時間內崩潰。
背后有什么原因嗎?
編輯:有時接收InputStream而不是接收56個字節,我分別得到33和22
在此處找到答案: Android InputStream刪除前兩個字節(修改后的BluetoothChat)
新增中
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
由於sleep
方法,僅解決了Android與Arduino之間非動態數據交換的問題。 事實證明,即使sleep(50)
在這種情況下也可以工作。 由於某種原因,此短暫的sleep
緩沖區永遠不會被分割或丟失。 如果編碼不正確,請在投票之前解釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.