查找 BLE 设备

要查找 BLE 设备,您可以使用 startScan() 方法。此方法采用 ScanCallback 作为参数。 您必须实现此回调,因为这是返回扫描结果的方式。 由于扫描非常耗电,因此您应该注意以下事项: 指南:

  • 找到所需设备后,立即停止扫描。
  • 永不循环扫描,并始终设置扫描时间限制。具有如下特征的设备: 可能已经超出有效范围, 很耗电。

在以下示例中,BLE 应用提供了一个 activity (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();
            }
        };