Search code examples
androidrx-javarxandroidble

Continue scanning for other BLE devices while connecting to one


I want my app to scan continuously for up to 3 different BLE peripherals (identified by MAC address). When one device is found, I stop scanning for it and connect to it. Code:

static Observable<ScanResult> bleSharedScanner = MyApplication
        .getRxBleClient()
        .scanBleDevices(new ScanSettings.Builder()
                .setScanMode(SCAN_MODE)
                .build())
        .share();

static Observable<ScanResult> device1Scanner = bleSharedScanner
        .filter(scanResult -> scanResult.getBleDevice().getMacAddress().equalsIgnoreCase( device1MacAddress ) 
        );

Code for Device2 and Device3 is the same. Initially I subscribe to all 3 of these device scanners; when I find one of the devices I unsubscribe that subscription—meanwhile the scan for the other two continues.

So far this seems to be working on my test Android phone. But I noticed your response to a previous question: "…stop the scanSubscription before trying to connect—Android sometimes do not handle well scan and connection at the same time."

Is this a common problem? Is there a good workaround? I need to continue scanning for the other devices while interacting with the one found.


Solution

  • My experience shows that at least some Huawei devices have issues when you connect to a peripheral while the scanning is in progress (I confirmed it on P8 Lite and P9) with two different peripherals.

    When the scanning was in progress I was receiving a COMMAND_DISALLOWED for the LE_CREATE_CONNECTION command. Communication between the host and BLE chip was extracted from HCI Snoop Log. The only workaround that worked for me was to stop the scan for a period of establishing the connection.

    We do not have any statistics to prove it - unfortunately.