2012-09-05 8 views
0

블루투스 기기에서 안전하게 연결 해제 할 수있는 방법을 찾고 있습니다. BluetoothChat 샘플을 사용했는데 연결을 끊을 때 cancel() 메서드에서 socket.close() 메서드를 호출하면 IntputStream.read()이 필연적으로 예외를 throw합니다. 우아한 해제 손실 연결 신호 다음에 : 그것은뿐만 아니라 "손실 연결" 안전 장치 역할을하기 때문에 Android : 블루투스 기기와의 연결을 해제 할 때 예외가 발생합니다.

내가 분리하려고 할 때 그래서 두 신호를 얻을, 주로이 필요합니다.

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();이있는 오류 코드입니다.

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

해결책 : 완벽하지는 않지만 멈출 길이 없기 때문에

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

disconnectingcancel() 메서드를 호출하기 전에 true로 설정 : NG는 예외가 나는 분리 condidition했다. 나는 그것에 만족하지 않지만 못생긴다. 나는 블루투스 단절이 처리되는 방식에 만족하지 않고있다.

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

이것은 도움이되지 않았지만 여전히 내 로그에서 '읽지 못함'오류가 발생합니다. 어리석게 쉽게 해결할 수있는 방법이 있거나 큰 결함이 있습니다. 연결을 끊고 종료하는 데 큰 차이가 있기 때문입니다. – Solenoid

+0

나는 또한이 문제에 직면했다. 그래서 그것을 마지막으로 onBackPressed() 메서드를 재정 의하여이 문제를 해결할 super() 제거 된 및 위의 전체 코드 위에 추가했습니다. 나는 그것이 perfact 솔루션이 아니라는 것을 알고있다. 그러나 나는 단지 흐름을 확인하기 위해 그것을했다. 그래서 당신이 원한다면, 당신은 그것을 확인하기 위해서만 사용할 수 있습니다. –

관련 문제