断开我正在寻找一种方式来正常从蓝牙设备断开连接时例外。我用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)
这并没有帮助,我仍然得到'无法read'我的日志错误。要么解决这个问题有一个非常简单的方法,要么是一个主要的缺陷,因为丢失和完成连接有很大的不同。 – Solenoid
我也遇到过这个问题。所以最后我通过覆盖onBackPressed()方法解决了这个问题,从那里删除了super()并在那里添加了上面的完整代码。我知道这不是完美的解决方案。但我只是为了检查流量而做的。所以,如果你想,那么你可以用它来检查。 –