查找 BLE 设备

要查找 BLE 设备,您可以使用 startScan() 方法。此方法采用 ScanCallback 作为参数。您必须实现此回调,因为这是返回扫描结果的方式。由于扫描会消耗大量电量,因此您应遵守以下指南

  • 找到所需设备后,立即停止扫描。
  • 切勿循环扫描,并且始终为扫描设置时间限制。先前可用的设备可能已移出范围,并且继续扫描会消耗电池电量。

在以下示例中,BLE 应用提供了一个活动(DeviceScanActivity)来扫描可用的蓝牙 LE 设备,并在列表中显示给用户。以下代码段显示了如何启动和停止扫描

Kotlin

private val bluetoothLeScanner = bluetoothAdapter.bluetoothLeScanner
private var scanning = false
private val handler = Handler()

// Stops scanning after 10 seconds.
private val SCAN_PERIOD: Long = 10000

private fun scanLeDevice() {
    if (!scanning) { // Stops scanning after a pre-defined scan period.
        handler.postDelayed({
            scanning = false
            bluetoothLeScanner.stopScan(leScanCallback)
        }, SCAN_PERIOD)
        scanning = true
        bluetoothLeScanner.startScan(leScanCallback)
    } else {
        scanning = false
        bluetoothLeScanner.stopScan(leScanCallback)
    }
}

Java

private BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
private boolean scanning;
private Handler handler = new Handler();

// Stops scanning after 10 seconds.
private static final long SCAN_PERIOD = 10000;

private void scanLeDevice() {
    if (!scanning) {
        // Stops scanning after a predefined scan period.
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                scanning = false;
                bluetoothLeScanner.stopScan(leScanCallback);
            }
        }, SCAN_PERIOD);

        scanning = true;
        bluetoothLeScanner.startScan(leScanCallback);
    } else {
        scanning = false;
        bluetoothLeScanner.stopScan(leScanCallback);
    }
}

要仅扫描特定类型的外设,您可以改为调用 startScan(List<ScanFilter>, ScanSettings, ScanCallback),提供一个 ScanFilter 对象列表来限制扫描查找的设备,以及一个 ScanSettings 对象来指定有关扫描的参数。

以下代码示例是 ScanCallback 的实现,它是用于传递 BLE 扫描结果的接口。找到结果后,它们将添加到 DeviceScanActivity 中的列表适配器中以显示给用户。

Kotlin

private val leDeviceListAdapter = LeDeviceListAdapter()
// Device scan callback.
private val leScanCallback: ScanCallback = object : ScanCallback() {
    override fun onScanResult(callbackType: Int, result: ScanResult) {
        super.onScanResult(callbackType, result)
        leDeviceListAdapter.addDevice(result.device)
        leDeviceListAdapter.notifyDataSetChanged()
    }
}

Java

private LeDeviceListAdapter leDeviceListAdapter = new LeDeviceListAdapter();

// Device scan callback.
private ScanCallback leScanCallback =
        new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
                super.onScanResult(callbackType, result);
                leDeviceListAdapter.addDevice(result.getDevice());
                leDeviceListAdapter.notifyDataSetChanged();
            }
        };