斷開我正在尋找一種方式來正常從藍牙設備斷開連接時例外。我用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()並在那裏添加了上面的完整代碼。我知道這不是完美的解決方案。但我只是爲了檢查流量而做的。所以,如果你想,那麼你可以用它來檢查。 –