Android BLE 广告 UUID 长度在不同的 SDK 级别上不同?

Android BLE Advertising UUID Length differs on different SDK level?

我想通过 BLE 广播一些数据。

addServiceData 函数接受一个 ParcelUuid 和数据。

https://developer.android.com/reference/android/bluetooth/le/AdvertiseData.Builder.html

我在我的 Android 7.0 智能手机上测试了它,Uuid 被缩小到 16 位 .

https://code.tutsplus.com/tutorials/how-to-advertise-android-as-a-bluetooth-le-peripheral--cms-25426

While this utility creates a 128-bit UUID, the Android system only uses 16-bit UUIDs for advertisement and will automatically adjust a 128-bit UUID to conform.

这很好,因为我需要带宽来发送数据。但是 same 应用程序在 Android 8.1 设备上发送 完整的 128 位 Uuid

我不明白这一点,我希望我的应用始终发送 16 位 Uuid。 我没有找到选择 Uuid 长度的选项。

16 位蓝牙 UUID 是以下的快捷方式:

0000xxxx-0000-1000-8000-00805F9B34FB

… 其中 xxxx 是 16 位。例如,如果你想发布一个BEEF UUID,我相信你需要将0000BEEF-0000-1000-8000-00805F9B34FB传递给AdvertiseData.Builder

在堆栈的更下方,Android 应将其识别为 16 位蓝牙 UUID,并仅广播这两个字节。相关代码在AOSP中的AdvertiseHelper and BluetoothUuid类中:

public static byte[] uuidToBytes(ParcelUuid uuid) {
    if (uuid == null) {
        throw new IllegalArgumentException("uuid cannot be null");
    }

    if (is16BitUuid(uuid)) {
        byte[] uuidBytes = new byte[UUID_BYTES_16_BIT];
        int uuidVal = getServiceIdentifierFromParcelUuid(uuid);
        uuidBytes[0] = (byte) (uuidVal & 0xFF);
        uuidBytes[1] = (byte) ((uuidVal & 0xFF00) >> 8);
        return uuidBytes;
    }

    ...

我猜这个行为可能在 7.0 和 8.1 之间发生了变化。看起来像以前,他们可能无论如何都将 128 位 UUID 转换为 16 位 UUID。现在,看起来只有在 128 位 UUID 遵循蓝牙 standard/notation.

时才会正确执行此操作