首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >RxAndroidBle -自动连接问题

RxAndroidBle -自动连接问题
EN

Stack Overflow用户
提问于 2017-12-06 09:23:33
回答 1查看 1.9K关注 0票数 2

我正在使用RxAndroidBle库:

此代码正常工作,点击UI上的Connect按钮,就可以建立连接。

当我想要在设备返回范围时自动连接到设备上时,问题就出现了。我不想再点击连接按钮了。

有这样的功能存在吗?“真”标志在这里能帮助我吗?如果是,如何实现?请给我建议。rxBleDevice.establishConnection(true);

如果我使用的是rxBleDevice.establishConnection(true),而不是“false”,请帮助:

代码语言:javascript
复制
RxBleLog.setLogLevel(RxBleLog.VERBOSE);
scanSubscription = rxBleClient.scanBleDevices(
        new ScanSettings.Builder()
                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
                .build(),
        new ScanFilter.Builder().setDeviceName("mydevice").build()
).take(1).subscribe(
        scanResult -> {
                final RxBleDevice rxBleDevice = scanResult.getBleDevice();
                // connect to device
                final Observable<RxBleConnection> connection = rxBleDevice.establishConnection(false);
                connection
                        .subscribe(rxBleConnection -> {
                                    DeviceInformation deviceInformation = new DeviceInformation();
                                    deviceInformation.setName(rxBleDevice.getName());
                                    scanSubscription.unsubscribe();
                                },
                                throwable -> {
                                    throwable.printStackTrace();
                                    System.out.println(throwable);
                                }

                        );
        }
);


false
------

D/RxBle#ClientOperationQueue:   QUEUED ScanOperationApi21(226148850)
D/RxBle#ClientOperationQueue:  STARTED ScanOperationApi21(226148850)
I/Choreographer: Skipped 240 frames!  The application may be doing too much work on its main thread.
I/RxBle#QueueOperation: Scan operation is requested to start.
D/BluetoothLeScanner: onClientRegistered() - status=0 clientIf=6
D/RxBle#ClientOperationQueue: FINISHED ScanOperationApi21(226148850)
D/BluetoothLeScanner: onScanResult() - ScanResult{mDevice=6F:AE:DE:3E:2E:C3, mScanRecord=ScanRecord [mAdvertiseFlags=26, mServiceUuids=[00001805], mManufacturerSpecificData={}, mServiceData={}, mTxPowerLevel=-2147483648, mDeviceName=101-1], mRssi=-92, mTimestampNanos=1043849718860030}
D/RxBle#ClientOperationQueue:   QUEUED ConnectOperation(890174706)
D/RxBle#ClientOperationQueue:  STARTED ConnectOperation(890174706)
V/RxBle#BleConnectionCompat: Connecting without reflection
D/BluetoothGatt: connect() - device: 6F:AE:DE:3E:2E:C3, auto: false
D/BluetoothGatt: registerApp()
D/BluetoothGatt: registerApp() - UUID=542bd417
D/BluetoothGatt: onClientRegistered() - status=0 clientIf=7
D/BluetoothGatt: onClientConnectionState() - status=0 clientIf=7 device=6F:AE:DE:3E:2E:C3
D/RxBle#BluetoothGatt: onConnectionStateChange newState=2 status=0
D/RxBle#ClientOperationQueue: FINISHED ConnectOperation(890174706)
I/RxBle#CancellableSubscription: Scan operation is requested to stop.
D/RxBle#ConnectionOperationQueue:   QUEUED ServiceDiscoveryOperation(888759094)
D/RxBle#ConnectionOperationQueue:  STARTED ServiceDiscoveryOperation(888759094)
D/BluetoothGatt: discoverServices() - device: 6F:AE:DE:3E:2E:C3
D/BluetoothGatt: onSearchComplete() = Device=6F:AE:DE:3E:2E:C3 Status=0
D/RxBle#BluetoothGatt: onServicesDiscovered status=0
D/BluetoothGatt: setCharacteristicNotification() - uuid: b31e89de enable: true
D/RxBle#ConnectionOperationQueue: FINISHED ServiceDiscoveryOperation(888759094)


true
------
D/RxBle#ClientOperationQueue:   QUEUED ScanOperationApi21(226148850)
D/RxBle#ClientOperationQueue:  STARTED ScanOperationApi21(226148850)
I/Choreographer: Skipped 207 frames!  The application may be doing too much work on its main thread.
I/RxBle#QueueOperation: Scan operation is requested to start.
D/BluetoothLeScanner: onClientRegistered() - status=0 clientIf=6
D/RxBle#ClientOperationQueue: FINISHED ScanOperationApi21(226148850)
D/BluetoothLeScanner: onScanResult() - ScanResult{mDevice=6F:AE:DE:3E:2E:C3, mScanRecord=ScanRecord [mAdvertiseFlags=26, mServiceUuids=[00001805], mManufacturerSpecificData={}, mServiceData={}, mTxPowerLevel=-2147483648, mDeviceName=101-1], mRssi=-81, mTimestampNanos=1043935540628438}
D/RxBle#ClientOperationQueue:   QUEUED ConnectOperation(890174706)
D/RxBle#ClientOperationQueue:  STARTED ConnectOperation(890174706)
V/RxBle#ConnectOperation: Trying to connectGatt using reflection.
V/RxBle#BleConnectionCompat: Found constructor with args count = 4
V/RxBle#BleConnectionCompat: Connecting using reflection
D/BluetoothGatt: connect() - device: 6F:AE:DE:3E:2E:C3, auto: true
D/BluetoothGatt: registerApp()
D/BluetoothGatt: registerApp() - UUID=125a849aa38e
D/BluetoothGatt: onClientRegistered() - status=0 clientIf=7
D/BluetoothGatt: onClientConnectionState() - status=6 clientIf=7 device=6F:AE:DE:3E:2E:C3
D/RxBle#BluetoothGatt: onConnectionStateChange newState=0 status=6
W/System.err: BleDisconnectedException{bluetoothDeviceAddress='6F:AE:DE:3E:2E:C3'}
W/System.err:     at com.polidea.rxandroidble.internal.connection.RxBleGattCallback$2.onConnectionStateChange(RxBleGattCallback.java:76)
W/System.err:     at android.bluetooth.BluetoothGatt$1.onClientConnectionState(BluetoothGatt.java:181)
W/System.err:     at android.bluetooth.IBluetoothGattCallback$Stub.onTransact(IBluetoothGattCallback.java:70)
W/System.err:     at android.os.Binder.execTransact(Binder.java:446)
I/System.out: BleDisconnectedException{bluetoothDeviceAddress='6F:AE:DE:3E:2E:C3'}
I/RxBle#ConnectionOperationQueue: Connection operations queue to be terminated (6F:AE:DE:3E:2E:C3)
D/RxBle#Executors$RunnableAdapter: Terminated.
D/RxBle#ClientOperationQueue:   QUEUED DisconnectOperation(550952755)
D/RxBle#ClientOperationQueue: FINISHED ConnectOperation(890174706)
D/RxBle#ClientOperationQueue:  STARTED DisconnectOperation(550952755)
D/BluetoothManager: getConnectionState()
D/BluetoothManager: getConnectedDevices
D/BluetoothGatt: close()
D/BluetoothGatt: unregisterApp() - mClientIf=7
D/RxBle#ClientOperationQueue: FINISHED DisconnectOperation(550952755)-
EN

回答 1

Stack Overflow用户

发布于 2017-12-28 11:29:51

有多种可能的解决方案来实现预期的行为,因此操作将在第一次单击Connect按钮时开始,如果连接丢失,则在没有用户交互的情况下重新连接。

你主要想要的是:

  1. 扫描单个设备
  2. 当设备被扫描时-连接到它
  3. 当连接-做你的东西
  4. 如果发生错误-重试连接

如果由于适配器关闭而导致断开连接,则需要先扫描设备以解决 being switched on问题。在这种情况下,我们将完成一部分流程,并从头开始重复。

代码语言:javascript
复制
Observable<Boolean> canUseBleObservable = canUseBle();
subscription = scanSingleDevice() // first scan the device
        .flatMapObservable(this::connectAndDoStuff) // when scanned connect and do your stuff
        .takeUntil(canUseBleObservable.takeFirst(isReady -> !isReady)) // if the BLE will be not ready (off) then unsubscribe from scanning and connecting
        .delaySubscription(canUseBleObservable.takeFirst(isReady -> isReady)) // delay subscription to scanning and connecting till BLE is ready (subscribing goes from bottom to top)
        .retry() // if scan will emit an error (connection should not as it has `.retry()`) just resubscribe to the upstream
        .repeatWhen(observable -> observable) // if the upstream will complete (due to `.takeUntil()` as `connectAndDoStuff` does not complete on it's own)—resubscribe to the upstream
        .subscribe(
                aVoid -> { /* consume */ } // `aVoid` should be changed to your model/events emitted by `.connectAndDoStuff`
                // throwable -> {  } => should not happen since there is `retry()` in the upstream
        );

其他构建块可能如下所示:

代码语言:javascript
复制
private Observable<Boolean> canUseBle() {
    return rxBleClient.observeStateChanges()
            .share() // share observing state changes
            .startWith(Observable.fromCallable(() -> rxBleClient.getState())) // on each subscription emit the current state
            .map(state -> state == RxBleClient.State.READY); // map to `true` when ready
}

private Single<RxBleDevice> scanSingleDevice() {
    return rxBleClient.scanBleDevices( // scan the device
            new ScanSettings.Builder().build(),
            new ScanFilter.Builder().setDeviceName("mydevice").build()
    )
            .map(ScanResult::getBleDevice)
            .take(1) // after the first device being scanned stop the scan
            .toSingle();
}

private Observable<Void> connectAndDoStuff(RxBleDevice rxBleDevice) {
    return rxBleDevice.establishConnection(false)
            .flatMap(rxBleConnection -> {
                // do your stuff
                return Observable.<Void>empty();
            })
            .repeat(); // if any error (going out of range) will happen then resubscribe from `.establishConnection()`
}

这是对用例的简单分解。如果需要的话,可能会使流动变得更加复杂。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47670741

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档