4

I am having an issue where when I call sock.connect() it just hangs indefinitely. There is no exception and no timeout.

try
    {
        Method m = dev.getClass().getMethod("createRfcommSocket", new     Class[] {int.class});          
        sock = (BluetoothSocket) m.invoke(dev, 1); 
        sock.connect();
        Thread.sleep(100);
        in = sock.getInputStream();
        out = sock.getOutputStream();
    }
    catch(ConnectTimeoutException ex)
    {
        return false;
    }
    catch(IOException ex)
    {
        return false;
    }
    catch(Exception ex)
    {
        return false;
    }

The reason is that another app is using the bluetooth device already. I am trying to make my connection fail and at least throw an exception or something to let me know the device is already in use by another app.

Any other suggestions to approaching this?

Thanks.

Jesse
  • 2,674
  • 6
  • 30
  • 47

1 Answers1

0

Why are you calling Thread.Sleep? BluetoothSocket.connect is a blocking call. This means that your Thread.Sleep will not be called until connect returns with either a successful connection or throws an exception.

Are you calling this in an activity? As this will hang your activity. You should have 3 threads to handle bluetooth, an accept thread, connect thread and a connected thread. Like in the BluetoothChat example here:

http://developer.android.com/resources/samples/BluetoothChat/index.html

Kevin Orriss
  • 1,012
  • 3
  • 11
  • 24