1

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?

Lechucico
  • 1,914
  • 7
  • 27
  • 60

1 Answers1

2

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() {
                        @Override
                        public void onConnectionStateChange(BluetoothGatt 
                               gatt, int status, int newState) {
                            super.onConnectionStateChange(gatt, status, newState);
                            switch (newState) {
                                case BluetoothProfile.STATE_CONNECTED:
                                    Log.i("GattCallback", "connected");
                                    gatt.getServices();
                                    break;
                                case BluetoothProfile.STATE_DISCONNECTED:
                                    Log.i("GattCallback", "Disconnected");
                                    break;
                            }
                        }
                    });
                }
            }

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

Salman Naseem
  • 462
  • 4
  • 17
  • Thanks! I've posted another question with more doubts: https://stackoverflow.com/questions/48810469/ble-receiving-gatt-notifications-from-a-characteristic – Lechucico Feb 15 '18 at 15:14
  • 1
    sorry, i dont know why the address when i startLeScan is "D7:1E:5E:34:74:D1", but after connected to this device + getBondedDevices(), i got "66:F2:24:55:5E:A8" – famfamfam Feb 16 '20 at 08:58