我正在寻找一种优雅地与蓝牙设备断开连接的方法。我使用了 BluetoothChat 示例,问题是当您打算断开连接时,您只需socket.close()
从该cancel()
方法调用,但随后IntputStream.read()
将不可避免地引发异常。
我需要这个主要是因为它也充当“丢失连接”故障保护,所以当我尝试断开连接时,我得到两个信号:正常断开连接,然后是丢失连接信号。
基本上我想要做的不是在不可避免地抛出异常的方法中抛出异常:
while(true)
{
try
{
bytes = 0;
while((ch = (byte) inStream.read()) != '\0')
{
buffer[bytes++] = ch;
}
String msg = new String(buffer, "UTF-8").substring(0, bytes);
Log.v(TAG, "Read: " + msg);
}
catch(IOException e)
{
Log.e(TAG, "Failed to read");
// Inform the parent of failed connection
connectionEnd(STATE_LOST);
break;
}
}
和极度自私的cancel()
:
public void cancel()
{
try
{
socket.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
编辑
这是我进入时得到的错误e.printStackTrace();
代码catch
:
09-06 13:05:58.557: W/System.err(32696): java.io.IOException: Operation Canceled
09-06 13:05:58.557: W/System.err(32696): at android.bluetooth.BluetoothSocket.readNative(Native Method)
09-06 13:05:58.557: W/System.err(32696): at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:333)
09-06 13:05:58.557: W/System.err(32696): at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:60)
09-06 13:05:58.557: W/System.err(32696): at com.bluetooth.BluetoothRemoteControlApp$ConnectedThread.run(BluetoothRemoteControlApp.java:368)