2014-04-07 1 views
3

Android 4.4에서 Bluetooth 연결을 설정하려고하는데 BluetoothSocket의 연결 방법이 이상하게 작동하는 것 같습니다. 내 응용 프로그램은 장치가 이미 본딩되었다고 추측 할 수 있으므로 MAC 주소를 통해 연결할 수 있습니다. 그것은 장치가 처음으로 연결될 때 완벽하고 즉각적으로 연결되지만, 다시 시작하면 연결이 설정되지 않고 시간 초과가 발생합니다. 연결될 때까지 while 루프 안에서이 작업을 수행하지만 실제 솔루션을 사용하려면 너무 오래 걸리거나 전혀 작동하지 않습니다. 다음은 코드 예제입니다.Android에서 Bluetooth 장치에 대한 두 번째 연결이 실패합니다.

public class BluetoothManager{ 

    private BluetoothAdapter bluetoothAdapter; 
    private BluetoothDevice bluetoothDevice; 
    private BluetoothSocket socket; 
    private OutputStream output; 
    private InputStream input; 

    public BluetoothManager() { 
     /***************/ 
     /* Constructor */ 
     /***************/ 

     // lock = new Object(); 

     bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
    } 

    public boolean turnOnBluetooth() { 
     /**************************************/ 
     /* Turn on Bluetooth an notify result */ 
     /**************************************/ 

     // check if bluetooth is supported 
     if (bluetoothAdapter == null) { 
      return (false); 
     } else { 
      // enable Bluetooth if not enabled yet 
      if (!bluetoothAdapter.isEnabled()) { 
       bluetoothAdapter.enable(); 
      } 
      while (!bluetoothAdapter.isEnabled()) { 
       Log.i("Debug", "Waiting for bluetooth to turn on"); 
       try { 
        Thread.sleep(500); 
       } catch (Exception e) { 
       } 
      } 
      return (true); 
     } 
    } 

    public boolean turnOffBluetooth() { 
     /***************************************/ 
     /* Turn off Bluetooth an notify result */ 
     /***************************************/ 

     // check if bluetooth is supported 
     if (bluetoothAdapter == null) { 
      return (false); 
     } else { 
      // disable Bluetooth if not enabled yet 
      if (bluetoothAdapter.isEnabled()) { 
       bluetoothAdapter.disable(); 
      } 
      while (bluetoothAdapter.isEnabled()) { 
       Log.i("Debug 
        Thread.sleep(500); 
       } catch (Exception e) { 
       } 
      } 
      return (true); 
     } 
    } 

    public boolean configureBluetooth(String MACaddress) { 
     /***********************************************************************/ 
     /* Configures to the specified bluetooth device and returns the result */ 
     /***********************************************************************/ 

     Log.i("Debug", "Connecting to Bluetooth Device"); 
     bluetoothDevice = bluetoothAdapter.getRemoteDevice(MACaddress); 

     return (true); 
    } 

    @SuppressLint("NewApi") 
    public void createSocket() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{ 
     final UUID serialUUID = UUID 
       .fromString("00001101-0000-1000-8000-00805F9B34FB"); 

     socket = null; 
     output = null; 
     input = null; 


     Method m = bluetoothDevice.getClass().getMethod("createInsecureRfcommSocket", new Class[] { int.class }); 
     socket = (BluetoothSocket)m.invoke(bluetoothDevice, 1); 
    } 


    @SuppressLint("NewApi") 
    public void connect() throws IOException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { 
     /************************************/ 
     /* Connects to the bluetooth device */ 
     /************************************/ 

     Log.i("Debug", "en connect"); 
     while (!socket.isConnected()) { // we try until the connection is established 
      try { 
       socket.connect(); 
       output = socket.getOutputStream(); 
       input = socket.getInputStream(); 
      } catch (IOException e) { 
       Log.i("Depuración", "Connection not established. Another run : "+e); 
       try { 
        Thread.sleep(1000); 
       } catch (Exception e1) { 
       } 
      } 
     } 
    } 

    public void terminateConnection() throws IOException { 
     Log.i("Debug", "terminating connection"); 
     if(output!=null){ 
      Log.i("Debug", "output!=null - stop streaming"); 
      stopStreaming(); 
     } 

     try { 
      Thread.sleep(100); 
     } catch (Exception e) { 
     } 
     if(input!=null){ 
      Log.i("Debug", "input!=null"); 
      input.close(); 
      input=null; 
     } 
     if(output!=null){ 
      Log.i("Depuración", "output!=null"); 
      output.close(); 
      output = null; 
     } 
     if(socket!=null){ 
      Log.i("Debug", "socket!=null"); 
      socket.close(); 
      socket=null; 
     } 
     try { 
      Thread.sleep(100); 
     } catch (Exception e) { 
     } 
     turnOffBluetooth(); 
     try { 
      Thread.sleep(100); 
     } catch (Exception e) { 
     } 
     try { 
      Thread.sleep(100); 
     } catch (Exception e) { 
     } 
     System.gc(); 
    } 

이 방법을 내 MainActivity에서 호출하면 작동하지만, 처음 장치가 본딩 된 경우에만 작동합니다.

socket.connect(); 

나는 그것이 내가 연결을 종료하는 방식과 함께 할 수있는 뭔가가 생각,하지만 난 그것을 알아낼 수 없습니다 : 다시 응용 프로그램을 실행할 경우에 나는에서 장치에 연결을 시도 예외가. 다음은 메소드의 순차적 호출입니다.

protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     bluetoothManager = new BluetoothManager(); 
     try { 
      bluetoothManager.terminateConnection(); 
     } catch (IOException e2) { 
      // TODO Auto-generated catch block 
      e2.printStackTrace(); 
     } 
     bluetoothManager.turnOffBluetooth(); 
     bluetoothManager.turnOnBluetooth(); 

     boolean configured = false; 
     while (!configured) { 
      Log.i("Debug", "Configuration Attemp"); 
      configured = bluetoothManager.configureBluetooth(MACaddress); 
     } 

     Log.i("Debug", "Bluetooth Configured"); 

     try { 
      bluetoothManager.createSocket(); 
     } catch (NoSuchMethodException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } catch (IllegalAccessException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } catch (IllegalArgumentException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } catch (InvocationTargetException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 

     Log.i("Depuración", "Socket created"); 

     try { 
      bluetoothManager.connect(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } catch (NoSuchMethodException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IllegalAccessException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IllegalArgumentException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (InvocationTargetException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     Log.i("Debug", "Connected!!!!"); 

protected void onPause() { 
    Log.i("Debug", "On pause"); 

    // TODO Auto-generated method stub 
    try { 
     bluetoothManager.terminateConnection(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    bluetoothManager = null; 
    System.gc(); 
    super.onPause(); 
}; 

저는 며칠 동안이 문제를 해결하려고 노력했지만 여전히 이유를 찾을 수 없습니다.

+0

BluetoothChat 샘플 응용 프로그램을 참조하셨습니까? 그렇지 않다면, 그것을 통과하십시오. –

+0

500msec 동안 기다리는 대신 BluetoothAdapter.ACTION_STATE_CHANGED 작업을 수신 대기하십시오. –

답변

0

글쎄, 나는이 프로가 아니지만, 앱이 닫힐 때 bluetoothManager.terminateConnection();에 전화해야한다고 말하지만, onDestroy이 아니라, onCreate; 이전 연결이 올바르게 종료되지 않은 경우에도 연결에 문제가있었습니다. 주 활동에이 방법을 추가하십시오 :

@Override 
    public void onDestroy(){ 
    if (bluetoothManager != null){ 
     bluetoothManager.terminateConnection(); 
    } 
    super.onDestroy(); 
} 

희망을 얻으십시오.

+0

BluetoothManager는 정확히 무엇입니까? 문서 참조 또는 적어도 부모 패키지 이름을 줄 수 있습니까? – milosmns

관련 문제