连接APP到Android的蓝牙UUID。

9
我正在开发一款安卓应用程序,用于跟踪设备的蓝牙连接,并在它们超出范围时触发警报。

安卓文档要求提供UUID以建立连接。

'uuid'是指通用唯一识别码(Universally Unique Identifier),是一个标准化的128位格式的字符串ID,用于唯一标识信息。它用于唯一标识您的应用程序的蓝牙服务。

 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;
}

我没有在两个设备上安装应用程序,因此我无法设置自己的UUID,我想使用Android的UUID...但是我无法在文档中找到这个信息。

也许我没有正确解决问题。任何帮助将不胜感激。 提前致谢。

1个回答

27

你可以通过BluetoothDevice获取UUID

    mmDevice = device;

    // Get a BluetoothSocket to connect with the given BluetoothDevice. This code below show how to do it and handle the case that the UUID from the device is not found and trying a default UUID.

    // Default UUID
    private UUID DEFAULT_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); 

    try {
        // Use the UUID of the device that discovered // TODO Maybe need extra device object
        if (mmDevice != null)
        {
            Log.i(TAG, "Device Name: " + mmDevice.getName());
            Log.i(TAG, "Device UUID: " + mmDevice.getUuids()[0].getUuid());
            tmp = device.createRfcommSocketToServiceRecord(mmDevice.getUuids()[0].getUuid());

        }
        else Log.d(TAG, "Device is null.");
    }
    catch (NullPointerException e)
    {
        Log.d(TAG, " UUID from device is null, Using Default UUID, Device name: " + device.getName());
        try {
            tmp = device.createRfcommSocketToServiceRecord(DEFAULT_UUID);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
    catch (IOException e) { }

1
我很乐意在这上面浪费了很多时间。你可以查看https://github.com/itzikBraun/ArduinoCar,这是一个通过蓝牙控制Arduino的应用程序,有两个线程处理连接,也许这会更有帮助。 - Braunster
很奇怪安卓不提供将两个设备配对的方法!(他们现在只添加了一个,在API 19上。当它似乎是如此基本和根本时) - frankelot
3
不幸的是,这只适用于一些设备。:/ 不是一个确定的解决方案。 - frankelot
2
明确检查 null 通常比捕获 NullPointerException 更可取。 - Greg Brown
2
你从哪里得到了这个“00001101-0000-1000-8000-00805F9B34FB”字符串? - luke cross
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接