2012-09-05 61 views
0

斷開我正在尋找一種方式來正常從藍牙設備斷開連接時例外。我用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) 

回答

0

解決方案:它並不完美,但因爲沒有stoppi方式NG的例外,我做了一個斷開 condidition:

catch(IOException e) 
{ 
    if(!disconnecting) 
    { 
     Log.e(TAG, "Failed to read"); 
     e.printStackTrace(); 
     // Inform the parent of failed connection 
     connectionEnd(STATE_LOST); 
    } 
    break; 
} 

disconnecting被調用cancel()方法之前設置爲true。我不喜歡它,但它不是難看。我只是不滿意藍牙斷開處理的方式(它工作或中斷)。

0

試試這個: 假設你有OutputStream的out對象和InputStream的in對象,然後裏面你取消關閉這樣的連接 :

public void cancel() 
{ 
    if(socket != null) 
     { 
      try { 
       out.close(); 
       in.close(); 
       socket.getOutputStream().close(); 
       socket.close(); 
       socket = null; 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 
} 

希望這有助於你

+0

這並沒有幫助,我仍然得到'無法read'我的日誌錯誤。要麼解決這個問題有一個非常簡單的方法,要麼是一個主要的缺陷,因爲丟失和完成連接有很大的不同。 – Solenoid

+0

我也遇到過這個問題。所以最後我通過覆蓋onBackPressed()方法解決了這個問題,從那裏刪除了super()並在那裏添加了上面的完整代碼。我知道這不是完美的解決方案。但我只是爲了檢查流量而做的。所以,如果你想,那麼你可以用它來檢查。 –