Android Bluetooth Socket Connect Hangs

I have a problem when I call sock.connect (), it just hangs endlessly. 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 application is already using a Bluetooth device. I try to make my connection fail and at least throw an exception or something to tell me that the device is already in use by another application.

Any other suggestions on this?

Thanks.

+4
source share
1 answer

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

Do you call it action? Because it will hang your activity. You must have 3 streams for bluetooth processing, receive stream, stream connection and associated stream. As in the BluetoothChat example:

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

0
source

Source: https://habr.com/ru/post/1399121/


All Articles