How to create UUID from string in android

后端 未结 6 1195
Happy的楠姐
Happy的楠姐 2020-12-29 01:53

In my app, I scan low energy Bluetooth for specific service uuid 2415. To convert the string 2415 into uuid I am using UUID serviceUUID = UUID.fromString(

6条回答
  •  有刺的猬
    2020-12-29 02:08

    The confusion that may lead many people here is that you can use short code UUIDs to reference bluetooth services and characteristics on other platforms - for instance on iOS with CBUUID. On Android however, you must provide a full, 128-bit length UUID as specified in RFC4122.

    The fix (as @Michael pointed out) is to prepend your 16bit or 32bit short UUID to the base bluetooth UUID. You can use these functions to make this a bit easier.

    public static final String baseBluetoothUuidPostfix = "0000-1000-8000-00805F9B34FB";
    
    public static UUID uuidFromShortCode16(String shortCode16) {
        return UUID.fromString("0000" + shortCode16 + "-" + baseBluetoothUuidPostfix);
    }
    
    public static UUID uuidFromShortCode32(String shortCode32) {
        return UUID.fromString(shortCode32 + "-" + baseBluetoothUuidPostfix);
    }
    

    For example:

    UUID uuid = uuidFromShortCode16("FFF0");
    

    This creates a UUID object from "0000FFF0-0000-1000-8000-00805F9B34FB".

提交回复
热议问题