安卓 - 获取此设备的蓝牙UUID

15
我在Stack和互联网上浏览,寻找一个简单的解决方案来获取我当前使用的设备的UUID。我偶然发现了像这样的帖子,但它们似乎都没有帮助到我。
文档告诉我关于这个getUuids()函数,但是当我通过Android Bluetooth的文档时,我得到的是一个BluetoothAdapter,但我需要一个BluetoothDevice来执行此函数。
所以我需要知道以下内容: 1.这个函数是否真的返回设备的UUID? 因为名称为复数形式(getUuids)。 2.如何获得此BluetoothDevice的实例?

无论如何,你怎么知道UUID是针对你的蓝牙设备的,@Ron? - gumuruh
2个回答

18

使用反射,您可以在BluetoothAdapter上调用隐藏的getUuids()方法:

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

Method getUuidsMethod = BluetoothAdapter.class.getDeclaredMethod("getUuids", null);

ParcelUuid[] uuids = (ParcelUuid[]) getUuidsMethod.invoke(adapter, null);

for (ParcelUuid uuid: uuids) {
    Log.d(TAG, "UUID: " + uuid.getUuid().toString());
}

这是在Nexus S上的结果:


UUID: 00001000-0000-1000-8000-00805f9b34fb
UUID: 00001001-0000-1000-8000-00805f9b34fb
UUID: 00001200-0000-1000-8000-00805f9b34fb
UUID: 0000110a-0000-1000-8000-00805f9b34fb
UUID: 0000110c-0000-1000-8000-00805f9b34fb
UUID: 00001112-0000-1000-8000-00805f9b34fb
UUID: 00001105-0000-1000-8000-00805f9b34fb
UUID: 0000111f-0000-1000-8000-00805f9b34fb
UUID: 0000112f-0000-1000-8000-00805f9b34fb
UUID: 00001116-0000-1000-8000-00805f9b34fb

例如,0000111f-0000-1000-8000-00805f9b34fb 代表 HandsfreeAudioGatewayServiceClass,而 00001105-0000-1000-8000-00805f9b34fb 则代表 OBEXObjectPushServiceClass。实际可用性可能取决于设备和固件版本。


1
我正在使用SDK16,但它对我不起作用。 "uuids"是“null”。此外,我想只获取我的蓝牙UUID。你知道如何获取吗? - Ron
Galaxy S2... 我需要开启蓝牙才能获取我的 UUID 吗? - Ron
1
蓝牙必须开启。我在安卓4.1.2的Galaxy S2上进行了测试,它能够正常工作并显示出12个UUID。 - Stefano S.
2
好的,目前为止很不错 - 谢谢 :) 但是我如何获取代表我的手机的UUID呢?或者我需要所有这些来识别我的设备吗? - Ron
1
@Ron,你得到你想要的了吗?我也想问。如果我为两个不同的Android设备定义自己的UUID来进行通信,这样可以吗?我的意思是,如果我为两个不同的设备使用相同的UUID,那么会不会冲突? - gumuruh
显示剩余6条评论

2
为了实现这一点,您必须定义蓝牙权限:
<uses-permission android:name="android.permission.BLUETOOTH"/>

然后您可以使用反射调用方法getUuids()

    try {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    Method getUuidsMethod = BluetoothAdapter.class.getDeclaredMethod("getUuids", null);
    ParcelUuid[] uuids = (ParcelUuid[]) getUuidsMethod.invoke(adapter, null);

         if(uuids != null) {
             for (ParcelUuid uuid : uuids) {
                 Log.d(TAG, "UUID: " + uuid.getUuid().toString());
             }
         }else{
             Log.d(TAG, "Uuids not found, be sure to enable Bluetooth!");
         }

    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }

您必须启用蓝牙才能获取Uuids。


java.lang.NoSuchMethodException: 参数类型为空 - "getUuids" - user924
我怎样才能知道哪个UUID属于我想配对的设备?我可以通过device.getAddress()发现一个设备,它返回类似于24:A0:C4:BF:5C:F2的东西。另一方面,使用您的代码,我会得到每个licass的3个UUID,如下所示:0000110a-0000-1000-8000-00805f9b34fb,只有第一个块中的差异。我想调用createInsecureRfcommSocketToServiceRecord(UUID)来将Android与ESP32设备配对。 - LucasRT

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接