google / mobly-bundled-snippets

Snippets to allow Mobly tests to control Android devices by exposing a simplified Android API.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Bluetooth pairing fails when using two android devices

aglogger opened this issue · comments

When using btPairDevice(), the PairingBroadcastReceiver (automatic pairing confirmation) is only registered for the device from which the paring request is started. However, since the corresponding confirmation, for successful pairing must be confirmed on both devices, the PairingBroadcastReceiver must also be registered for the second device.

@Rpc(description = "Pair with a bluetooth device.")
public void btPairDevice(String deviceAddress) throws Throwable {
BluetoothDevice device = mDiscoveryResults.get(deviceAddress);
if (device == null) {
throw new NoSuchElementException(
"No device with address "
+ deviceAddress
+ " has been discovered. Cannot proceed.");
}
mContext.registerReceiver(
new PairingBroadcastReceiver(mContext), PairingBroadcastReceiver.filter);
if (!(boolean) Utils.invokeByReflection(device, "createBond")) {
throw new BluetoothAdapterSnippetException(
"Failed to initiate the pairing process to device: " + deviceAddress);
}
if (!Utils.waitUntil(() -> device.getBondState() == BluetoothDevice.BOND_BONDED, 120)) {
throw new BluetoothAdapterSnippetException(
"Failed to pair with device " + deviceAddress + " after 2min.");
}
}

My solution for this problem was implementing a additional Rpc-function which is only used to register the broadcast receiver for any device as required.

public void btStartPairingBroadcastReceiver () {
    mContext.registerReceiver(new PairingBroadcastReceiver(mContext), PairingBroadcastReceiver.filter);
}