title: Android Bluetooth IOException bad file number
body: <p>I have a receive thread listening with the BluetoothServerSocket accept() call. This thread will be killed and restarted by another thread pretty frequently. When it gets the kill signal, it closes the BluetoothServerSocket therefore causing an IOException in accept(), and gets out of the infinite-loop. But occasionally, during these starts and restarts the listenUsingRfcommWithServiceRecord() call will catch a "bad file number" IOException and exit the loop prematurely. I think I may not be shutting down the BT component correctly  in kill(?) but haven't figure out anything yet... Could someone give me some pointers?</p>
  
  <pre><code>private class ReceiveThread extends Thread {
      private final static String TAG = "ReceiveThread";
      private BluetoothServerSocket mmBtServer;
      private BluetoothSocket mmBtSocket;
  
      public ReceiveThread() {
          setName(TAG);
      }
  
      public void run() {
          if(D) Log.d(TAG,"RceiveThread running");
  
          while(true) {
              try {
                  SetState(SERVICE_STATE.LISTENING);
                  mmBtServer = mBtAdapter.listenUsingRfcommWithServiceRecord(mAppName, mUUID);
  
                  if(D) Log.d(TAG,"ReceiveThd accepting connection");
                  mmBtSocket = mmBtServer.accept();
                  // Close server once socket establishes
                  mmBtServer.close();
  
                  if(D) Log.d(TAG, "Connection Established");
                  SetState(SERVICE_STATE.CONNECTED_BUSY);
  
  
  
                  /** Handle Processing **/
  
  
  
                  // Close socket
                  mmBtSocket.close();
              } catch (IOException e) {
                  SetState(SERVICE_STATE.NOT_CONNECTED);
                  Log.d(TAG,"IOException in ReceiveThread", e);
                  break;
              }
  
              SetState(SERVICE_STATE.CONNECTED_IDLE);
          }
      }
  
      public void kill() {
          try {
              if(mmBtSocket!=null) mmBtSocket.close();
              if(mmBtServer!=null) mmBtServer.close();
          } catch (IOException e) {
              Log.d(TAG,"Failure killing ReceiveThread", e);
          }
          SetState(SERVICE_STATE.NOT_CONNECTED);
      }
  }
  </code></pre>