最初的Android BLE API具有
BluetoothLeScanner
类,该类允许使用以下四种模式之一启动扫描:
-
SCAN_MODE_LOW_LATENCY
扫描是连续的
-
SCAN_MODE_BALANCED
扫描每5秒进行2秒
-
SCAN_MODE_LOW_POWER
扫描每5秒进行0.5秒
-
SCAN_MODE_OPPORTUNISTIC
–只有当不同的应用程序启动扫描时,扫描才起作用
时间测量由Nordic Semiconductors员工执行,并以
comprehensive guide
适用于Android BLE开发者。
这个
RxAndroidBle
图书馆也有一个功能
RxBleClient.scanBleDevices(ScanSettings, ScanFilter...)
在一个
ScanSettings
对象
如果需要获得不同的扫描参数,可以简单地使用以下组合:
Observable.takeUntil()
和
Observable.repeatWhen()
:
Observable<ScanResult> lowLatencyScanObservable = rxBleClient.scanBleDevices(
new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) // make sure that the scanning will be always on by default
.build()
);
Observable<ScanResult> periodicalScan = lowLatencyScanObservable
.takeUntil(Observable.timer(SCAN_TIME, SCAN_TIMEUNIT)) // scan for a specific amount of time and then unsubscribe to the upstream
.repeatWhen(completionObservable -> completionObservable.delay(PAUSE_TIME, PAUSE_TIMEUNIT)); // when the upstream will complete because of `takeUntil()` wait for the pause time and resubscribe to the upstream
人们仍然需要记住API 24+的未记录“功能”,它阻止在30秒内启动5次以上的扫描。