Custom UUID for multiple Bluetooth connection in Android

走远了吗. 提交于 2020-11-29 19:13:54

问题


I have an android device acting as server which connects to multiple bluetooth android clients. I understand the concept of UUID and how it is unique.

My question is, can I use the same UUID for all my clients connecting to my server? If not, how do I generate a UUID for my clients programmatically and let my server know about their UUIDs.

The problem started appearing after Android 8.1 where you no longer had access to bluetooth MAC address which I initially used to generate UUIDs for client android devices.


回答1:


Answer:

I finally found out that you can use a custom UUID using a generator and it works with multiple devices. The UUID must be unique and should not collide with the ones that are common & public. Hopefully someone finds it useful




回答2:


You can generate one like this. First, is needed to generate as long the 64 least and most significant bits:

private static long get64LeastSignificantBitsForVersion1() {
    Random random = new Random();
    long random63BitLong = random.nextLong() & 0x3FFFFFFFFFFFFFFFL;
    long variant3BitFlag = 0x8000000000000000L;
    return random63BitLong + variant3BitFlag;
}
 
private static long get64MostSignificantBitsForVersion1() {
    LocalDateTime start = LocalDateTime.of(1582, 10, 15, 0, 0, 0);
    Duration duration = Duration.between(start, LocalDateTime.now());
    long seconds = duration.getSeconds();
    long nanos = duration.getNano();
    long timeForUuidIn100Nanos = seconds * 10000000 + nanos * 100;
    long least12SignificatBitOfTime = (timeForUuidIn100Nanos & 0x000000000000FFFFL) >> 4;
    long version = 1 << 12;
    return 
      (timeForUuidIn100Nanos & 0xFFFFFFFFFFFF0000L) + version + least12SignificatBitOfTime;
}

next you can use the above methods to build one UUID:

public static UUID generateType1UUID() {
 
    long most64SigBits = get64MostSignificantBitsForVersion1();
    long least64SigBits = get64LeastSignificantBitsForVersion1();
 
    return new UUID(most64SigBits, least64SigBits);
}


来源:https://stackoverflow.com/questions/52670823/custom-uuid-for-multiple-bluetooth-connection-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!