23 android广播包的解析
final class BleUtil {
public static BleAdvertisedData parseAdertisedData(byte[] advertisedData) {
List<UUID> uuids = new ArrayList<UUID>();
String name = null;
byte[] data = null;
if (advertisedData == null) {
return new BleAdvertisedData(uuids, name);
}
ByteBuffer buffer = ByteBuffer.wrap(advertisedData)
.order(ByteOrder.LITTLE_ENDIAN);
while (buffer.remaining() > 2) {
byte length = buffer.get();
if (length == 0)
break;
byte type = buffer.get();
switch (type) {
case 0x02:
case 0x03:
while (length >= 2) {
uuids.add(UUID.fromString(
String.format("%08x-0000-1000-8000-00805f9b34fb",
buffer.getShort())));
length -= 2;
}
break;
case 0x05:
while (length >= 4) {
uuids.add(UUID.fromString(
String.format("%016x-0000-1000-8000-00805f9b34fb",
buffer.getInt())));
length -= 4;
}
break;
case 0x06:
case 0x07:
while (length >= 16) {
long lsb = buffer.getLong();
long msb = buffer.getLong();
uuids.add(new UUID(msb, lsb));
length -= 16;
}
break;
case 0x09:
byte[] nameBytes = new byte[length - 1];
buffer.get(nameBytes);
try {
name = new String(nameBytes, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
break;
case 0x16:
if (uuid128To16bit(BleLink.SERVICE_UUID) != buffer.getShort()) {
IwdsLog.d(MasterBleLink.TAG, "don't care the service data");
break;
}
data = new byte[length - 3];
buffer.get(data);
break;
default:
buffer.position(buffer.position() + length - 1);
break;
}
}
return new BleAdvertisedData(uuids, name, data);
}
private static short uuid128To16bit(String serviceUuid) {
String uuid16bit = serviceUuid.substring(4, 8);
return Integer.decode("0x" + uuid16bit).shortValue();
}
}
class BleAdvertisedData {
private List<UUID> mUuids;
private String mName;
private byte[] mData;
public BleAdvertisedData(List<UUID> uuids, String name) {
this(uuids, name, null);
}
public BleAdvertisedData(List<UUID> uuids, String name, byte[] data) {
mUuids = uuids;
mName = name;
mData = data;
}
public List<UUID> getUuids() {
return mUuids;
}
public String getName() {
return mName;
}
public byte[] getServiceData() {
return mData;
}
}