我已经开始扫描BLE设备了这段代码:
Log.i("timeChar", "Begin");
customBluetoothManager.scanLeDevice(true);
然后调用scanLeDevice(),管理蓝牙适配器以启动BLE扫描:
public void scanLeDevice(final boolean enable) {
mHandler = new Handler();
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}, SCAN_PERIOD);
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}
现在,通过扫描找到的每个设备的回调:
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi,
byte[] scanRecord) {
String name = device.getName();
if (name != null && name.compareTo(bluetoothDeviceName) == 0) {
Log.i("timeChar", "Device found");
}
}
};
每次我要扫描我的BLE设备(具有外围设备角色)时,大约需要11秒才能检测到它......
05-31 17:32:39.139 27545-9668/app I/timeChar: Begin
05-31 17:32:50.149 27545-27545/app I/timeChar: Device found
有没有办法减少这个时间?
答案 0 :(得分:0)
BLE扫描和设备广告每隔一段时间完成一次。如果广告之间的间隔很长,让我们说一秒,那么android可能会错过它。为了从应用程序端修复此问题:
//global ScanSettings settings;
ScanSettings.Builder settingBuilder = new ScanSettings.Builder();
settingBuilder.setScanMode(SCAN_MODE_LOW_LATENCY);
settings = settingBuilder.build();
您稍后将其传递给扫描方法
mBluetoothAdapter.getBluetoothLeScanner().startScan(null, settings, mLeScanCallback);
答案 1 :(得分:0)
为了做到这一点,你应该考虑到:
在BLE信标中设置的定义间隔。为了节省电量,您可以定义BLE信标发送的每个数据包之间的时间间隔(从100毫秒到几秒)。因此,首先检查您的信标的时间间隔。
Android OS中设置的时间,表示您已收到新数据包(回调函数)。如Marcin所示,您可以这样做:
scanSettings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY ).build();