【发布时间】:2018-05-18 11:35:16
【问题描述】:
我的问题是从 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();
}
【问题讨论】:
-
我正在使用 2 个全局变量。在这个方法中 byte[] buffer = new byte[256]; // 流的缓冲存储 int bytes; // read() 返回的字节数
标签: java android multithreading android-service inputstream