title: Second connection to Bluetooth device fails in Android
body: <p>I'm trying to establish a Bluetooth connection in Android 4.4 but the connect method of BluetoothSocket seems to be working strangely. My app can assume the device is already bonded, so I can connect via MAC address. The thing is that it connects perfectly and immediately the first time the device is bonded, but if I relaunch it, the connection isn't established and a timeout occurs. I do this inside a while loop until it connects, but it takes too long for a real solution or it doesn't work at all. Here's a sample of my code:</p>
  
  <pre><code>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();
      }
  </code></pre>
  
  <p>If I call this methods from my MainActivity, it works, but only the first time the device is bonded. If I launch the app again I get an exception trying to connect to the device in:</p>
  
  <pre><code>socket.connect();
  </code></pre>
  
  <p>I suspect it has something to do with the way I terminate the connection, but I can't figure it out. Here's the sequential call of the methods:</p>
  
  <pre><code>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();
  };
  </code></pre>
  
  <p>I've been trying to solve this for days and I still can't find a reason.</p>