Android - 获取此设备的蓝牙UUID

时间:2013-10-28 09:12:08

标签: android bluetooth uuid android-bluetooth

我正在浏览Stack和互联网,以获得一个简单的解决方案来获取我正在使用的设备的UUID。我偶然发现了posts like this,但他们似乎都没有帮助我。

该文档告诉我about this getUuids()函数,但在浏览Android Bluetooth的文档时,我最终得到BluetoothAdapter,但我需要BluetoothDevice来执行此功能。

所以我需要知道以下内容:

1)函数是否真的返回设备UUID?因为这个名字是复数(getUuid s

2)如何获取此BluetoothDevice的实例?

谢谢!

2 个答案:

答案 0 :(得分:17)

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

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用于HandsfreeAudioGatewayServiceClass00001105-0000-1000-8000-00805f9b34fb用于OBEXObjectPushServiceClass。此方法的实际可用性可能取决于设备和固件版本。

答案 1 :(得分: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。