2012-09-05 239 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()并在那里添加了上面的完整代码。我知道这不是完美的解决方案。但我只是为了检查流量而做的。所以,如果你想,那么你可以用它来检查。 –