【发布时间】:2016-06-24 00:31:08
【问题描述】:
我正在通过蓝牙连接两台设备,当我按下一台设备上的注销按钮时,我想向另一台设备发送一条消息(告诉另一台也注销),关闭蓝牙连接,然后关闭当前活动(即返回我的登录活动)
问题是我不断收到这个异常,这让我觉得我没有正确关闭我的连接:
java.io.IOException: bt socket closed, read return: -1
at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:517)
at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:96)
at java.io.InputStream.read(InputStream.java:162)
at com.example.BTService$ConnectedThread.run(BTService.java:269)
BTService.java:269 是 connectedThread 从输入流中读取的位置
按下注销时,我基本上破坏了MainActivity,并在onDestroy() 中停止了我的蓝牙服务:
this.stopService(new Intent(this, BTService.class))
应该调用我的服务的onDestroy(),它调用stopConnect():
public static void stopConnect(){
if (connectThread != null) {
connectThread.cancel();
connectThread = null;
}
if (connectedThread != null) {
connectedThread.cancel();
connectedThread = null;
}
}
所以只要点击注销销毁服务,就应该调用我的connectedThread的cancel()方法:
public static class ConnectedThread extends Thread {
private BluetoothSocket mmSocket;
private InputStream mmInStream;
private OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
//Tell other phone that we have connected
write("connected".getBytes());
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (!this.isInterrupted()) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
if (mmInStream != null) {
try {mmInStream.close();} catch (Exception e) {}
mmInStream = null;
}
if (mmOutStream != null) {
try {mmOutStream.close();} catch (Exception e) {}
mmOutStream = null;
}
if (mmSocket != null) {
try {mmSocket.close();} catch (Exception e) {}
mmSocket = null;
}
this.interrupt();
}
}
我认为我这样做是正确的,首先关闭我的输入和输出流,然后关闭套接字,然后关闭线程。我从这里的答案中得到了这个:Disconnect a bluetooth socket in Android
但是,一旦按下注销,我就会收到 ioexception,因为它仍在尝试从输入流中读取。我还尝试将我的输入/输出/套接字关闭代码放在 ConnectedThread 类之外的方法中,但这会导致同样的问题
【问题讨论】:
-
到底是什么问题?您在读取套接字时关闭了套接字,因此出现“套接字关闭”异常。这正是应该发生的事情。
-
我认为在关闭套接字之前停止尝试读取它会更好吗?因此,为什么我在关闭套接字之前尝试关闭输入流但它仍然抛出异常
标签: android multithreading sockets bluetooth stream