我从 BT 串行连接接收到的数据应该是:
0
1
2
3
.
.
.
27
28
29
0
1
2
3
.
.
.
etc
但我实际上得到的是一些数据被切掉了。像这样:
11
12
1
3
14
15
1
6
1
7
18
19
2
0
在 BTSerialService.java
/** * 此线程在与远程设备连接期间运行。*它处理所有传入和传出的传输。*/
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "create ConnectedThread");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
//final byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
//Send the obtained bytes to the UI Activity
mHandler.obtainMessage(FinalSetting.MESSAGE_READ, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}
然后在 FinalSetting.java 案例消息中读取:
case MESSAGE_READ:
int i;
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
Log.i(LOG_TAG, readMessage);
mTextView.setText(readMessage);
String [] numbers = readMessage.split("\n");
int [] intNumber = new int[numbers.length];
for (String number : numbers) {
if(number.trim().length()>0){
try{
for (i=0;i<numbers.length;i++){
intNumber[i] = Integer.valueOf(number.trim());
if (intNumber[i]<0 || intNumber[i]>95){
//some action
}
}
} catch (NumberFormatException e){
Log.i(LOG_TAG, "Unable to parse integer" + e);
}
}
}
break;
LogCat 显示的内容:
05-06 17:28:07.079: I/HBAS(15090): 10
05-06 17:28:07.079: I/HBAS(15090): 11
05-06 17:28:07.079: I/HBAS(15090): 12
05-06 17:28:07.969: I/HBAS(15090): 1
05-06 17:28:08.029: I/HBAS(15090): 3
05-06 17:28:09.019: I/HBAS(15090): 14
05-06 17:28:09.979: I/HBAS(15090): 1
05-06 17:28:10.029: I/HBAS(15090): 5
05-06 17:28:10.989: I/HBAS(15090): 16
05-06 17:28:12.009: I/HBAS(15090): 17
05-06 17:28:12.999: I/HBAS(15090): 18
05-06 17:28:13.999: I/HBAS(15090): 19
05-06 17:28:14.999: I/HBAS(15090): 20
05-06 17:28:16.009: I/HBAS(15090): 21
那么有谁知道如何解决这个问题???提前致谢..