MarioCas
MarioCas

Reputation: 39

BLE - First connection with app is not working

I'm working with device Texas, for management of the LED, in my custom Android app. The device has enabled the pairing with a default passkey 000000. In my code for app, I have this part of code for reading the paired of device.

    private void getpaireddevices(){
    Set<BluetoothDevice> devicesArray = BluetoothAdapter.getDefaultAdapter().getBondedDevices();
    if(devicesArray.size() > 0) {
        for(BluetoothDevice device : devicesArray) {
            device.getName();
            device.getAddress();
        }
    }
}

In this moment, when I enable the BLE the app found the device, it connect but not works. For this to work I should exit and reconnect with my device. Why?

Upvotes: 0

Views: 553

Answers (1)

Stanley Ko
Stanley Ko

Reputation: 3497

This is possible if the device is already bonded. Call removeBond() method to clear previous bonding state.

device.removeBond();

For check bonding state of BluetoothDevice, use getBondState().

Ble gatt connection success rate is different per device by device. You may need disconnect ble by hidden method, if your connection fails continuously.

Please read this: BLE Device Bonding Remove Automatically in Android

The method unpairDevice() will unpair bluetooth connection.

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

for (BluetoothDevice bt : pairedDevices) {
        if (bt.getName().contains("String you know has to be in device name")) {
            unpairDevice(bt);
        }
}

// Function to unpair from passed in device
private void unpairDevice(BluetoothDevice device) {
    try {

        Method m = device.getClass().getMethod("removeBond", (Class[]) null);
        m.invoke(device, (Object[]) null);
    } catch (Exception e) { Log.e(TAG, e.getMessage()); }
}

Upvotes: 1

Related Questions