Android BLE广播添加ServiceData启动失败(错误码1)求助
Hey there, let's break down why your advertising is failing and how to fix it!
First, error code 1 corresponds to ADVERTISE_FAILED_DATA_TOO_LARGE in Android's BLE API. This means your combined advertising data exceeds the maximum allowed size for a BLE broadcast packet.
Key Background: BLE Broadcast Size Limit
BLE primary advertising packets have a strict maximum size of 31 bytes total. This includes all components you add: device name, service UUIDs, service data, flags, etc. When you enable setIncludeDeviceName(true) and add ServiceData, the sum of their byte counts is likely pushing over this 31-byte limit.
Common Fixes to Try:
Trim the Device Name
If your device name is longer than necessary, shorten it. Alternatively, remove the device name from the primary broadcast entirely by settingsetIncludeDeviceName(false)(you can still include it in the scan response packet if needed).Split Data Between Primary Broadcast and Scan Response
The scan response packet also has a 31-byte limit, but it's a separate packet sent only when a scanner requests it. Move non-critical data (like the device name) to the scan response, leaving the primary broadcast for your ServiceData:// Primary advertising data (only ServiceData) val advertiseData = AdvertiseData.Builder() .addServiceData(ParcelUuid(BleConsts.SERVICE_UUID), myData.toByteArray(Charsets.UTF_8)) .build() // Scan response data (contains device name) val scanResponse = AdvertiseData.Builder() .setIncludeDeviceName(true) .build() // Start advertising with both packets bleAdvertiser.startAdvertising( settings.build(), advertiseData, scanResponse, advertiseCallback )Use a 16-bit UUID Instead of 128-bit
If your service UUID is a 128-bit value, it takes up 16 bytes in the broadcast packet. Switching to a 16-bit UUID (if your service allows it) cuts that down to 2 bytes, freeing up space for your ServiceData.Compress Your ServiceData
Shorten themyDatastring or convert it to a more compact binary format. For example, if you're sending structured data, use protobuf or custom binary encoding instead of UTF-8 strings to reduce byte count.
Quick Check to Verify
You can calculate the total size of your advertising data to confirm it's over 31 bytes:
- Device name length (in bytes) + UUID size (2 or 16 bytes) + ServiceData length + 2 bytes (for the ServiceData header) + other overhead (like flags, ~3 bytes) = total size.
If this sum exceeds 31, that's definitely the issue!
内容的提问来源于stack exchange,提问作者giozh

