以下两个是完全不同的东西,尽管都称为 UUID。
- 托管在 BLE 外围设备上的 GATT 服务的 UUID。
- iBeacon 的接近度 UUID。
关于“GATT 服务的 UUID”你应该知道的:
- BLE 外围设备可以实现 GATT 服务器。
- GATT 服务器托管 GATT 服务。
- API“android.bluetooth.BluetoothGatt.getServices()”返回的是 GATT 服务列表 (List<BluetoothGattService>)。
- BluetoothGattService.getUuid() 返回服务的 ID。
关于“iBeacon 的 Proximity UUID”你应该知道的:
- BLE 外围设备广播广告数据包。
- 广告数据包的有效负载部分包含一个 AD 结构列表。
- AD结构由(1)长度(1字节)、(2)AD类型(1字节)和(3)AD数据组成。AD结构格式在“Bluetooth Core Specification 4.2”的“11 ADVERTISING AND SCAN RESPONSE DATA FORMAT”中有描述。
- iBeacon 是一种 AD 结构。
- iBeacon 的 AD 类型为 0xFF(表示制造商特定数据)。
- iBeacon 的 AD Data 的前 4 个字节分别为 0x4C、0x00、0x02 和 0x15。前 2 个字节(0x4C、0x00)表示“Apple, Inc.”。接下来的 2 个字节(0x02、0x15)表示“iBeacon 格式”。
- Proximity UUID(16 字节)、主编号(大端 2 字节)、次编号(大端 2 字节)和功率(1 字节)在前 4 个字节之后。
所以,要获取 iBeacon 信息(Proximity UUID、major、minor、power),你需要做的事情如下。
- 将广告数据包的有效负载解析为 AD 结构列表。
- 对于每个 AD 结构,检查 AD Type 是否为 0xFF,AD Data 的前 4 个字节为 0x4C、0x00、0x02 和 0x15。
- 当满足2.的条件时,将剩余字节解析为Proximity UUID、major number、minor number、power。
如果您使用nv-bluetooth,您可以从广告包中提取 iBeacon,如下所示:
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord)
{
// Parse the payload of the advertising packet.
List<ADStructure> structures =
ADPayloadParser.getInstance().parse(scanRecord);
// For each AD structure contained in the advertising packet.
for (ADStructure structure : structures)
{
if (structure instanceof IBeacon)
{
// iBeacon was found.
IBeacon iBeacon = (IBeacon)structure;
// Proximity UUID, major number, minor number and power.
UUID uuid = iBeacon.getUUID();
int major = iBeacon.getMajor();
int minor = iBeacon.getMinor();
int power = iBeacon.getPower();
........
详见“ iBeacon 作为一种 AD 结构”。