Android BLE 通告失败,错误代码为 1

Android BLE Advertisement fails with error code 1

我有一个使用 BLE 来公布一些数据的示例应用程序。但是,我的广告失败,错误代码为 1。错误代码 1 基本上意味着有效负载大于广告数据包允许的 31 个字节。但是从我的代码中,我可以看到有效负载小于 31 个字节。问题在哪里?

有人建议关闭设备名称广告,因为长名称需要 space。我也这样做了。

private void advertise(){
        BluetoothLeAdvertiser advertiser =         BluetoothAdapter.getDefaultAdapter().getBluetoothLeAdvertiser();
    AdvertiseSettings settings = new AdvertiseSettings.Builder()
            .setAdvertiseMode( AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY )
            .setTxPowerLevel( AdvertiseSettings.ADVERTISE_TX_POWER_HIGH )
            .setTimeout(0)
            .setConnectable( false )
            .build();
    ParcelUuid pUuid = new ParcelUuid( UUID.fromString( getString( R.string.ble_uuid ) ) );
    //ParcelUuid pUuid = new ParcelUuid( UUID.randomUUID() );


    AdvertiseData data = new AdvertiseData.Builder()
            .setIncludeDeviceName(false)
            .setIncludeTxPowerLevel(false)

            .addServiceUuid( pUuid )
            .addServiceData( pUuid, "D".getBytes() )
            .build();
    advertiser.startAdvertising( settings, data, advertisingCallback );
}

我希望这会公布数据 "D",不会因错误代码 1 而失败。

在我看来,您将 pUuid 添加到广告数据中两次。一次单独使用,第二次使用数据 "D"。 BLE 广告只有 1 个 UUID 的空间。尝试消除第一次调用:

.addServiceUuid(pUuid)

而仅使用:

.addServiceData(pUuid, "D".getBytes())

“serviceDataUuid”仅为 16 位。如果 UUID 来自蓝牙 SIG,.addServiceData 方法会从给定的 128 位 UUID 中静默提取 16 位 UUID。从您的自定义 UUID = CDB7950D-73F1-4D4D-8E47-C090502DBD63,您必须创建一个在蓝牙 SIG 地址范围内的 16 位 UUID。

private void advertise(){
    BluetoothLeAdvertiser advertiser = BluetoothAdapter.getDefaultAdapter().getBluetoothLeAdvertiser();
    AdvertiseSettings settings = new AdvertiseSettings.Builder()
            .setAdvertiseMode( AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY )
            .setTxPowerLevel( AdvertiseSettings.ADVERTISE_TX_POWER_HIGH )
            .setTimeout(0)
            .setConnectable( false )
            .build();
    //ParcelUuid pUuid = new ParcelUuid( UUID.fromString( getString( R.string.ble_uuid ) ) );
    //ParcelUuid pUuid = new ParcelUuid( UUID.randomUUID() );
    ParcelUuid pUuid = new ParcelUuid( UUID.fromString("cdb7950d-73f1-4d4d-8e47-c090502dbd63"));
    ParcelUuid pServiceDataUuid = new ParcelUuid(UUID.fromString("0000950d-0000-1000-8000-00805f9b34fb"));


    AdvertiseData data = new AdvertiseData.Builder()
            .setIncludeDeviceName(false)
            .setIncludeTxPowerLevel(false)

            .addServiceUuid( pUuid )
            .addServiceData( pServiceDataUuid, "D".getBytes() )
            .build();
    advertiser.startAdvertising( settings, data, advertisingCallback );
}

Screenshot nRF Connect

我尝试了@Greg Moens 和@S 的上述解决方案。 Gysin,我发现的是 您只需将 ble_uuidCDB7950D-73F1-4D4D-8E47-C090502DBD63 更改为 00001101-0000-1000-8000-00805F9B34FB.

对我有用。

您也可以在此处查看完整的博文:https://code.tutsplus.com/tutorials/how-to-advertise-android-as-a-bluetooth-le-peripheral--cms-25426