我想从设备读取后写(通过蓝牙插座) 问题是当套接字关闭时while(true)完成,所以我不能再写了。
这是代码:
try {
// This will block until it succeeds in connecting to the device
// through the bluetoothSocket or throws an exception
bluetoothSocket.connect();
try {
connectingThread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
outstream = bluetoothSocket.getOutputStream();
outstream.write("P".getBytes());
instream = bluetoothSocket.getInputStream();
byte[] buffer = new byte[128]; // buffer store for the stream
int bytes; // bytes returned from read()
String readMessage = "";
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = instream.read(buffer);
if(bytes!= -1){
// Send the obtained bytes to the UI activity
readMessage = new String(buffer, 0, bytes);
arrayList.add(readMessage);
biodyMsg = TextUtils.join("", arrayList);
}
} catch (Exception e) {
Log.d("Read Error", e.toString());
}finally {
outstream = bluetoothSocket.getOutputStream();
outstream.write("F".getBytes());
}
break;
}
} catch (IOException connectException) {
connectException.printStackTrace();
try {
bluetoothSocket.close();
} catch (IOException closeException) {
closeException.printStackTrace();
}
}
你能帮助我吗
答案 0 :(得分:0)
while (true)
循环可以终止的唯一方法是通过break
语句,或通过获取未捕获的异常,并且您没有提到获得一个。此代码中有两种可能的例外情况:
IOException
:但是使用此代码获取IOException
的唯一方法是对等重置连接。ArrayIndexOutOfBoundsException
在构建String
时,如果bytes
是否定的,则可以是:见下文;但你也没有提到这一点。你的实际问题是你没有检查bytes
是否为-1,这表示流的结束,这反过来表明对等方已关闭连接,这反过来表明你应该关闭套接字和跳出读循环。