How to connect to a paired BLE device

Lechucico Source

I currently have a device paired to my smartphone (Micro:Bit BBC). My app has to connect to it, reconnect in case it loses connexion and read from one characteristic that this device provides.

I'm new on Android. I've already read this link Android BLE SDK but I can't understand everything and there are some parts from that code that are missing.

I know how to look for paired devices but I don't know what to do after this:

bleAdapter = ((BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter();
Set<BluetoothDevice> pairedDevices = bleAdapter.getBondedDevices();

This shows me the unique device bonded (BBC micro:bit [zogav]). How I can connect to that device, keep the connection alive and reconnect in case the micro:bit gets out of range?



answered 6 months ago Salman Naseem #1

So after getting the Set of Paired Devices, find your device and make connection with it like this:

BluetoothAdapter bleAdapter = ((BluetoothManager) getSystemService(BLUETOOTH_SERVICE)).getAdapter();
            Set<BluetoothDevice> pairedDevices = bleAdapter.getBondedDevices();
            for(BluetoothDevice d: pairedDevices){
                if(d.getAddress().equals("Your Device MAC")){
                   d.connectGatt(MainActivity.this, true, new BluetoothGattCallback() {
                        public void onConnectionStateChange(BluetoothGatt 
                               gatt, int status, int newState) {
                            super.onConnectionStateChange(gatt, status, newState);
                            switch (newState) {
                                case BluetoothProfile.STATE_CONNECTED:
                                    Log.i("GattCallback", "connected");
                                case BluetoothProfile.STATE_DISCONNECTED:
                                    Log.i("GattCallback", "Disconnected");

To achieve Auto Connect set Auto Connect variable true in device.connectGatt(context, Auto Connect, BluetoothGattCallback);.

comments powered by Disqus