Android BLE扫描并显示结果

时间:2019-10-21 20:40:14

标签: android bluetooth-lowenergy

我正在开发需要连接至低功耗蓝牙设备的android应用。为了实现该目标并遵循Android Dev page,我在清单文件中包含了正确的权限。在mainActivity中,我尝试扫描BLE设备并将结果打印在屏幕上。代码如下:

     final BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
     bluetoothLeScanner.startScan(callback);
     // Before 5 seconds, stop the scan and show results.
     new Handler().postDelayed(new Runnable() {
         @Override
         public void run() {
             bluetoothLeScanner.stopScan(callback);
             callback.onBatchScanResults(results);
             callback.onScanFailed(2);
             callback.onScanResult(3,result);
             listOfResults.setText(results.toString());
         }
     },5000);
  • 其中:
    • bluetoothApater是执行android page
    • 中所述的操作所需的BlueoothAdapter。
    • bluetoothLeScanner是执行LE扫描操作所需的对象,
    • callback是扫描回叫对象
    • results是列表
    • result是ScanResult,
    • listOfResults是文本视图。
  • 问题可能出在所使用的方法上,因为根据Android Official Page,我们发现三个要与回调一起执行的空隙(onBatchScanResult,onScanResult和onScanFailed),但是我只能在onBatchScanResult上工作。
  • 为什么没有显示设备?打印的唯一内容是活动名称,程序包名称和应用程序名称。

1 个答案:

答案 0 :(得分:0)

我这样做的方法是实现scanCallback()对象,并根据需要覆盖onScanResult()或onBatchScanResults()。

return sorted(los, key=lambda x: len(x)) == los and len({len(x) for x in los}) == len(los)

然后,您在 private ScanCallback callback= new ScanCallback() { @Override public void onScanResult(int callbackType, ScanResult result) { super.onScanResult(callbackType, result); // handles scan result } @Override public void onBatchScanResults(List<ScanResult> results) { super.onBatchScanResults(results); // handles batch scan results for (ScanResult result : results) { // you can iterate through each result like so } } @Override public void onScanFailed(int errorCode) { super.onScanFailed(errorCode); // handles error } }; callback内传递stopScan()

startScan()

也可以考虑使用bluetoothLeScanner.startScan(callback); bluetoothLeScanner.stopScan(callback); ,以便您可以检索所需设备的特定数据,而不是获取大量信息。例如,result.getDevice()仅用于地址。