我正在开发一个通过蓝牙与微控制器通信的应用程序。我正在发送一个由字节数组成的数据包,该数据包已成功接收。但是,我没有收到微控制器发送的字节数组。没有错误出现。接收代码如下:
private void beginListenForData() {
// TODO Auto-generated method stub
Log.e("clientsocket", "listening data");
final Handler handler = new Handler();
final byte delimiter = 10; // This is the ASCII code for a newline
// character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted() && !stopWorker) {
try {
int bytesAvailable = mmInputStream.available();
if (bytesAvailable > 0) {
Log.e("bytes", "" + bytesAvailable);
Log.e("bytes", "" + bytesAvailable);
byte[] packetBytes = new byte[bytesAvailable];
Log.v("packet Bytes", "" + packetBytes);
for (int m = 0; m < packetBytes.length; m++)
Log.e("checking array", "" + packetBytes[m]);
Log.v("packet bytes len", "" + packetBytes.length);
mmInputStream.readFully(packetBytes, 0,
packetBytes.length);
for (int i = 0; i < bytesAvailable; i++) {
byte b = packetBytes[i];
if (b == delimiter) {
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0,
encodedBytes, 0,
encodedBytes.length);
for (int k = 0; k < encodedBytes.length; k++)
Log.v("encoded bytes", ""
+ encodedBytes[k]);
int[] iarray = new int[encodedBytes.length - 1];
int k = 0;
for (int j = 0; j < encodedBytes.length - 1; j++)
iarray[k++] = encodedBytes[j] & 0xff;
StringBuilder sb = new StringBuilder(
iarray.length);
for (int l : iarray)
sb.append(l);
for (k = 0; k < iarray.length; k++)
Log.v("iarray", "" + iarray[k]);
final String data = sb.toString();
// final String data = new String(
// encodedBytes, "UTF-8");
Log.e("data server", data);
readBufferPosition = 0;
Log.e("clientserver", "" + data);
handler.post(new Runnable() {
public void run() {
myLabel.append("\n" + data);
System.gc();
Log.e("clientserver", "" + data);
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
} catch (IOException ex) {
stopWorker = true;
myLabel.append("\n" + "Try Again!");
}
}
}
});
workerThread.start();
}
最初,当微控制器以字符串形式发送数据时,我正在成功读取它。但是当它打开到字节数组时,问题就开始了。有人可以帮我这个吗? 谢谢:))
答案 0 :(得分:0)
解决了问题!这是因为分隔符在两端都不匹配。感谢你的关心。 :)