startLeScan with 128 bit UUIDs doesn't work on native Android BLE implementation

后端 未结 11 2326
别跟我提以往
别跟我提以往 2020-11-28 04:19

I am having trouble using startLeScan( new UUID[]{ MY_DESIRED_128_BIT_SERVICE_UUID }, callback ) on the new introduced BLE API of Android 4.3 on my Nexus 4.

The cal

11条回答
  •  猫巷女王i
    2020-11-28 04:58

    @Navin's code is good, but it includes an overflow bug from the original 16-bit Android code. (If either byte is larger than 127 then it becomes a negative integer.)

    Here's an implementation which fixes that bug and adds 128-bit support:

    private List parseUuids(byte[] advertisedData) {
         List uuids = new ArrayList();
    
         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: // Partial list of 16-bit UUIDs
                 case 0x03: // Complete list of 16-bit UUIDs
                     while (length >= 2) {
                         uuids.add(UUID.fromString(String.format(
                                 "%08x-0000-1000-8000-00805f9b34fb", buffer.getShort())));
                         length -= 2;
                     }
                     break;
    
                 case 0x06: // Partial list of 128-bit UUIDs
                 case 0x07: // Complete list of 128-bit UUIDs
                     while (length >= 16) {
                         long lsb = buffer.getLong();
                         long msb = buffer.getLong();
                         uuids.add(new UUID(msb, lsb));
                         length -= 16;
                     }
                     break;
    
                 default:
                     buffer.position(buffer.position() + length - 1);
                     break;
             }
         }
    
         return uuids;
     }
    

提交回复
热议问题