安卓设备.getUuids返回空值。

13

我正在使用蓝牙低功耗(BLE)的方式,尝试通过Android应用程序连接Arduino Uno。
我在Android Studio上开发,在一个运行着Android 5.0.1的三星Galaxy S4上进行测试。
我按照这个链接:http://www.truiton.com/2015/04/android-bluetooth-low-energy-ble-example/ 的指引操作。
我正在扫描设备,当找到一个设备时,我想在连接它之前获取其UUID,以确保它是正确类型的设备:

mScanCallback = new ScanCallback() {
        @Override
        @TargetApi(21)
        public void onScanResult(int callbackType, ScanResult result) {
            BluetoothDevice btDevice = result.getDevice();
            ParcelUuid[] uuids = btDevice.getUuids(); //<-- this is always null!! :(

            Log.d(TAG, ""+btDevice.fetchUuidsWithSdp()); //<-- prints true.
            Log.d(TAG, "result : " + result.toString()); //<-- prints a bunch of relevant info that contains the UUID I want to check.
            Log.d(TAG, "uuids : " + uuids); //<-- prints null.
            /*
            for (ParcelUuid u : uuids) {
                //Compare with the UUID of my device, and connect if ok.
            }
            */
        }
然而,btDevice.getUuids(); 一直返回空值并且没有错误...
我如何获取已扫描设备的UUID?
一种暴力方法是使用regexp和result.toString()来获取我想要的内容,但一定会有更好的方法,不是吗?
谢谢。

你找到解决方案了吗? - Igor Fridman
3个回答

12
 BluetoothLeScanner scanner = mBluetoothAdapter.getBluetoothLeScanner();
 // scan for devices
 scanner.startScan(new ScanCallback() {
 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
 @Override
 public void onScanResult(int callbackType, ScanResult result) 
   {
      List<ParcelUuid> uuids = result.getScanRecord().getServiceUuids();
   }
}

这对我在Android 6.0.1上有效。


使用 Kotlin 编写的代码如下:val uuids = result.scanRecord!!.serviceUuids。 - Kenn

2

经过数小时的搜索,我发现如果您想检索iBeacon的uuid,则getUuid()不是正确的方法。

如果是这种情况,您需要直接从扫描结果result对象中获取它。

我通过使用ADEBAYO OSIPITAN提供的答案成功解决了问题。 BLE obtain uuid encoded in advertising packet

以下是他的代码片段:

//For APIs greater than 21, Returns Device UUID
public String getUUID(ScanResult result){
String UUIDx = UUID
        .nameUUIDFromBytes(result.getScanRecord().getBytes()).toString();
    return UUIDx;
}

0

来自Java DOC:

public ParcelUuid[] getUuids ()

API 15中添加 返回远程设备支持的特征(UUID)。

此方法不会启动服务发现过程以从远程设备检索UUID。相反,返回本地缓存的服务UUID副本。

如果需要新的UUID,请使用fetchUuidsWithSdp()。

需要蓝牙。

返回远程设备支持的特征(UUID),或在出错时返回null。

您的ScanResult可能是一个错误。


1
我已经阅读了文档,甚至阅读了代码(它是开源的)。我确定这是一个错误,但它没有在任何地方打印出来...在BluetoothObject.java代码中,他们只记录了某种类型的错误,否则返回null而没有消息... - codejedi14

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