I'm trying to find all devices that are paired and are in range of my mobile device.
I'm testing with my laptop and my sony amp which are bluetooth enabled.
I can find my laptop, but my amp always returns "read failed, socket might closed or timeout, read ret: -1". My laptop is connected to my amp via bluetooth playing spotify - so maybe this is why my phone can't connect. However I still need to be able to detect whether this device is in range regardless of whether I can connect to it.
Here is some example code showing how I am trying to retrieve the devices. I got this solution from this SO answer https://stackoverflow.com/a/25647197/400320
Set<BluetoothDevice> bondedDevices = new HashSet<>(getBondedDevices());
Set<BluetoothDevice> connectedDevices = new HashSet<>();
for (BluetoothDevice device : bondedDevices) {
BluetoothDevice actual = bluetoothAdapter.getRemoteDevice(device.getAddress());
UUID SERIAL_UUID = actual.getUuids()[0].getUuid(); //if you don't know the UUID of the bluetooth device service, you can get it like this from android cache
BluetoothSocket socket = null;
try {
socket = device.createRfcommSocketToServiceRecord(SERIAL_UUID);
} catch (Exception e) {
Log.e("", "Error creating socket");
}
try {
socket.connect();
connectedDevices.add(device);
Log.e("", "Connected");
} catch (IOException e) {
Log.e("", e.getMessage());
try {
Log.e("", "trying fallback...");
socket = (BluetoothSocket) actual.getClass().getMethod("createRfcommSocket", new Class[]{int.class}).invoke(actual, 1);
socket.connect();
connectedDevices.add(device);
Log.e("", "Connected");
} catch (Exception e2) {
Log.e("", "Couldn't establish Bluetooth connection!");
}
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return connectedDevices;