Search code examples
androidbluetoothbroadcastreceiverrxandroidble

Why can we pair with the BLE device, without displaying system Dialog, by using BroadcastReceiver?


I'm using RxAndroidBle library to scan and connect with BLE devices. What I also need is to pair with this found device, without displaying system dialog about the key pairing. The bonding mechanism is JustWorks.

I've already achieved that by creating BroadcastReceiver, following the gist I posted below(credits to @dglozano).

Code gist: https://gist.github.com/dglozano/9b0ce38a558eeca16137909bd368698c

It actually works pretty well but I would like to understand why when I'm simply using rxBleDevice.bluetoothDevice.createBond() it displays the Dialog but when I handle it by my own BroadcastReceiver then, it doesn't. Is this someway unregistering normal BroadcastReceiver that would handle device BOND_STATE? Why my BroadcastReceiver takes main control of that? I'm interested in - what happens inside when I'm registering my own receiver.


Solution

  • Okay, I figured it out.

    My first impression that this BroadcastReceiver handles this system Dialog was wrong. We use this Receiver only to double-check BOUND_STATE. It has nothing to do with pairing dialog, this assumption was a mistake.

    So the first important fact is that only a createBond() method is necessary to pair. The rest is just about establishing it.

    The most important fact is that this is "Just works" pairing method. There we can read about BLE security and about "Just works". As you can read here:

    In this method, the TK is set to 0.

    TK is a Temporary Key. At this moment, let go back for the moment to our Android createBond() method. In the documentation we can read:

    Android system services will handle the necessary user interactions to confirm and complete the bonding process.

    But if it handles user interactions why it doesn't display a dialog? We find the answer when we combine those two things together. When Temporary Key value is set to 0, then displaying Pairing key dialog isn't necessary for Android handler.

    There are small changes between Bluetooth 4.0/4.1 and Bluetooth 4.2 but it shouldn't have an impact on this behavior. You can read more about it here.

    TL:DR Using "Just works" pairing method means that Temporary Key value is set to 0 which means we don't need it during the pairing process. createBound() method handles only necessary user interactions so when we don't need pairing key, we don't need to interact with a user about it. That's why Dialog isn't being displayed - because it isn't necessary.