title: Bluetooth On Android: my Socket.connect() Blocks forever, and Socket.close does not unblock
body: <p>I have been working on a bluetooth app for android for awhile now and I just discovered this problem. When I preform <code>mySocket.connect();</code> in my bluetooth service class it occasionally blocks indefinitely. I read the documentation for <code>BluetoothSocket.close()</code> and it says the following:</p>
  
  <blockquote>
    <p>Immediately close this socket, and release all associated resources. </p>
    
    <p>Causes blocked calls on this socket in other threads to immediately
    throw an IOException.</p>
  </blockquote>
  
  <p>However, this does not seem to work for me. Here is my code for setting a timer and then trying to connect.</p>
  
  <pre><code>//code for starting timer and connecting
      MyRunnable runner = new MyRunnable(mySocket);
      Thread countThread = new Thread(runner);
      countThread.start();
  
      mySocket.connect();
      runner.setSocketConnected();
  
  
  //code for MyRunnable
      private class MyRunnable implements Runnable{
          private boolean didSocketConnect = false;
          private boolean socketConnectFailed = false;
          private BluetoothSocket socket;
  
          public MyRunnable(BluetoothSocket socket){
              this.socket = socket;
          }
  
          public void run() {
              long start = System.currentTimeMillis();
              while(ESTABLISH_TIMEOUT + start &gt;= System.currentTimeMillis() &amp;&amp; !didSocketConnect &amp;&amp; !socketConnectFailed){
  
              }
              if(!didSocketConnect &amp;&amp; !socketConnectFailed){
                  Log.v(TAG,"Reached Timeout and socket not open. Look for #");
                  try {
                      socket.close();
                      Log.v(TAG,"#THIS CALL SHOULD BE MADE AFTER REACHED TIMEOUT AND SOCKET NOT OPEN");
                  } catch (IOException e) {
                      Log.v(TAG,"Closing the socket connection fail--", e);
                  }
              }else{
                  Log.v(TAG, "Connected or Failed Before Timeout Thread Hit");
              }
          }
  
          public void setSocketConnected(){
              didSocketConnect = true;
          }
  
          public void setSocketFailed(){
              socketConnectFailed= true;
          }
      }
  </code></pre>
  
  <p>When I call close(), it also blocks indefinitely and the connect() call never throws an IOException, despite BluetoothSocket.close() documentation. What is the best way to make it work so that the connect() and close() do not block indefinitely?</p>
  
  <p>NOTE: I am using Android 2.2 for this project.</p>