我的问题是从android应用程序接收数据我从Arduino发送数据,就像这样{166;122;33;5;n} 当我用 Android 打开套接字时,它只接收前 9 或 10 个字节,并向我显示 166;122;33 等数据。 想知道如何在InputStream中接收所有内容。 负责此操作的函数是 beginListenForData() 。
<小时/> void beginListenForData() {
final Handler handler = new Handler();
stopThread = false;
Thread thread = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted() && !stopThread) {
try {
final int byteCount = inputStream.available();
if (byteCount > 0) {
byte[] rawBytes = new byte[byteCount];
inputStream.read(rawBytes);
final String str = new String(rawBytes);
handler.post(new Runnable() {
public void run() {
if (str.charAt(0) == '{') {
try {
bytes = inputStream.read(buffer, 0,
buffer.length);
String readMessage1 = new String(buffer,
0, bytes, "US-ASCII");
Log.e("bytes ",
Integer.toString(bytes));
Log.e("tag:", readMessage1);
sendMessage(readMessage1);
} catch (IOException e) {
e.printStackTrace();
Log.e("tag", "failed");
}
}
}
});
}
} catch (IOException ex) {
sendMessage("F");
stopThread = true;
}
}
}
});
thread.start();
}
最佳答案
> Try something like:
void beginListenForData() {
final Handler handler = new Handler();
stopThread = false;
Thread thread = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted() && !stopThread) {
try {
byte[] buffer = new byte[1];
bytes = mmInStream.read(buffer, 0, 1);
String read = new String(buffer, 0, 1);
readMessage.append(read);
if (buffer[0] == '}') {
bytes = mmInStream.read(buffer, 0, 1);
readMessage.append(read);
String readMessage1 = new String(buffer,
0, bytes, "US-ASCII");
Log.e("bytes ",
Integer.toString(bytes));
sendMessage(readMessage);
} catch (IOException e) {
e.printStackTrace();
Log.e("tag", "failed");
}
}
});
}
} catch (IOException ex) {
sendMessage("F");
stopThread = true;
}
}
}
});
thread.start();
}
关于java - Android InputStream 无法接收来自蓝牙 HC-05 的完整消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50410463/