看官们,我们在上一章回中介绍了BLE开发中蓝牙扫描设备的例子,本章回中我们继续介绍该例子,闲话休提,言归正转。让我们一起Talk Android吧!

我们在上一章回中介绍了BluetoothLeScanner类的startScan方法,本章回中介绍该方法的第一个参数:filters,该参数是ScanFilter类型的List.该参数的主要作用是用来过滤蓝牙设备,这点和前面章回中提到的UUID一样。不过它提供的过滤条件更加丰富,官方给出的条件有以下五个:

  • UUID
  • 蓝牙设备名
  • 蓝牙设备MAC地址
  • 服务包含的数据
  • 厂商提供的特殊数据;

下面是官方文档中的说明:

Current filtering on the following fields are supported: Service UUIDs which identify the bluetooth gatt services running on the device. Name of remote Bluetooth LE device. Mac address of the remote
device. Service data which is the data associated with a service.
Manufacturer specific data which is the data associated with a particular manufacturer.

我在代码中使用了设备名称来当作过滤条件,示例代码如下:

List<ScanFilter> filters = new ArrayList<ScanFilter>();
filters.add(0, new ScanFilter.Builder().setDeviceName("nameA").build());

不过从实际使用中看,它只扫描到和名字完成相同的设备,比如我们想扫描姓张的设备,设备名字写成张*这样的正则表达式,扫描结果为空,也就是扫描不到蓝牙设备。因此我推断它不支持像正则表达式一样设置过滤条件,分析源代码后发现它使用了ScanFilter类的equals方法进行判断,而且该类还重写了equals方法。从源代码中可以看到我的推断是正确的。关于源代码中各种嵌套的调用这里不列出了,最后会使用到下面的方法,而该方法就是使用了ScanFilter类的equals方法:

public boolean isAllFieldsEmpty() {
    return EMPTY.equals(this);
}

我在代码还尝试使用UUID来当作过滤条件,具体的代码如下:

List<ScanFilter> filters = new ArrayList<ScanFilter>();
filters.add(0, new ScanFilter.Builder().setServiceUuid(new ParcelUuid(UUID.fromString(SEARCH_SERVICE_UUID))).build());

扫描设备后,可以扫描出与UUID类型匹配的蓝牙设备,这点和使用BluetoothAdapter的startLeScan方法得到的结果相同。其它的过滤条件我没有去尝试,感兴趣的看官们可以自己动手实践一下。

各位看官,关于Android中蓝牙扫描设备的例子咱们就介绍到这里,欲知后面还有什么例子,且听下回分解!