calling connectGatt() and createBond() together

1.8k Views Asked by At

I'm trying to create a bond between my Android phone and my device. Before they were connected well by calling device.connectGatt() with my gattCallback. But now as I want to also want to add bonding by calling device.createBond(), my onConnectionStateChange shows an alternate pattern of connected and disconnected with the status code 0 when connected and 8 when disconnected. Here is my snippet of code of how I'm trying to use connectGatt and createBond together.

    @Override
    public void onScanResult(int callbackType, ScanResult result) {
        System.out.println("on scan result");
        super.onScanResult(callbackType, result);
        BluetoothDevice device = result.getDevice();
        synchronized (this) {
            if (mBluetoothGatt == null) {
                if (device.createBond()) {
                    System.out.println("create bond success");
                    mBluetoothGatt = device.connectGatt(mListener.retrieveApplicationContext(), true, mGattCallback);
                }
                else System.out.println("create bond sb");
            }
        }
    }

Is there anything wrong by calling these two methods in this way? I searched the internet for creating bonds but none of the pages uses createBond and connectGatt together. I only got a hint from this post about how to call these two methods this way: Android BLE onCharacteristicChanged() using notify not triggered

Also, my BroadCastReceiver always shows device bonding as well but never shows device bonded.

1

There are 1 best solutions below

4
Emil On

The createBond method will internally first connect to the device if not connected using autoConnect set to false. That means the bonding attempt will be aborted after 30 seconds if the device never connects successfully during that time. But you connect using autoConnect set to true, which means no timeout. So if it for some reason takes 31 seconds to connect, the bonding will not happen.

If I were you, I'd first connect the device myself, and when the device has successfully connected and services discovered (and checked that it has the desired services), call createBond, to make sure everything seems right before bonding.

Status code 8 means "Connection Timeout". This means the connection was up and running but dropped unexpectedly on the radio level, which is not a software error, but something that happens naturally as you go out of range but also due to bad hw such as buggy firmware or bad crystal clock frequency.