查找范围内的配对设备 - 找不到所有设备

时间:2015-09-16 13:49:15

标签: android bluetooth android-bluetooth

我正在尝试查找所有已配对且位于我的移动设备范围内的设备。

我正在测试我的笔记本电脑和我的索尼功放是否支持蓝牙功能。

我可以找到我的笔记本电脑,但我的放大器总是返回“读取失败,插座可能关闭或超时,读取ret:-1”。我的笔记本电脑通过蓝牙播放spotify连接到我的放大器 - 所以也许这就是为什么我的手机无法连接。但是,我仍然需要能够检测此设备是否在范围内,无论我是否可以连接到它。

以下是一些示例代码,显示了我如何检索设备。我从这个SO回答中得到了这个解决方案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;

0 个答案:

没有答案