使用 AltBeacon 库以 CoreBluetooth 格式发布广告

Advertise in CoreBluetooth format using the AltBeacon library

我正在尝试使用 BLE 在 Android 和 ios 之间实现 os 间广告和扫描功能。 我需要了解从 Android 设备在 CoreBluetooth 中投放广告需要遵循的流程。 我一直在使用 AltBeacon 库以 iBeacon 格式做广告,效果很好,但是 ios 无法扫描 iBeacon 上有限数量的信标的限制迫使我转向 CoreBluetooth 框架。

这是我用来以 iBeacon 格式做广告的示例代码:

BluetoothManager bluetoothManager =
            (BluetoothManager) applicationContext.getSystemService(Context.BLUETOOTH_SERVICE);
    if (bluetoothManager != null) {
        BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();
        BluetoothLeAdvertiser mBluetoothLeAdvertiser = mBluetoothAdapter.getBluetoothLeAdvertiser();
        if (mBluetoothLeAdvertiser != null) {
            beacon = new Beacon.Builder()
                    .setId1(userId)
                    .setId2("1")
                    .setId3("1")
                    .setManufacturer(0x004C)
                    .setTxPower(-75)
                    .setDataFields(Arrays.asList(new Long[]{0l}))
                    .build();
            beaconParser = new BeaconParser()
                    .setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24");
            beaconTransmitter = new BeaconTransmitter(InventaSdk.getContext(), beaconParser);
            beaconTransmitter.setBeacon(beacon);
        }
    }

CoreBluetooth 不是一种格式。它是 iOS 上的一组 API。使用 CoreBluetooth,您可以检测各种具有限制的信标格式:

  • 只有 iOS 应用在前台才能检测到 AltBeacon 格式
  • Eddystone 格式可以在前台和后台检测到,但在后台检测比 iBeacon 慢。
  • CoreBluetooth 无法检测到 iBeacon 格式。为此,您必须使用 CoreLocation。

要在 AltBeacon(可被核心蓝牙检测)中做广告,请使用此代码:

Beacon beacon = new Beacon.Builder()
        .setId1("2f234454-cf6d-4a0f-adf2-f4911ba9ffa6")
        .setId2("1")
        .setId3("2")
        .setManufacturer(0x0118)
        .setTxPower(-59)
        .setDataFields(Arrays.asList(new Long[] {0l}))
        .build();
BeaconParser beaconParser = new BeaconParser()
        .setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25");
BeaconTransmitter beaconTransmitter = new BeaconTransmitter(getApplicationContext(), beaconParser);
beaconTransmitter.startAdvertising(beacon);

使用 CoreBlutooth 解析信标很棘手。您可能想使用工具来执行此操作,例如 iOS Beacon Tools.

还值得补充的是,iOS 不能宣传 AltBeacon 或 Eddystone 格式。它只能发布 iBeacon 和 GATT 服务 UUID。