title: Bluetooth: program stuck at connect() method
body: <p>I'm programming a simple Bluetooth client to send and receive text messages throught RFCOMM as a serial port. I had a look at the Android SDK tutorials and did it in the same way: an Activity which calls a thread to make the connection, and once done, another thread to take care of msg reception.</p>
  
  <p>I'm trying to connect to a Parallax EasyBluetooth. Connection works all right between computer and EasyBT, and also between a Java based mobile and the EasyBT. So the problem must be at the code or, I hope not, at the Android mobile bluetooth chip. Anyway it gets on and off, and detects other devices when scanning, so I guess problem is just my coding.</p>
  
  <p>The problem is that the code gets stuck at the connect() method. So let's see if anyone knows why.</p>
  
  <p>The XML for the activity is simple:</p>
  
  <pre><code>    &lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:orientation="vertical"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      &gt;
  &lt;TextView  
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:text="@string/hello"
      /&gt;
  &lt;Button 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:text="@string/boton"
      android:id="@+id/boton_enviar"
      /&gt;
  &lt;/LinearLayout&gt;
  </code></pre>
  
  <p>Of course I have added the bluetooth permissions to the Manifiest:</p>
  
  <pre><code>&lt;uses-permission android:name="android.permission.BLUETOOTH" /&gt;
  &lt;uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /&gt;
  </code></pre>
  
  <p>And the code is the following:</p>
  
  <pre><code>package uniovi.PFC;
  
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.OutputStream;
  import java.util.HashMap;
  import java.util.Map;
  import java.util.Set;
  import java.util.UUID;
  
  import android.app.Activity;
  import android.bluetooth.BluetoothAdapter;
  import android.bluetooth.BluetoothDevice;
  import android.bluetooth.BluetoothSocket;
  import android.content.Intent;
  import android.os.Bundle;
  import android.os.Handler;
  import android.util.Log;
  import android.view.View;
  import android.view.View.OnClickListener;
  import android.widget.ArrayAdapter;
  import android.widget.Button;
  
  public class PruebaBTActivity extends Activity {
      private String TAG = "pruebaBT";
      private BluetoothAdapter mBluetoothAdapter;
      private Map&lt;String, BluetoothDevice&gt; mArrayAdapter;
      private ConnectedThread hiloEscuchas;
      private ConnectThread hiloConectando;
      private Handler mHandler;
      private Button botonEnviar;
      private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
      private static final int REQUEST_ENABLE_BT = 1;
      private static final int MESSAGE_READ = 1;
      private byte bytes_enviar[];
      private String cmd;
  
      /** Called when the activity is first created. */
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);
          Log.d(TAG, "On create abriendo");
  
          mArrayAdapter = new HashMap&lt;String, BluetoothDevice&gt;();
  
          botonEnviar = (Button)findViewById(R.id.boton_enviar);
          botonEnviar.setEnabled(false);
          botonEnviar.setOnClickListener(new OnClickListener() {
  
              @Override
              public void onClick(View v) {
                   cmd = "A";
                   bytes_enviar = cmd.getBytes();
                   hiloEscuchas.write(bytes_enviar);
              }
          });
          Log.d(TAG, "On create cerrando");
      }
  
      @Override
  
      public void onResume() {
          super.onResume();
          mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
          if (mBluetoothAdapter == null) {
              Log.d(TAG, "Device does not support Bluetooth");
          }
          if (!mBluetoothAdapter.isEnabled()) {
              Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
              startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
          }
  
          Set&lt;BluetoothDevice&gt; pairedDevices = mBluetoothAdapter.getBondedDevices();
           // If there are paired devices
           if (pairedDevices.size() &gt; 0) {
               // Loop through paired devices
               for (BluetoothDevice device : pairedDevices) {
                   // Add the name and address to an array adapter to show in a ListView
                   mArrayAdapter.put(device.getName(), device);
               }
           }
  
           BluetoothDevice device = mArrayAdapter.get("EasyBT");
           hiloConectando = new ConnectThread(device);
           hiloConectando.run();
           //while(hiloEscuchas.isConnected()==false);
           //botonEnviar.setEnabled(true);
      }
  
      private class ConnectThread extends Thread {
          private final BluetoothSocket mmSocket;
          private final BluetoothDevice mmDevice;
  
          public ConnectThread(BluetoothDevice device) {
              // Use a temporary object that is later assigned to mmSocket,
              // because mmSocket is final
              BluetoothSocket tmp = null;
              mmDevice = device;
  
              // Get a BluetoothSocket to connect with the given BluetoothDevice
              try {
                  // MY_UUID is the app's UUID string, also used by the server code
                  tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
              } catch (IOException e) { }
              mmSocket = tmp;
          }
  
          public void run() {
              // Cancel discovery because it will slow down the connection
              mBluetoothAdapter.cancelDiscovery();
  
              try {
                  // Connect the device through the socket. This will block
                  // until it succeeds or throws an exception
                  mmSocket.connect();
              } catch (IOException connectException) {
                  // Unable to connect; close the socket and get out
                  try {
                      mmSocket.close();
                  } catch (IOException closeException) { }
                  return;
              }
  
              // Do work to manage the connection (in a separate thread)
              hiloEscuchas = new ConnectedThread(mmSocket);
              hiloEscuchas.run();
          }
  
          /** Will cancel an in-progress connection, and close the socket */
          public void cancel() {
              try {
                  mmSocket.close();
              } catch (IOException e) { }
          }
      }
  
      private class ConnectedThread extends Thread {
          private final BluetoothSocket mmSocket;
          private final InputStream mmInStream;
          private final OutputStream mmOutStream;
          private boolean conectado;
  
          public ConnectedThread(BluetoothSocket socket) {
              mmSocket = socket;
              InputStream tmpIn = null;
              OutputStream tmpOut = null;
              conectado = false;
              mHandler = new Handler();
  
              // Get the input and output streams, using temp objects because
              // member streams are final
              try {
                  tmpIn = socket.getInputStream();
                  tmpOut = socket.getOutputStream();
              } catch (IOException e) { }
  
              mmInStream = tmpIn;
              mmOutStream = tmpOut;
              conectado = true;
          }
  
          public boolean isConnected(){
              return conectado;
          }
  
          public void run() {
              byte[] buffer = new byte[1024];  // buffer store for the stream
              int bytes; // bytes returned from read()
  
              // Keep listening to the InputStream until an exception occurs
              while (true) {
                  try {
  
                      cmd = "A";
                      bytes_enviar = cmd.getBytes();
                      hiloEscuchas.write(bytes_enviar);
                      // Read from the InputStream
                      bytes = mmInStream.read(buffer);
                      // Send the obtained bytes to the UI Activity
                      mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                              .sendToTarget();
  
                  } catch (IOException e) {
                      break;
                  }
              }
          }
  
          /* Call this from the main Activity to send data to the remote device */
          public void write(byte[] bytes) {
              try {
                  mmOutStream.write(bytes);
              } catch (IOException e) { }
          }
  
          /* Call this from the main Activity to shutdown the connection */
          public void cancel() {
              try {
                  mmSocket.close();
              } catch (IOException e) { }
  
  
           }
          }
      }
  </code></pre>
  
  <p>There was some code to make a bluetooth scan for devices, but in order to get things simple until it works, I wrote the MAC address manually into a variable. Comments explain this, and also shows where it gets stuck.</p>
  
  <p>Thanks</p>