bluetoothAdapter.enable() reConnect() }else{//蓝牙正常,开始扫描 bluetoothLeScanner = bluetoothAdapter.bluetoothLeScanner // Android5.0新增的扫描API,扫描返回的结果更友好,比如BLE广播数据以前是byte [] scanRecord,而新API帮我们解析成ScanRecord类 bluetoothLeScanner.startScan(mScanCallback) Thread(Runnable { Thread.sleep(5000) bluetoothLeScanner.stopScan 核心代码: bluetoothLeScanner = bluetoothAdapter.bluetoothLeScanner bluetoothLeScanner.startScan(mScanCallback
每当扫描到附近ble设备并进行回调时都会报错,根本获取不了扫描的结果,报错如下: D/BluetoothLeScanner: onClientRegistered() - status=0 clientIf android.bluetooth.IBluetoothGatt$Stub$Proxy.startScan(IBluetoothGatt.java:772) at android.bluetooth.le.BluetoothLeScanner $BleScanCallbackWrapper.onClientRegistered(BluetoothLeScanner.java:324) at android.bluetooth.IBluetoothGattCallback
bluetoothLeScanner?. bluetoothLeScanner?. bluetoothLeScanner?.
可能无法使用新 API(如 BluetoothLeScanner 需要 API 21+)。但可以覆盖更多老旧设备(如 Android 4.4)。(3)快应用(Quick App)是否需要特殊设置?
ScanLeDeviceAsync() { //第一个参数可以设置过滤条件-蓝牙名称,名称前缀,服务号等,这里暂时不设置过滤条件 _bluetoothAdapter.BluetoothLeScanner.StartScan => { _callback.WaitOne(); }); _bluetoothAdapter.BluetoothLeScanner.StopScan
如果应用需要重新连接至设备,请调用 BluetoothLeScanner 中接受 PendingIntent 参数的 startScan 方法,当过滤条件满足时会被触发。
三、做低功耗蓝牙应用的细节 ① BluetoothLeScanner ② ScanCallback ③ ScanResult ④ BluetoothGatt ⑤ BluetoothGattCallback 首先要扫描到蓝牙设备,这个地方你可以 ① BluetoothLeScanner 这个类提供对蓝牙 LE 设备执行扫描相关操作的方法。
或 ACCESS_COARSE_LOCATION BluetoothDevice.ACTION_FOUND ACCESS_FINE_LOCATION 或 ACCESS_COARSE_LOCATION BluetoothLeScanner.startScan
替换方法是: BluetoothLeScanner scanner = bluetoothAdapter.getBluetoothLeScanner(); //不进行权限验证 ScanCallback PS:不管是BluetoothLeScanner 还是bluetoothAdapter.startDiscovery() 去查找蓝牙设备。都不建议一直重复扫描。
BluetoothAdapter 映射了设备的蓝牙模块,通过BluetoothManager来获取,但其最终还是调用BluetoothAdapter.getDefaultAdapter()获取的 2 BluetoothLeScanner
bluetoothLeScanner if (bleScanner == null) { Log.e("Bluetooth", "设备不支持 BLE") bluetoothLeScanner ?
= null private var mScanner: BluetoothLeScanner? bluetoothLeScanner } } } } /** * 设置扫描过滤 */ bluetoothLeScanner if (!mBluetoothAdapter!!. return } if (mScanner == null) { localScanFailed("BluetoothLeScanner is Null
bluetoothLeScanner ?
mHandler.postDelayed(() -> { mReconnectCount++; // 动态调整扫描策略 BluetoothLeScanner
为了在没有筛选器的情况下使用 BluetoothLeScanner ,您必须通过在应用程序的清单文件中声明 ACCESS_COARSE_LOCATION 或 ACCESS_FINE_LOCATION 权限来请求用户的权限
private lateinit var mBluetoothAdapter: BluetoothAdapter //扫描者 private lateinit var scanner: BluetoothLeScanner
MainActivity.class.getSimpleName(); //获取系统蓝牙适配器 private BluetoothAdapter mBluetoothAdapter; //扫描者 private BluetoothLeScanner